如何向预构建的 ReAct 智能体添加内存¶
本指南将演示如何向预构建的 ReAct 智能体添加内存。有关如何开始使用预构建的 ReAct 智能体的更多信息,请参阅本教程
我们可以通过将检查点传递给create_react_agent 函数来向智能体添加内存。
设置¶
首先,让我们安装所需的软件包并设置 API 密钥
在 [1]
已复制!
%%capture --no-stderr
%pip install -U langgraph langchain-openai
%%capture --no-stderr %pip install -U langgraph langchain-openai
在 [2]
已复制!
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")
代码¶
在 [3]
已复制!
# 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(city: Literal["nyc", "sf"]):
"""Use this to get weather information."""
if city == "nyc":
return "It might be cloudy in nyc"
elif city == "sf":
return "It's always sunny in sf"
else:
raise AssertionError("Unknown city")
tools = [get_weather]
# We can add "chat memory" to the graph with LangGraph's checkpointer
# to retain the chat context between interactions
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, 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(city: Literal["nyc", "sf"]): """使用此工具获取天气信息。""" if city == "nyc": return "纽约的天气可能多云" elif city == "sf": return "旧金山总是阳光明媚" else: raise AssertionError("未知城市") tools = [get_weather] # 我们可以使用 LangGraph 的检查点将“聊天内存”添加到图中 # 以在交互之间保留聊天上下文 from langgraph.checkpoint.memory import MemorySaver memory = MemorySaver() # 定义图 from langgraph.prebuilt import create_react_agent graph = create_react_agent(model, tools=tools, checkpointer=memory)
用法¶
让我们多次与它交互以显示它可以记住信息
在 [5]
已复制!
def print_stream(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()
在 [6]
已复制!
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))
config = {"configurable": {"thread_id": "1"}} inputs = {"messages": [("user", "纽约的天气怎么样?")]} print_stream(graph.stream(inputs, config=config, stream_mode="values"))
================================ Human Message ================================= What's the weather in NYC? ================================== Ai Message ================================== Tool Calls: get_weather (call_xM1suIq26KXvRFqJIvLVGfqG) Call ID: call_xM1suIq26KXvRFqJIvLVGfqG Args: city: nyc ================================= Tool Message ================================= Name: get_weather It might be cloudy in nyc ================================== Ai Message ================================== The weather in NYC might be cloudy.
请注意,当我们传递相同的线程 ID 时,聊天历史记录会保留下来
在 [7]
已复制!
inputs = {"messages": [("user", "What's it known for?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))
inputs = {"messages": [("user", "它以什么而闻名?")]} print_stream(graph.stream(inputs, config=config, stream_mode="values"))
================================ Human Message ================================= What's it known for? ================================== Ai Message ================================== New York City (NYC) is known for a variety of iconic landmarks, cultural institutions, and vibrant neighborhoods. Some of the most notable aspects include: 1. **Statue of Liberty**: A symbol of freedom and democracy. 2. **Times Square**: Known for its bright lights, Broadway theaters, and bustling atmosphere. 3. **Central Park**: A large urban park offering a green oasis in the middle of the city. 4. **Empire State Building**: An iconic skyscraper with an observation deck offering panoramic views of the city. 5. **Broadway**: Famous for its world-class theater productions. 6. **Wall Street**: The financial hub of the United States. 7. **Museums**: Including the Metropolitan Museum of Art, the Museum of Modern Art (MoMA), and the American Museum of Natural History. 8. **Diverse Cuisine**: A melting pot of culinary experiences from around the world. 9. **Cultural Diversity**: A rich tapestry of cultures, languages, and traditions. 10. **Fashion**: A global fashion capital, home to New York Fashion Week. These are just a few highlights of what makes NYC a unique and vibrant city.
在 []
已复制!