mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
26 KiB
26 KiB
In [1]:
%%capture --no-stderr
%pip install --quiet -U langgraph langchain_anthropicIn [ ]:
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("ANTHROPIC_API_KEY")In [3]:
from langchain_core.messages import AIMessage
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNodeIn [4]:
@tool
def get_weather(location: str):
"""Call to get the current weather."""
if location.lower() in ["sf", "san francisco"]:
return "It's 60 degrees and foggy."
else:
return "It's 90 degrees and sunny."
@tool
def get_coolest_cities():
"""Get a list of coolest cities"""
return "nyc, sf"In [5]:
tools = [get_weather, get_coolest_cities]
tool_node = ToolNode(tools)In [6]:
message_with_single_tool_call = AIMessage(
content="",
tool_calls=[
{
"name": "get_weather",
"args": {"location": "sf"},
"id": "tool_call_id",
"type": "tool_call",
}
],
)
tool_node.invoke({"messages": [message_with_single_tool_call]})Out [6]:
{'messages': [ToolMessage(content="It's 60 degrees and foggy.", name='get_weather', tool_call_id='tool_call_id')]}In [7]:
message_with_multiple_tool_calls = AIMessage(
content="",
tool_calls=[
{
"name": "get_coolest_cities",
"args": {},
"id": "tool_call_id_1",
"type": "tool_call",
},
{
"name": "get_weather",
"args": {"location": "sf"},
"id": "tool_call_id_2",
"type": "tool_call",
},
],
)
tool_node.invoke({"messages": [message_with_multiple_tool_calls]})Out [7]:
{'messages': [ToolMessage(content='nyc, sf', name='get_coolest_cities', tool_call_id='tool_call_id_1'),
ToolMessage(content="It's 60 degrees and foggy.", name='get_weather', tool_call_id='tool_call_id_2')]}In [8]:
from typing import Literal
from langchain_anthropic import ChatAnthropic
from langgraph.graph import StateGraph, MessagesState
from langgraph.prebuilt import ToolNode
model_with_tools = ChatAnthropic(
model="claude-3-haiku-20240307", temperature=0
).bind_tools(tools)In [9]:
model_with_tools.invoke("what's the weather in sf?").tool_callsOut [9]:
[{'name': 'get_weather',
'args': {'location': 'San Francisco'},
'id': 'toolu_01Fwm7dg1mcJU43Fkx2pqgm8',
'type': 'tool_call'}]In [10]:
tool_node.invoke({"messages": [model_with_tools.invoke("what's the weather in sf?")]})Out [10]:
{'messages': [ToolMessage(content="It's 60 degrees and foggy.", name='get_weather', tool_call_id='toolu_01LFvAVT3xJMeZS6kbWwBGZK')]}In [11]:
from typing import Literal
from langgraph.graph import StateGraph, MessagesState
def should_continue(state: MessagesState) -> Literal["tools", "__end__"]:
messages = state["messages"]
last_message = messages[-1]
if last_message.tool_calls:
return "tools"
return "__end__"
def call_model(state: MessagesState):
messages = state["messages"]
response = model_with_tools.invoke(messages)
return {"messages": [response]}
workflow = StateGraph(MessagesState)
# Define the two nodes we will cycle between
workflow.add_node("agent", call_model)
workflow.add_node("tools", tool_node)
workflow.add_edge("__start__", "agent")
workflow.add_conditional_edges(
"agent",
should_continue,
)
workflow.add_edge("tools", "agent")
app = workflow.compile()In [12]:
from IPython.display import Image, display
try:
display(Image(app.get_graph().draw_mermaid_png()))
except Exception:
# This requires some extra dependencies and is optional
passIn [13]:
# example with a single tool call
for chunk in app.stream(
{"messages": [("human", "what's the weather in sf?")]}, stream_mode="values"
):
chunk["messages"][-1].pretty_print()================================[1m Human Message [0m================================= what's the weather in sf? ==================================[1m Ai Message [0m================================== [{'text': "Okay, let's check the weather in San Francisco:", 'type': 'text'}, {'id': 'toolu_01LdmBXYeccWKdPrhZSwFCDX', 'input': {'location': 'San Francisco'}, 'name': 'get_weather', 'type': 'tool_use'}] Tool Calls: get_weather (toolu_01LdmBXYeccWKdPrhZSwFCDX) Call ID: toolu_01LdmBXYeccWKdPrhZSwFCDX Args: location: San Francisco =================================[1m Tool Message [0m================================= Name: get_weather It's 60 degrees and foggy. ==================================[1m Ai Message [0m================================== The weather in San Francisco is currently 60 degrees with foggy conditions.
In [14]:
# example with a multiple tool calls in succession
for chunk in app.stream(
{"messages": [("human", "what's the weather in the coolest cities?")]},
stream_mode="values",
):
chunk["messages"][-1].pretty_print()================================[1m Human Message [0m================================= what's the weather in the coolest cities? ==================================[1m Ai Message [0m================================== [{'text': "Okay, let's find out the weather in the coolest cities:", 'type': 'text'}, {'id': 'toolu_01LFZUWTccyveBdaSAisMi95', 'input': {}, 'name': 'get_coolest_cities', 'type': 'tool_use'}] Tool Calls: get_coolest_cities (toolu_01LFZUWTccyveBdaSAisMi95) Call ID: toolu_01LFZUWTccyveBdaSAisMi95 Args: =================================[1m Tool Message [0m================================= Name: get_coolest_cities nyc, sf ==================================[1m Ai Message [0m================================== [{'text': "Now let's get the weather for those cities:", 'type': 'text'}, {'id': 'toolu_01RHPQBhT1u6eDnPqqkGUpsV', 'input': {'location': 'nyc'}, 'name': 'get_weather', 'type': 'tool_use'}] Tool Calls: get_weather (toolu_01RHPQBhT1u6eDnPqqkGUpsV) Call ID: toolu_01RHPQBhT1u6eDnPqqkGUpsV Args: location: nyc =================================[1m Tool Message [0m================================= Name: get_weather It's 90 degrees and sunny. ==================================[1m Ai Message [0m================================== [{'id': 'toolu_01W5sFGF8PfgYzdY4CqT5c6e', 'input': {'location': 'sf'}, 'name': 'get_weather', 'type': 'tool_use'}] Tool Calls: get_weather (toolu_01W5sFGF8PfgYzdY4CqT5c6e) Call ID: toolu_01W5sFGF8PfgYzdY4CqT5c6e Args: location: sf =================================[1m Tool Message [0m================================= Name: get_weather It's 60 degrees and foggy. ==================================[1m Ai Message [0m================================== Based on the results, it looks like the weather in the coolest cities is: - New York City: 90 degrees and sunny - San Francisco: 60 degrees and foggy So the weather in the coolest cities is a mix of warm and cool temperatures, with some sunny and some foggy conditions.