21 def search(query, options)
22 api_key = options.api_key || ENV["JINA_API_KEY"]
23 raise Rager::Errors::CredentialsError.new("Jina", env_var: ["JINA_API_KEY"]) if api_key.nil?
24
25 params = {"q" => query}
26
27 headers = {
28 "Accept" => "application/json",
29 "X-Return-Format" => "markdown"
30 }
31
32 headers["Authorization"] = "Bearer #{api_key}" if api_key
33
34 request = Rager::Http::Request.new(
35 verb: Rager::Http::Verb::Get,
36 url: "https://s.jina.ai/?#{URI.encode_www_form(params)}",
37 headers: headers,
38 timeout: options.timeout || Rager.config.timeout
39 )
40
41 response = Rager.config.http_adapter.make_request(request)
42 response_body = T.cast(T.must(response.body), String)
43
44 raise Rager::Errors::HttpError.new(Rager.config.http_adapter, request.url, response.status, body: response_body) if response.status != 200
45
46 parsed_response = JSON.parse(response_body)
47 search_results = parsed_response["data"] || []
48
49 search_results = search_results.first(options.n) if options.n
50
51 urls = search_results.map { |r| r["url"] }
52 titles = search_results.map { |r| r["title"] }
53 contents = search_results.map { |r|
54 content = r["content"] || r["description"]
55 options.max_length ? content&.slice(0, options.max_length) : content
56 }
57
58 Rager::Search::Output.new(
59 urls: urls,
60 titles: titles,
61 contents: contents
62 )
63 end