设置¶
首先,让我们安装所需的软件包并设置我们的 API 密钥
在 [2]
已复制!
%%capture --no-stderr
%pip install -U langgraph langchain-openai
%%capture --no-stderr %pip install -U langgraph langchain-openai
在 [3]
已复制!
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
import getpass import os def _set_env(var: str): if not os.environ.get(var): os.environ[var] = getpass.getpass(f"{var}: ") _set_env("OPENAI_API_KEY")
代码¶
在 [4]
已复制!
# First we initialize the model we want to use.
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)
from typing import Literal
from langchain_core.tools import tool
@tool
def get_weather(location: str):
"""Use this to get weather information from a given location."""
if location.lower() in ["nyc", "new york"]:
return "It might be cloudy in nyc"
elif location.lower() in ["sf", "san francisco"]:
return "It's always sunny in sf"
else:
raise AssertionError("Unknown Location")
tools = [get_weather]
# We need a checkpointer to enable human-in-the-loop patterns
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
# Define the graph
from langgraph.prebuilt import create_react_agent
graph = create_react_agent(
model, tools=tools, interrupt_before=["tools"], checkpointer=memory
)
# 首先,我们初始化要使用的模型。 from langchain_openai import ChatOpenAI model = ChatOpenAI(model="gpt-4o", temperature=0) # 对于本教程,我们将使用自定义工具,该工具为两个城市(纽约和旧金山)的预定义天气值返回结果 from typing import Literal from langchain_core.tools import tool @tool def get_weather(location: str): """使用此工具从给定位置获取天气信息。""" if location.lower() in ["nyc", "new york"]: return "纽约可能会多云" elif location.lower() in ["sf", "san francisco"]: return "旧金山总是阳光明媚" else: raise AssertionError("未知位置") tools = [get_weather] # 我们需要一个检查点来启用人机交互模式 from langgraph.checkpoint.memory import MemorySaver memory = MemorySaver() # 定义图 from langgraph.prebuilt import create_react_agent graph = create_react_agent( model, tools=tools, interrupt_before=["tools"], checkpointer=memory )
使用¶
在 [7]
已复制!
def print_stream(stream):
"""A utility to pretty print the stream."""
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
def print_stream(stream): """用于漂亮打印流的实用程序。""" for s in stream: message = s["messages"][-1] if isinstance(message, tuple): print(message) else: message.pretty_print()
在 [8]
已复制!
from langchain_core.messages import HumanMessage
config = {"configurable": {"thread_id": "42"}}
inputs = {"messages": [("user", "what is the weather in SF, CA?")]}
print_stream(graph.stream(inputs, config, stream_mode="values"))
from langchain_core.messages import HumanMessage config = {"configurable": {"thread_id": "42"}} inputs = {"messages": [("user", "旧金山,加利福尼亚州的天气怎么样?")]} print_stream(graph.stream(inputs, config, stream_mode="values"))
================================ Human Message ================================= what is the weather in SF, CA? ================================== Ai Message ================================== Tool Calls: get_weather (call_YjOKDkgMGgUZUpKIasYk1AdK) Call ID: call_YjOKDkgMGgUZUpKIasYk1AdK Args: location: SF, CA
我们可以验证我们的图是否在正确的位置停止
在 [9]
已复制!
snapshot = graph.get_state(config)
print("Next step: ", snapshot.next)
snapshot = graph.get_state(config) print("下一步:", snapshot.next)
Next step: ('tools',)
现在,我们可以在继续到下一个节点之前批准或编辑工具调用。如果我们想批准工具调用,我们只需使用 None
输入继续流式传输图。如果我们想编辑工具调用,我们需要更新状态以拥有正确的工具调用,然后在更新应用后,我们可以继续。
我们可以尝试恢复,但我们会看到一个错误出现
在 [10]
已复制!
print_stream(graph.stream(None, config, stream_mode="values"))
print_stream(graph.stream(None, config, stream_mode="values"))
================================== Ai Message ================================== Tool Calls: get_weather (call_YjOKDkgMGgUZUpKIasYk1AdK) Call ID: call_YjOKDkgMGgUZUpKIasYk1AdK Args: location: SF, CA ================================= Tool Message ================================= Name: get_weather Error: AssertionError('Unknown Location') Please fix your mistakes. ================================== Ai Message ================================== Tool Calls: get_weather (call_CLu9ofeBhtWF2oheBspxXkfE) Call ID: call_CLu9ofeBhtWF2oheBspxXkfE Args: location: San Francisco, CA
此错误出现是因为我们的工具参数“旧金山,加利福尼亚州”不是我们的工具识别的位置。
让我们展示如何编辑工具调用以搜索“旧金山”而不是“旧金山,加利福尼亚州” - 因为我们编写的工具将“旧金山,加利福尼亚州”视为未知位置。我们将更新状态,然后继续流式传输图,应该不会看到任何错误出现
在 [11]
已复制!
state = graph.get_state(config)
last_message = state.values["messages"][-1]
last_message.tool_calls[0]["args"] = {"location": "San Francisco"}
graph.update_state(config, {"messages": [last_message]})
state = graph.get_state(config) last_message = state.values["messages"][-1] last_message.tool_calls[0]["args"] = {"location": "旧金山"} graph.update_state(config, {"messages": [last_message]})
Out[11]
{'configurable': {'thread_id': '42', 'checkpoint_ns': '', 'checkpoint_id': '1ef801d1-5b93-6bb9-8004-a088af1f9cec'}}
在 [12]
已复制!
print_stream(graph.stream(None, config, stream_mode="values"))
print_stream(graph.stream(None, config, stream_mode="values"))
================================== Ai Message ================================== Tool Calls: get_weather (call_CLu9ofeBhtWF2oheBspxXkfE) Call ID: call_CLu9ofeBhtWF2oheBspxXkfE Args: location: San Francisco ================================= Tool Message ================================= Name: get_weather It's always sunny in sf ================================== Ai Message ================================== The weather in San Francisco is currently sunny.
太棒了!我们的图已正确更新以查询旧金山的天气,并从工具中获得了正确的“旧金山总是阳光明媚”响应,然后相应地回复用户。