Get startedGet started for free

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

View Course

Exercise instructions

  • Create an api_wrapper that initializes WikipediaAPIWrapper() with top_k_results=1 to fetch only the top Wikipedia result.
  • Create a WikipediaQueryRun() tool called wikipedia_tool, passing in the api_wrapper as its input before saving it to a list called tools.
  • Bind the tools list to the llm by passing it to the .bind_tools() method.
  • To direct the chatbot to respond with the tool, pass the content of "messages" in state to the .invoke() method and apply it to llm_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": [____.____(____["____"])]}
Edit and Run Code