如何管理ReAct代理中的对话历史记录¶
消息历史记录可能会迅速增长并超出LLM上下文窗口大小,无论您是构建具有许多对话轮次的聊天机器人还是具有众多工具调用的代理系统。管理消息历史记录有几种策略:
为了在create_react_agent
中管理消息历史记录,您需要定义一个pre_model_hook
函数或可运行对象,该函数接收图状态并返回状态更新:
-
修剪示例:
from langchain_core.messages.utils import ( trim_messages, count_tokens_approximately ) from langgraph.prebuilt import create_react_agent # 此函数将在每次调用LLM之前被调用 def pre_model_hook(state): trimmed_messages = trim_messages( state["messages"], strategy="last", token_counter=count_tokens_approximately, max_tokens=384, start_on="human", end_on=("human", "tool"), ) # 您可以将更新后的消息返回到`llm_input_messages`或`messages`键下(见下方注释) return {"llm_input_messages": trimmed_messages} checkpointer = InMemorySaver() agent = create_react_agent( model, tools, pre_model_hook=pre_model_hook, checkpointer=checkpointer, )
-
摘要示例:
from langmem.short_term import SummarizationNode from langchain_core.messages.utils import count_tokens_approximately from langgraph.prebuilt.chat_agent_executor import AgentState from langgraph.checkpoint.memory import InMemorySaver from typing import Any model = ChatOpenAI(model="gpt-4o") summarization_node = SummarizationNode( token_counter=count_tokens_approximately, model=model, max_tokens=384, max_summary_tokens=128, output_messages_key="llm_input_messages", ) class State(AgentState): # 注意:我们添加了此键以跟踪先前的摘要信息 # 确保我们不会在每次LLM调用时都进行摘要 context: dict[str, Any] checkpointer = InMemorySaver() graph = create_react_agent( model, tools, pre_model_hook=summarization_node, state_schema=State, checkpointer=checkpointer, )
重要
- 若要在图状态中**保持原始消息历史记录不变**,并将更新后的历史记录仅作为输入传递给LLM,请在
llm_input_messages
键下返回更新后的消息 - 若要在图状态中**用更新后的历史记录覆盖原始消息历史记录**,请在
messages
键下返回更新后的消息
覆盖messages
键,您需要执行以下操作:
设置环境¶
首先,让我们安装所需的包并设置API密钥
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")
为LangGraph开发设置LangSmith
注册LangSmith可以快速发现并解决您的LangGraph项目中的问题,提高性能。使用LangSmith,您可以利用跟踪数据来调试、测试和监控使用LangGraph构建的LLM应用程序——更多关于如何开始的信息,请参阅这里。
保持原始消息历史不变¶
让我们构建一个ReAct代理,并添加一个管理对话历史记录的步骤:当历史记录长度超过指定的令牌数量时,我们将调用trim_messages
工具来减少历史记录,同时满足LLM提供商的约束条件。
更新后的消息历史可以在ReAct代理内部以两种方式应用:
- 保持原始消息历史不变,在图状态中保留其原始形式,并且仅将更新后的历史作为输入传递给LLM
- 覆盖原始消息历史,在图状态中使用更新后的历史记录
我们先从实现第一个方法开始。首先需要定义模型和工具供我们的代理使用:
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
def get_weather(location: str) -> str:
"""Use this to get weather information."""
if any([city in location.lower() for city in ["nyc", "new york city"]]):
return "It might be cloudy in nyc, with a chance of rain and temperatures up to 80 degrees."
elif any([city in location.lower() for city in ["sf", "san francisco"]]):
return "It's always sunny in sf"
else:
return f"I am not sure what the weather is in {location}"
tools = [get_weather]
现在让我们实现pre_model_hook
——一个将被添加为新节点并在每次调用LLM(即agent
节点)之前调用的函数。
我们的实现将包裹trim_messages
调用,并在llm_input_messages
下返回修剪后的消息。这将**保持原始消息历史记录不变**,同时仅将更新的历史记录作为输入传递给LLM。
API Reference: create_react_agent | InMemorySaver | trim_messages | count_tokens_approximately
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import InMemorySaver
from langchain_core.messages.utils import (
trim_messages,
count_tokens_approximately,
)
# This function will be added as a new node in ReAct agent graph
# that will run every time before the node that calls the LLM.
# The messages returned by this function will be the input to the LLM.
def pre_model_hook(state):
trimmed_messages = trim_messages(
state["messages"],
strategy="last",
token_counter=count_tokens_approximately,
max_tokens=384,
start_on="human",
end_on=("human", "tool"),
)
return {"llm_input_messages": trimmed_messages}
checkpointer = InMemorySaver()
graph = create_react_agent(
model,
tools,
pre_model_hook=pre_model_hook,
checkpointer=checkpointer,
)
我们还将定义一个工具,用于优雅地渲染代理输出:
def print_stream(stream, output_messages_key="llm_input_messages"):
for chunk in stream:
for node, update in chunk.items():
print(f"Update from node: {node}")
messages_key = (
output_messages_key if node == "pre_model_hook" else "messages"
)
for message in update[messages_key]:
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
print("\n\n")
现在让我们用几个不同的查询来运行代理,以达到指定的最大令牌限制:
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}
result = graph.invoke(inputs, config=config)
inputs = {"messages": [("user", "What's it known for?")]}
result = graph.invoke(inputs, config=config)
让我们看看到目前为止消息历史中还有多少令牌:
你可以看到我们已经接近max_tokens
阈值,所以在下一次调用时,你应该会看到pre_model_hook
启动并修剪消息历史记录。让我们再运行一次:
inputs = {"messages": [("user", "where can i find the best bagel?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="updates"))
Update from node: pre_model_hook
================================ Human Message =================================
What's it known for?
================================== Ai Message ==================================
New York City is known for a variety of iconic landmarks, cultural institutions, and vibrant neighborhoods. Some of the most notable features include:
1. **Statue of Liberty**: A symbol of freedom and democracy, located on Liberty Island.
2. **Times Square**: Known for its bright lights, Broadway theaters, and bustling atmosphere.
3. **Central Park**: A large public park offering a natural retreat in the middle of the city.
4. **Empire State Building**: An iconic skyscraper 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, Museum of Modern Art (MoMA), and the American Museum of Natural History.
8. **Diverse Cuisine**: A melting pot of cultures offering a wide range of culinary experiences.
9. **Cultural Diversity**: A rich tapestry of cultures and communities from around the world.
10. **Fashion**: A global fashion capital, hosting events like New York Fashion Week.
These are just a few highlights of what makes New York City a unique and vibrant place.
================================ Human Message =================================
where can i find the best bagel?
Update from node: agent
================================== Ai Message ==================================
New York City is famous for its bagels, and there are several places renowned for serving some of the best. Here are a few top spots where you can find excellent bagels in NYC:
1. **Ess-a-Bagel**: Known for their large, chewy bagels with a variety of spreads and toppings.
2. **Russ & Daughters**: A classic spot offering traditional bagels with high-quality smoked fish and cream cheese.
3. **H&H Bagels**: Famous for their fresh, hand-rolled bagels.
4. **Murray’s Bagels**: Offers a wide selection of bagels and spreads, with a no-toasting policy to preserve freshness.
5. **Absolute Bagels**: Known for their authentic, fluffy bagels and a variety of cream cheese options.
6. **Tompkins Square Bagels**: Offers creative bagel sandwiches and a wide range of spreads.
7. **Bagel Hole**: Known for their smaller, denser bagels with a crispy crust.
Each of these places has its own unique style and flavor, so it might be worth trying a few to find your personal favorite!
pre_model_hook
节点现在只返回了最后3条消息,如预期所示。然而,现有的消息历史未受影响:
updated_messages = graph.get_state(config).values["messages"]
assert [(m.type, m.content) for m in updated_messages[: len(messages)]] == [
(m.type, m.content) for m in messages
]
覆写原始消息历史记录¶
我们现在将 pre_model_hook
更改为**覆盖**图状态中的消息历史记录。为此,我们将在 messages
键下返回更新后的消息。我们还将包含一个特殊的 RemoveMessage(REMOVE_ALL_MESSAGES)
对象,该对象指示 create_react_agent
从图状态中移除之前的全部消息:
API Reference: RemoveMessage
from langchain_core.messages import RemoveMessage
from langgraph.graph.message import REMOVE_ALL_MESSAGES
def pre_model_hook(state):
trimmed_messages = trim_messages(
state["messages"],
strategy="last",
token_counter=count_tokens_approximately,
max_tokens=384,
start_on="human",
end_on=("human", "tool"),
)
# NOTE that we're now returning the messages under the `messages` key
# We also remove the existing messages in the history to ensure we're overwriting the history
return {"messages": [RemoveMessage(REMOVE_ALL_MESSAGES)] + trimmed_messages}
checkpointer = InMemorySaver()
graph = create_react_agent(
model,
tools,
pre_model_hook=pre_model_hook,
checkpointer=checkpointer,
)
现在让我们用与之前相同的查询来运行代理:
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}
result = graph.invoke(inputs, config=config)
inputs = {"messages": [("user", "What's it known for?")]}
result = graph.invoke(inputs, config=config)
messages = result["messages"]
inputs = {"messages": [("user", "where can i find the best bagel?")]}
print_stream(
graph.stream(inputs, config=config, stream_mode="updates"),
output_messages_key="messages",
)
Update from node: pre_model_hook
================================ Remove Message ================================
================================ Human Message =================================
What's it known for?
================================== Ai Message ==================================
New York City is known for a variety of iconic landmarks, cultural institutions, and vibrant neighborhoods. Some of the most notable features include:
1. **Statue of Liberty**: A symbol of freedom and democracy, located on Liberty Island.
2. **Times Square**: Known for its bright lights, Broadway theaters, and bustling atmosphere.
3. **Central Park**: A large public park offering a natural oasis amidst the urban environment.
4. **Empire State Building**: An iconic skyscraper offering panoramic views of the city.
5. **Broadway**: Famous for its world-class theater productions and musicals.
6. **Wall Street**: The financial hub of the United States, located in the Financial District.
7. **Museums**: Including the Metropolitan Museum of Art, Museum of Modern Art (MoMA), and the American Museum of Natural History.
8. **Diverse Cuisine**: A melting pot of cultures, offering a wide range of international foods.
9. **Cultural Diversity**: Known for its diverse population and vibrant cultural scene.
10. **Brooklyn Bridge**: An iconic suspension bridge connecting Manhattan and Brooklyn.
These are just a few highlights, as NYC is a city with endless attractions and activities.
================================ Human Message =================================
where can i find the best bagel?
Update from node: agent
================================== Ai Message ==================================
New York City is famous for its bagels, and there are several places renowned for serving some of the best. Here are a few top spots where you can find delicious bagels in NYC:
1. **Ess-a-Bagel**: Known for its large, chewy bagels and a wide variety of spreads and toppings. Locations in Midtown and the East Village.
2. **Russ & Daughters**: A historic appetizing store on the Lower East Side, famous for its bagels with lox and cream cheese.
3. **Absolute Bagels**: Located on the Upper West Side, this spot is popular for its fresh, fluffy bagels.
4. **Murray’s Bagels**: Known for its traditional, hand-rolled bagels. Located in Greenwich Village.
5. **Tompkins Square Bagels**: Offers a wide selection of bagels and creative cream cheese flavors. Located in the East Village.
6. **Bagel Hole**: A small shop in Park Slope, Brooklyn, known for its classic, no-frills bagels.
7. **Leo’s Bagels**: Located in the Financial District, known for its authentic New York-style bagels.
Each of these places has its own unique style and flavor, so it might be worth trying a few to find your personal favorite!
pre_model_hook
节点再次返回了最后三条消息。然而,这一次,在图的状态中也修改了消息历史:
updated_messages = graph.get_state(config).values["messages"]
assert (
# First 2 messages in the new history are the same as last 2 messages in the old
[(m.type, m.content) for m in updated_messages[:2]]
== [(m.type, m.content) for m in messages[-2:]]
)
汇总消息历史记录¶
最后,我们将应用一种不同的策略来管理消息历史——摘要。与修剪一样,您可以选择保留原始消息历史不变或覆盖它。以下示例仅显示前者。
我们将使用预构建的langmem
库中的SummarizationNode
。一旦消息历史达到令牌限制,摘要节点将对早期的消息进行摘要,以确保它们适合max_tokens
。
API Reference: AgentState
from langmem.short_term import SummarizationNode
from langgraph.prebuilt.chat_agent_executor import AgentState
from typing import Any
model = ChatOpenAI(model="gpt-4o")
summarization_model = model.bind(max_tokens=128)
summarization_node = SummarizationNode(
token_counter=count_tokens_approximately,
model=summarization_model,
max_tokens=384,
max_summary_tokens=128,
output_messages_key="llm_input_messages",
)
class State(AgentState):
# NOTE: we're adding this key to keep track of previous summary information
# to make sure we're not summarizing on every LLM call
context: dict[str, Any]
checkpointer = InMemorySaver()
graph = create_react_agent(
# limit the output size to ensure consistent behavior
model.bind(max_tokens=256),
tools,
pre_model_hook=summarization_node,
state_schema=State,
checkpointer=checkpointer,
)
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}
result = graph.invoke(inputs, config=config)
inputs = {"messages": [("user", "What's it known for?")]}
result = graph.invoke(inputs, config=config)
inputs = {"messages": [("user", "where can i find the best bagel?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="updates"))
Update from node: pre_model_hook
================================ System Message ================================
Summary of the conversation so far: The user asked about the current weather in New York City. In response, the assistant provided information that it might be cloudy, with a chance of rain, and temperatures reaching up to 80 degrees.
================================ Human Message =================================
What's it known for?
================================== Ai Message ==================================
New York City, often referred to as NYC, is known for its:
1. **Landmarks and Iconic Sites**:
- **Statue of Liberty**: A symbol of freedom and democracy.
- **Central Park**: A vast green oasis in the middle of the city.
- **Empire State Building**: Once the tallest building in the world, offering stunning views of the city.
- **Times Square**: Known for its bright lights and bustling atmosphere.
2. **Cultural Institutions**:
- **Broadway**: Renowned for theatrical performances and musicals.
- **Metropolitan Museum of Art** and **Museum of Modern Art (MoMA)**: World-class art collections.
- **American Museum of Natural History**: Known for its extensive exhibits ranging from dinosaurs to space exploration.
3. **Diverse Neighborhoods and Cuisine**:
- NYC is famous for having a melting pot of cultures, reflected in neighborhoods like Chinatown, Little Italy, and Harlem.
- The city offers a wide range of international cuisines, from street food to high-end dining.
4. **Financial District**:
- Home to Wall Street, the New York Stock Exchange (NYSE), and other major financial institutions.
5. **Media and Entertainment**:
- Major hub for television, film, and media, with numerous studios and networks based there.
6. **Fashion**:
- Often referred to as one of the "Big Four" fashion capitals, hosting events like New York Fashion Week.
7. **Sports**:
- Known for its passionate sports culture with teams like the Yankees (MLB), Mets (MLB), Knicks (NBA), and Rangers (NHL).
These elements, among others, contribute to NYC's reputation as a vibrant and dynamic city.
================================ Human Message =================================
where can i find the best bagel?
Update from node: agent
================================== Ai Message ==================================
Finding the best bagel in New York City can be subjective, as there are many beloved spots across the city. However, here are some renowned bagel shops you might want to try:
1. **Ess-a-Bagel**: Known for its chewy and flavorful bagels, located in Midtown and Stuyvesant Town.
2. **Bagel Hole**: A favorite for traditionalists, offering classic and dense bagels, located in Park Slope, Brooklyn.
3. **Russ & Daughters**: A legendary appetizing store on the Lower East Side, famous for their bagels with lox.
4. **Murray’s Bagels**: Located in Greenwich Village, known for their fresh and authentic New York bagels.
5. **Absolute Bagels**: Located on the Upper West Side, they’re known for their fresh, fluffy bagels with a variety of spreads.
6. **Tompkins Square Bagels**: In the East Village, famous for their creative cream cheese options and fresh bagels.
7. **Zabar’s**: A landmark on the Upper West Side known for their classic bagels and smoked fish.
Each of these spots offers a unique take on the classic New York bagel experience, and trying several might be the best way to discover your personal favorite!