Build a Wikipedia tool
The school administration is quite happy with your work! They would like to make the chatbot even more powerful by incorporating external resources. You suggest equipping the chatbot with access to Wikipedia. The administration agrees to extend your commission, so you decide to build a tool for the chatbot using the Wikipedia API.
The following modules have been imported for you to get started: WikipediaQueryRun
, WikipediaAPIWrapper
This exercise is part of the course
Designing Agentic Systems with LangChain
Exercise instructions
- Create an
api_wrapper
that initializesWikipediaAPIWrapper()
withtop_k_results=1
to fetch only the top Wikipedia result. - Create a
WikipediaQueryRun()
tool calledwikipedia_tool
, passing in theapi_wrapper
as its input before saving it to a list calledtools
. - Bind the
tools
list to thellm
by passing it to the.bind_tools()
method. - To direct the chatbot to respond with the tool, pass the content of
"messages"
instate
to the.invoke()
method and apply it tollm_with_tools
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Initialize Wikipedia API wrapper to fetch top one result
api_wrapper = ____(top_k_results=1)
# Create a Wikipedia query tool using the API wrapper
wikipedia_tool = ____(api_wrapper=____)
tools = [____]
# Bind the Wikipedia tool to the language model
llm_with_tools = ____.____(____)
# Modify chatbot function to respond with Wikipedia
def chatbot(state: State):
return {"messages": [____.____(____["____"])]}