from langchain.messages import RemoveMessagefrom langgraph.graph.message import REMOVE_ALL_MESSAGESfrom langgraph.checkpoint.memory import InMemorySaverfrom langchain.agents import create_agent, AgentStatefrom langchain.agents.middleware import before_modelfrom langgraph.runtime import Runtimefrom langchain_core.runnables import RunnableConfigfrom typing import Any@before_modeldef trim_messages(state: AgentState, runtime: Runtime) -> dict[str, Any] | None: """Keep only the last few messages to fit context window.""" messages = state["messages"] if len(messages) <= 3: return None # No changes needed first_msg = messages[0] recent_messages = messages[-3:] if len(messages) % 2 == 0 else messages[-4:] new_messages = [first_msg] + recent_messages return { "messages": [ RemoveMessage(id=REMOVE_ALL_MESSAGES), *new_messages ] }agent = create_agent( your_model_here, tools=your_tools_here, middleware=[trim_messages], checkpointer=InMemorySaver(),)config: RunnableConfig = {"configurable": {"thread_id": "1"}}agent.invoke({"messages": "hi, my name is bob"}, config)agent.invoke({"messages": "write a short poem about cats"}, config)agent.invoke({"messages": "now do the same but for dogs"}, config)final_response = agent.invoke({"messages": "what's my name?"}, config)final_response["messages"][-1].pretty_print()"""================================== Ai Message ==================================Your name is Bob. You told me that earlier.If you'd like me to call you a nickname or use a different name, just say the word."""
from langchain.messages import RemoveMessage def delete_messages(state): messages = state["messages"] if len(messages) > 2: # remove the earliest two messages return {"messages": [RemoveMessage(id=m.id) for m in messages[:2]]}
要删除所有消息:
from langgraph.graph.message import REMOVE_ALL_MESSAGES def delete_messages(state): return {"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]}
删除消息时,确保生成的消息历史是有效的。检查您使用的 LLM 提供程序的局限性。例如:
某些提供程序期望消息历史以 user 消息开头
大多数提供程序要求带有工具调用的 assistant 消息后跟相应的 tool 结果消息。
from langchain.messages import RemoveMessagefrom langchain.agents import create_agent, AgentStatefrom langchain.agents.middleware import after_modelfrom langgraph.checkpoint.memory import InMemorySaverfrom langgraph.runtime import Runtimefrom langchain_core.runnables import RunnableConfig@after_modeldef delete_old_messages(state: AgentState, runtime: Runtime) -> dict | None: """Remove old messages to keep conversation manageable.""" messages = state["messages"] if len(messages) > 2: # remove the earliest two messages return {"messages": [RemoveMessage(id=m.id) for m in messages[:2]]} return Noneagent = create_agent( "gpt-5-nano", tools=[], system_prompt="Please be concise and to the point.", middleware=[delete_old_messages], checkpointer=InMemorySaver(),)config: RunnableConfig = {"configurable": {"thread_id": "1"}}for event in agent.stream( {"messages": [{"role": "user", "content": "hi! I'm bob"}]}, config, stream_mode="values",): print([(message.type, message.content) for message in event["messages"]])for event in agent.stream( {"messages": [{"role": "user", "content": "what's my name?"}]}, config, stream_mode="values",): print([(message.type, message.content) for message in event["messages"]])
[('human', "hi! I'm bob")][('human', "hi! I'm bob"), ('ai', 'Hi Bob! Nice to meet you. How can I help you today? I can answer questions, brainstorm ideas, draft text, explain things, or help with code.')][('human', "hi! I'm bob"), ('ai', 'Hi Bob! Nice to meet you. How can I help you today? I can answer questions, brainstorm ideas, draft text, explain things, or help with code.'), ('human', "what's my name?")][('human', "hi! I'm bob"), ('ai', 'Hi Bob! Nice to meet you. How can I help you today? I can answer questions, brainstorm ideas, draft text, explain things, or help with code.'), ('human', "what's my name?"), ('ai', 'Your name is Bob. How can I help you today, Bob?')][('human', "what's my name?"), ('ai', 'Your name is Bob. How can I help you today, Bob?')]
from langchain.agents import create_agentfrom langchain.agents.middleware import SummarizationMiddlewarefrom langgraph.checkpoint.memory import InMemorySaverfrom langchain_core.runnables import RunnableConfigcheckpointer = InMemorySaver()agent = create_agent( model="gpt-4.1", tools=[], middleware=[ SummarizationMiddleware( model="gpt-4.1-mini", trigger=("tokens", 4000), keep=("messages", 20) ) ], checkpointer=checkpointer,)config: RunnableConfig = {"configurable": {"thread_id": "1"}}agent.invoke({"messages": "hi, my name is bob"}, config)agent.invoke({"messages": "write a short poem about cats"}, config)agent.invoke({"messages": "now do the same but for dogs"}, config)final_response = agent.invoke({"messages": "what's my name?"}, config)final_response["messages"][-1].pretty_print()"""================================== Ai Message ==================================Your name is Bob!"""
from langchain.agents import create_agent, AgentStatefrom langchain.tools import tool, ToolRuntimeclass CustomState(AgentState): user_id: str@tooldef get_user_info( runtime: ToolRuntime) -> str: """Look up user info.""" user_id = runtime.state["user_id"] return "User is John Smith" if user_id == "user_123" else "Unknown user"agent = create_agent( model="gpt-5-nano", tools=[get_user_info], state_schema=CustomState,)result = agent.invoke({ "messages": "look up user information", "user_id": "user_123"})print(result["messages"][-1].content)# > User is John Smith.
from langchain.agents import create_agentfrom typing import TypedDictfrom langchain.agents.middleware import dynamic_prompt, ModelRequestclass CustomContext(TypedDict): user_name: strdef get_weather(city: str) -> str: """Get the weather in a city.""" return f"The weather in {city} is always sunny!"@dynamic_promptdef dynamic_system_prompt(request: ModelRequest) -> str: user_name = request.runtime.context["user_name"] system_prompt = f"You are a helpful assistant. Address the user as {user_name}." return system_promptagent = create_agent( model="gpt-5-nano", tools=[get_weather], middleware=[dynamic_system_prompt], context_schema=CustomContext,)result = agent.invoke( {"messages": [{"role": "user", "content": "What is the weather in SF?"}]}, context=CustomContext(user_name="John Smith"),)for msg in result["messages"]: msg.pretty_print()
Output
================================ Human Message =================================What is the weather in SF?================================== Ai Message ==================================Tool Calls: get_weather (call_WFQlOGn4b2yoJrv7cih342FG) Call ID: call_WFQlOGn4b2yoJrv7cih342FG Args: city: San Francisco================================= Tool Message =================================Name: get_weatherThe weather in San Francisco is always sunny!================================== Ai Message ==================================Hi John Smith, the weather in San Francisco is always sunny!
from langchain.messages import RemoveMessagefrom langgraph.graph.message import REMOVE_ALL_MESSAGESfrom langgraph.checkpoint.memory import InMemorySaverfrom langchain.agents import create_agent, AgentStatefrom langchain.agents.middleware import before_modelfrom langchain_core.runnables import RunnableConfigfrom langgraph.runtime import Runtimefrom typing import Any@before_modeldef trim_messages(state: AgentState, runtime: Runtime) -> dict[str, Any] | None: """Keep only the last few messages to fit context window.""" messages = state["messages"] if len(messages) <= 3: return None # No changes needed first_msg = messages[0] recent_messages = messages[-3:] if len(messages) % 2 == 0 else messages[-4:] new_messages = [first_msg] + recent_messages return { "messages": [ RemoveMessage(id=REMOVE_ALL_MESSAGES), *new_messages ] }agent = create_agent( "gpt-5-nano", tools=[], middleware=[trim_messages], checkpointer=InMemorySaver())config: RunnableConfig = {"configurable": {"thread_id": "1"}}agent.invoke({"messages": "hi, my name is bob"}, config)agent.invoke({"messages": "write a short poem about cats"}, config)agent.invoke({"messages": "now do the same but for dogs"}, config)final_response = agent.invoke({"messages": "what's my name?"}, config)final_response["messages"][-1].pretty_print()"""================================== Ai Message ==================================Your name is Bob. You told me that earlier.If you'd like me to call you a nickname or use a different name, just say the word."""