Class: Boxcars::WikipediaSearch

Inherits:
Boxcar
  • Object
show all
Defined in:
lib/boxcars/boxcar/wikipedia_search.rb

Overview

A Boxcar that uses the Wikipedia search API to get answers to questions.

Constant Summary collapse

WDESC =

the description of this boxcar

"useful for when you need to answer questions about topics from Wikipedia." \
"You should ask targeted questions"

Instance Attribute Summary

Attributes inherited from Boxcar

#description, #name, #parameters, #return_direct

Instance Method Summary collapse

Methods inherited from Boxcar

#apply, assi, #call, #conduct, hist, #input_keys, #load, #output_keys, #save, #schema, syst, user, #validate_inputs, #validate_outputs

Constructor Details

#initialize(name: "Wikipedia", description: WDESC) ⇒ WikipediaSearch

implements a boxcar that uses the Wikipedia Search to get answers to questions.

Parameters:

  • name (String) (defaults to: "Wikipedia")

    The name of the boxcar. Defaults to classname.

  • description (String) (defaults to: WDESC)

    A description of the boxcar. Defaults to SERPDESC.

  • serpapi_api_key (String)

    The API key to use for the SerpAPI. Defaults to Boxcars.configuration.serpapi_api_key.



15
16
17
# File 'lib/boxcars/boxcar/wikipedia_search.rb', line 15

def initialize(name: "Wikipedia", description: WDESC)
  super
end

Instance Method Details

#run(question) ⇒ String

Get an answer from Google using the SerpAPI.

Parameters:

  • question (String)

    The question to ask Google.

Returns:

  • (String)

    The answer to the question.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/boxcars/boxcar/wikipedia_search.rb', line 22

def run(question)
  Boxcars.debug "Question: #{question}", :yellow
  uri = URI("https://en.wikipedia.org/w/api.php")
  params = { action: "query", list: "search", srsearch: question, format: "json" }
  uri.query = URI.encode_www_form(params)

  res = Net::HTTP.get_response(uri)
  raise "Error getting response from Wikipedia: #{res.body}" unless res.is_a?(Net::HTTPSuccess)

  response = JSON.parse res.body
  answer = response.dig("query", "search", 0, "snippet").to_s.gsub(/<[^>]*>/, "")
  pageid = response.dig("query", "search", 0, "pageid")
  answer = "#{answer}\nurl: https://en.wikipedia.org/?curid=#{pageid}" if pageid
  Boxcars.debug "Answer: #{answer}", :yellow, style: :bold
  answer
end