Class: Anthemic::Tools::WebSearch

Inherits:
Base
  • Object
show all
Defined in:
lib/anthemic/tools/web_search.rb

Instance Attribute Summary

Attributes inherited from Base

#description, #name

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil) ⇒ WebSearch

Initialize a web search tool

Parameters:

  • api_key (String) (defaults to: nil)

    the API key for the search provider (default: nil, uses configuration)

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/anthemic/tools/web_search.rb', line 9

def initialize(api_key: nil)
  super(
    name: "web_search",
    description: "Search the web for current information"
  )
  
  @api_key = api_key || Anthemic.configuration.api_keys[:google_search]
  
  raise ConfigurationError, "Google Search API key is required for WebSearch tool" unless @api_key
  
  @connection = Faraday.new(url: "https://www.googleapis.com") do |conn|
    conn.request :json
    conn.response :json
    conn.adapter Faraday.default_adapter
  end
end

Instance Method Details

#run(args = {}) ⇒ Array<Hash>

Run a web search

Parameters:

  • query (String)

    the search query

  • num (Integer)

    number of results to return (default: 5)

Returns:

  • (Array<Hash>)

    search results with title, link, and snippet



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
# File 'lib/anthemic/tools/web_search.rb', line 31

def run(args = {})
  query = args[:query] || raise(ArgumentError, "query is required")
  num = args[:num] || 5
  
  response = @connection.get("/customsearch/v1") do |req|
    req.params = {
      key: @api_key,
      cx: Anthemic.configuration.api_keys[:google_cx],
      q: query,
      num: num
    }
  end
  
  if response.status == 200
    results = response.body["items"] || []
    results.map do |item|
      {
        title: item["title"],
        link: item["link"],
        snippet: item["snippet"]
      }
    end
  else
    raise Error, "Google Search API error: #{response.body["error"]["message"]}"
  end
rescue Faraday::Error => e
  raise Error, "Google Search connection error: #{e.message}"
end