Langchain Agents

Welcome to our latest article on Langchain agents! In this guide, we’ll dive into the innovative approach to building agents introduced in Langchain update 0.1.Â

By leveraging agents, you can significantly enhance the capabilities of the OpenAI API and seamlessly integrate external tools.Â

Interested in discussing a Data or AI project? Feel free to reach out via email or simply complete the contact form on my website.

Install Packages

To execute the code utilized in the tutorial, please pip install the following packages

!pip install duckduckgo-search
!pip install wikipedia
!pip install langchain
!pip install langchainhub
!pip install langchain_openai

You will also need an Open AI API key. If you do not have one, please grab one before moving forward with the article. Simply use the following code once you have a key and replace the YOUR_KEY_GOES_HERE. The key should be in quotes.

import os
os.environ["OPENAI_API_KEY"] = "YOUR_KEY_GOES_HERE"

We will need to import classes and functions from the LangChain and OpenAI Libraries. Let’s start with these 6 to get started.

from langchain_openai import ChatOpenAI
from langchain import hub
from langchain.agents import create_openai_functions_agent
from langchain.agents import AgentExecutor
from langchain.schema import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI

Example 1 - No Agents

In our first example, I’m going to showcase why we need to use Agents with our OpenAI model. One of the biggest drawbacks with using OpenAI is the lack of up to date information. As of early 2024, 2023 news/events haven’t been integrated into GPT-3.5-Turbo.

Being a big baseball fan, let’s find out who won the World Series in 2023.

llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
messages = [
    SystemMessage(
        content="A User will input in a year and you will get the baseball world series champion"
    ),
    HumanMessage(
        content="2023"
    ),
]
llm.invoke(messages)

The output from invoking the model above.

Example 2 - Finding the 2023 World Series Champion

While example 1 showed us the drawback of using GPT-3.5 for up to date information, we can solve this dilemma with the use of agents.

Wikipedia is a great alternative for finding up to date information. Wiki editors are quick to make changes to pages and there are layers of verification. We have to import WikipediaQueryRun and the WikipediaAPIWrapper

from langchain.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper

Next we import in the prompt from a hub. This configures the agent’s behavior.

prompt = hub.pull("hwchase17/openai-functions-agent")

The WikipediaAPIWrapper is instantiated with parameters: top_k_results=1 & doc_content_chars_max=500:

This means it will only return the top result and the length is limited to 500 characters.

api_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=500)
tools = [WikipediaQueryRun(api_wrapper=api_wrapper)]

Next, we create an agent using the function create_openai_functions_agent with three parameters:

  • llm: This is the large language model (not defined in the snippet but assumed to be set up elsewhere).
  • tools: This is the list of tools the agent can use (in this case, the Wikipedia query tool).
  • prompt: The prompt pulled earlier that guides the agent’s behavior.
agent = create_openai_functions_agent(llm, tools, prompt)

AgentExecutor is instantiated with the created agent and the list of tools. This executor is responsible for running the agent.

agent_executor = AgentExecutor(agent=agent, tools=tools)

agent_executor.invoke is called with a dictionary containing the key “input” and the query “Who won the 2023 world series?”.

agent_executor.invoke({"input": "Who won the 2023 world series?"})

The output from invoking the model above. With the use of Wikipedia we now see that the Texas Rangers won the 2023 World Series.

Example 3 Agent with LLM Math and Duck Duck Go

For this example, we are going to add in the additional requirement to see how many years it’s been since a team has won the world series.

Instead of using Wikipedia, we will be looking at using Duck Duck Go.Â

And we will be needing to use LLM Match for the calculation

Start by importing in the required Libraries and Functions in LLMMathChain, Tool, initialize_agent, and DuckDuckGoSearchRun

from langchain import LLMMathChain
from langchain.agents import Tool, initialize_agent
from langchain.tools import DuckDuckGoSearchRun

A Tool is created from the llm_math_chain.run function. This tool is named “Calculator” and is specifically designed to handle math-related queries.

llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)
math_tool = Tool.from_function(
        func=llm_math_chain.run,
        name="Calculator",
        description="Useful for when you need to answer questions about math. This tool is only for math questions and nothing else. Only input math expressions.",
    )

This line initializes an instance of DuckDuckGoSearchRun, which is a tool for performing searches using the DuckDuckGo search engine

search = DuckDuckGoSearchRun()
 

Unlike the earlier example, we will have multiple tools this turn. So add both the math_tool and search the the tools2 list.

tools2 = [math_tool, search]
 

Create an agent using create_openai_functions_agent with the specified llm, the list of tools (tools2), and a previously defined prompt

agent2 = create_openai_functions_agent(llm= llm, tools = tools2, prompt=prompt)
 

AgentExecutor is instantiated with agent2 and tools2. The verbose=True flag enables detailed logging for the executor’s operations

agent_executor2 = AgentExecutor(agent=agent2, tools=tools2, verbose=True)

agent_executor2.invoke is called with a dictionary containing the key “input” and the query “Who won the 2021 world series and how many years was it since their last world series win?”.

agent_executor2.invoke({"input": "Who won the 2021 world series and how many years was it since their last world series win"})

Leave a Reply

Your email address will not be published. Required fields are marked *