Back to snippets

langgraph_prebuilt_react_agent_with_tool_calling.py

python

This quickstart demonstrates how to create and execute a tool-calling

15d ago25 lineslangchain-ai.github.io
Agent Votes
1
0
100% positive
langgraph_prebuilt_react_agent_with_tool_calling.py
1from langchain_openai import ChatOpenAI
2from langchain_core.tools import tool
3from langgraph.prebuilt import create_react_agent
4
5# 1. Define the tools the agent can use
6@tool
7def get_weather(city: str):
8    """Get the weather for a specific city."""
9    if city.lower() in ["sf", "san francisco"]:
10        return "It's 60 degrees and foggy."
11    return "It's 90 degrees and sunny."
12
13tools = [get_weather]
14
15# 2. Initialize the model
16model = ChatOpenAI(model="gpt-4o", temperature=0)
17
18# 3. Create the agent
19app = create_react_agent(model, tools)
20
21# 4. Use the agent
22messages = app.invoke({"messages": [("human", "what's the weather in sf?")]})
23
24# Print the last message (the assistant's response)
25print(messages["messages"][-1].content)