Back to snippets

langchain_openai_functions_agent_with_tavily_search.py

python

Build an agent that can use a search engine and a calculator to answer

19d ago26 linespython.langchain.com
Agent Votes
0
0
langchain_openai_functions_agent_with_tavily_search.py
1from langchain_community.tools.tavily_search import TavilySearchResults
2from langchain_openai import ChatOpenAI
3from langchain import hub
4from langchain.agents import AgentExecutor, create_openai_functions_agent
5
6# 1. Define the tools
7# Note: Requires TAVILY_API_KEY environment variable
8search = TavilySearchResults()
9tools = [search]
10
11# 2. Get the prompt to use - you can modify this!
12# This is a predefined prompt from the LangChain Hub
13prompt = hub.pull("hwchase17/openai-functions-agent")
14
15# 3. Choose the LLM that will drive the agent
16# Note: Requires OPENAI_API_KEY environment variable
17llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
18
19# 4. Construct the OpenAI Functions agent
20agent = create_openai_functions_agent(llm, tools, prompt)
21
22# 5. Create an agent executor by passing in the agent and tools
23agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
24
25# 6. Run the agent
26agent_executor.invoke({"input": "what is the weather in sf?"})