Files
langgraph/examples/agent_executor/high-level.ipynb
T
2024-02-15 23:09:59 -08:00

17 KiB

Agent Executor

This notebook walks through an example creating an agent executor to work with an existing LangChain agent. This is useful for getting started quickly. However, it is highly likely you will want to customize the logic - for information on that, check out the other examples in this folder.

Setup

First we need to install the packages required

In [ ]:
!pip install --quiet -U langchain langchain_openai tavily-python

Next, we need to set API keys for OpenAI (the LLM we will use) and Tavily (the search tool we will use)

In [ ]:
import os
import getpass

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
os.environ["TAVILY_API_KEY"] = getpass.getpass("Tavily API Key:")

Optionally, we can set API key for LangSmith tracing, which will give us best-in-class observability.

In [ ]:
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = getpass.getpass("LangSmith API Key:")

Set up LangChain Agent

First, will set up our LangChain Agent. See documentation here for more information on what these agents are and how to think about them

In [2]:
from langchain_openai import ChatOpenAI
from langchain import hub
from langchain.agents import create_openai_functions_agent
from langchain_community.tools.tavily_search import TavilySearchResults
In [3]:
tools = [TavilySearchResults(max_results=1)]

# Get the prompt to use - you can modify this!
prompt = hub.pull("hwchase17/openai-functions-agent")

# Choose the LLM that will drive the agent
llm = ChatOpenAI(model="gpt-3.5-turbo-1106")

# Construct the OpenAI Functions agent
agent_runnable = create_openai_functions_agent(llm, tools, prompt)

Create agent executor

Now we will use the high level method to create the agent executor

In [4]:
from langgraph.prebuilt import create_agent_executor
In [5]:
app = create_agent_executor(agent_runnable, tools)
In [6]:
inputs = {"input": "what is the weather in sf", "chat_history": []}
for s in app.stream(inputs):
    print(list(s.values())[0])
    print("----")
{'agent_outcome': AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'current weather in San Francisco'}, log="\nInvoking: `tavily_search_results_json` with `{'query': 'current weather in San Francisco'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"current weather in San Francisco"}', 'name': 'tavily_search_results_json'}})])}
----
{'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'current weather in San Francisco'}, log="\nInvoking: `tavily_search_results_json` with `{'query': 'current weather in San Francisco'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"current weather in San Francisco"}', 'name': 'tavily_search_results_json'}})]), "[{'url': 'https://en.climate-data.org/north-america/united-states-of-america/california/san-francisco-385/t/january-1/', 'content': 'San Francisco Weather in January  you can find all information about the weather in San Francisco in January:  San Francisco weather in January San Francisco weather by month // weather averages 9.6 (49.2) 6.2 (43.2) 14 (57.3) 113  San Francisco weather in January // weather averages Airport close to San FranciscoWeather ☀ ⛅ San Francisco ☀ ⛅ January ☀ ⛅ Information on temperature, sunshine hours, water temperature & rainfall in January for San Francisco. ... Are you planning a holiday with hopefully nice weather in San Francisco in January 2024? Here you can find all information about the weather in San Francisco in January: ... 15. January ...'}]")]}
----
{'agent_outcome': AgentFinish(return_values={'output': "I couldn't find the current weather in San Francisco. However, you can visit a reliable weather website or check a weather app for the most up-to-date information."}, log="I couldn't find the current weather in San Francisco. However, you can visit a reliable weather website or check a weather app for the most up-to-date information.")}
----
{'input': 'what is the weather in sf', 'chat_history': [], 'agent_outcome': AgentFinish(return_values={'output': "I couldn't find the current weather in San Francisco. However, you can visit a reliable weather website or check a weather app for the most up-to-date information."}, log="I couldn't find the current weather in San Francisco. However, you can visit a reliable weather website or check a weather app for the most up-to-date information."), 'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'current weather in San Francisco'}, log="\nInvoking: `tavily_search_results_json` with `{'query': 'current weather in San Francisco'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"current weather in San Francisco"}', 'name': 'tavily_search_results_json'}})]), "[{'url': 'https://en.climate-data.org/north-america/united-states-of-america/california/san-francisco-385/t/january-1/', 'content': 'San Francisco Weather in January  you can find all information about the weather in San Francisco in January:  San Francisco weather in January San Francisco weather by month // weather averages 9.6 (49.2) 6.2 (43.2) 14 (57.3) 113  San Francisco weather in January // weather averages Airport close to San FranciscoWeather ☀ ⛅ San Francisco ☀ ⛅ January ☀ ⛅ Information on temperature, sunshine hours, water temperature & rainfall in January for San Francisco. ... Are you planning a holiday with hopefully nice weather in San Francisco in January 2024? Here you can find all information about the weather in San Francisco in January: ... 15. January ...'}]")]}
----
In [18]:
s["__end__"]["agent_outcome"]
Out [18]:
AgentFinish(return_values={'output': "I couldn't find the current weather in San Francisco. However, you can check the weather on a reliable weather website or using a weather app for the most up-to-date information."}, log="I couldn't find the current weather in San Francisco. However, you can check the weather on a reliable weather website or using a weather app for the most up-to-date information.")

Custom Input Schema

By default, the create_agent_executor assumes that the input will be a dictionary with two keys: input and chat_history. If this is not the case, you can easily customize the input schema. You should do this, by defining a schema as a TypedDict.

For this example, we will create a new agent that expects question and language as inputs.

Create New Agent

In [7]:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "human",
            "Respond to the user question: {question}. Answer in this language: {language}",
        ),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ]
)
agent_runnable = create_openai_functions_agent(llm, tools, prompt)

Define Input Schema

In [8]:
from typing import TypedDict
In [9]:
class InputSchema(TypedDict):
    question: str
    language: str

Create new agent executor

In [10]:
app = create_agent_executor(agent_runnable, tools, input_schema=InputSchema)
In [11]:
inputs = {"question": "what is the weather in sf", "language": "italian"}
for s in app.stream(inputs):
    print(list(s.values())[0])
    print("----")
{'agent_outcome': AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'che tempo fa a sf'}, log="\nInvoking: `tavily_search_results_json` with `{'query': 'che tempo fa a sf'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"che tempo fa a sf"}', 'name': 'tavily_search_results_json'}})])}
----
{'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'che tempo fa a sf'}, log="\nInvoking: `tavily_search_results_json` with `{'query': 'che tempo fa a sf'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"che tempo fa a sf"}', 'name': 'tavily_search_results_json'}})]), '[{\'url\': \'https://www.mxbars.net/2024/01/14/san-francisco-supercross-2024-results-and-points-video/\', \'content\': "Scritto domenica 14 Gennaio 2024 alle 04:38. SAN FRANCISCO Oracle Park, CA January 13, 2024  sera gli orari sono anticipati di due ore causa mal tempo per non compromettere lo spettacolo!  secondo weekend con la seconda tappa e pista molto tecnica per San Francisco dove sta piovendo e lo stadio aperto non  . Commenta la gara\\xa0CLICCANDO\\xa0il link! http://forum.mxbars.net/viewtopic.php?f=18&t=50182SAN FRANCISCO. Oracle Park, CA. January 13, 2024. Ecco che la NUOVA stagione del Monster Energy Supercross 2024 continua, dopo Anaheim 1 si passa al secondo weekend con la seconda tappa e pista molto tecnica per San Francisco dove sta piovendo e lo stadio aperto non vede possibilità di chiudersi, per la lotta nella 450 dove sono tutti agguerriti e quest\'anno il livello è ancora più alto ..."}]')]}
----
{'agent_outcome': AgentFinish(return_values={'output': 'Al momento sta piovendo a San Francisco.'}, log='Al momento sta piovendo a San Francisco.')}
----
{'question': 'what is the weather in sf', 'language': 'italian', 'agent_outcome': AgentFinish(return_values={'output': 'Al momento sta piovendo a San Francisco.'}, log='Al momento sta piovendo a San Francisco.'), 'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'che tempo fa a sf'}, log="\nInvoking: `tavily_search_results_json` with `{'query': 'che tempo fa a sf'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"che tempo fa a sf"}', 'name': 'tavily_search_results_json'}})]), '[{\'url\': \'https://www.mxbars.net/2024/01/14/san-francisco-supercross-2024-results-and-points-video/\', \'content\': "Scritto domenica 14 Gennaio 2024 alle 04:38. SAN FRANCISCO Oracle Park, CA January 13, 2024  sera gli orari sono anticipati di due ore causa mal tempo per non compromettere lo spettacolo!  secondo weekend con la seconda tappa e pista molto tecnica per San Francisco dove sta piovendo e lo stadio aperto non  . Commenta la gara\\xa0CLICCANDO\\xa0il link! http://forum.mxbars.net/viewtopic.php?f=18&t=50182SAN FRANCISCO. Oracle Park, CA. January 13, 2024. Ecco che la NUOVA stagione del Monster Energy Supercross 2024 continua, dopo Anaheim 1 si passa al secondo weekend con la seconda tappa e pista molto tecnica per San Francisco dove sta piovendo e lo stadio aperto non vede possibilità di chiudersi, per la lotta nella 450 dove sono tutti agguerriti e quest\'anno il livello è ancora più alto ..."}]')]}
----
In [25]:
s["__end__"]["agent_outcome"]
Out [25]:
AgentFinish(return_values={'output': 'Il clima a San Francisco durante il mese di gennaio è generalmente fresco con temperature medie di circa 9.6°C (49.2°F) e massime di 14°C (57.3°F). Si consiglia di prepararsi a temperature fresche se si pianifica una visita a San Francisco in gennaio.'}, log='Il clima a San Francisco durante il mese di gennaio è generalmente fresco con temperature medie di circa 9.6°C (49.2°F) e massime di 14°C (57.3°F). Si consiglia di prepararsi a temperature fresche se si pianifica una visita a San Francisco in gennaio.')
In [ ]: