Class: Kodo::Search::Tavily

Inherits:
Base
  • Object
show all
Defined in:
lib/kodo/search/tavily.rb

Constant Summary collapse

API_URL =
'https://api.tavily.com/search'
READ_TIMEOUT =
15
OPEN_TIMEOUT =
10

Instance Method Summary collapse

Constructor Details

#initialize(api_key:) ⇒ Tavily

Returns a new instance of Tavily.



14
15
16
17
# File 'lib/kodo/search/tavily.rb', line 14

def initialize(api_key:)
  super()
  @api_key = api_key
end

Instance Method Details

#search(query, max_results: 5) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
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
# File 'lib/kodo/search/tavily.rb', line 19

def search(query, max_results: 5)
  uri = URI(API_URL)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.read_timeout = READ_TIMEOUT
  http.open_timeout = OPEN_TIMEOUT

  request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
  request.body = JSON.generate(
    api_key: @api_key,
    query: query,
    max_results: max_results,
    include_answer: false
  )

  response = http.request(request)

  unless response.is_a?(Net::HTTPSuccess)
    raise Kodo::Error, "Tavily API error: #{response.code} #{response.message}"
  end

  data = JSON.parse(response.body)
  results = data['results'] || []

  results.map do |r|
    Result.new(
      title: r['title'] || '',
      url: r['url'] || '',
      snippet: r['content'] || '',
      content: r['raw_content']
    )
  end
rescue Net::OpenTimeout, Net::ReadTimeout => e
  raise Kodo::Error, "Tavily API timeout: #{e.message}"
rescue JSON::ParserError => e
  raise Kodo::Error, "Tavily API returned invalid JSON: #{e.message}"
rescue SocketError, Errno::ECONNREFUSED => e
  raise Kodo::Error, "Tavily API connection failed: #{e.message}"
end