Class: Exa::CLI::Formatters::AnswerFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/exa/cli/formatters/answer_formatter.rb

Class Method Summary collapse

Class Method Details

.format(result, format, skip_citations: false) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/exa/cli/formatters/answer_formatter.rb', line 7

def self.format(result, format, skip_citations: false)
  case format
  when "json"
    format_json(result, skip_citations: skip_citations)
  when "pretty"
    format_pretty(result, skip_citations: skip_citations)
  when "text"
    format_text(result)
  when "toon"
    Exa::CLI::Base.encode_as_toon(result.to_h)
  else
    format_json(result, skip_citations: skip_citations)
  end
end

.format_json(result, skip_citations: false) ⇒ Object



24
25
26
27
28
# File 'lib/exa/cli/formatters/answer_formatter.rb', line 24

def self.format_json(result, skip_citations: false)
  hash = result.to_h
  hash.delete(:citations) if skip_citations
  JSON.pretty_generate(hash)
end

.format_pretty(result, skip_citations: false) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/exa/cli/formatters/answer_formatter.rb', line 30

def self.format_pretty(result, skip_citations: false)
  output = []
  output << "Answer:"
  output << "-" * 60

  # Handle both string and structured (hash) answers
  if result.answer.is_a?(Hash)
    output << JSON.pretty_generate(result.answer)
  else
    output << result.answer
  end
  output << ""

  unless skip_citations
    if result.citations && !result.citations.empty?
      output << "Citations:"
      output << "-" * 60
      result.citations.each_with_index do |citation, idx|
        output << "[#{idx + 1}] #{citation['title']}"
        output << "    URL:      #{citation['url']}"
        output << "    Author:   #{citation['author']}" if citation['author']
        output << "    Date:     #{citation['publishedDate']}" if citation['publishedDate']
        output << ""
      end
    end
  end

  output << "Cost: $#{result.cost_dollars}" if result.cost_dollars

  output.join("\n")
end

.format_text(result) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/exa/cli/formatters/answer_formatter.rb', line 62

def self.format_text(result)
  # Handle both string and structured (hash) answers
  if result.answer.is_a?(Hash)
    JSON.pretty_generate(result.answer)
  else
    result.answer
  end
end