Skip to content

trim_messages returning invalid messages history #33245

@ozuromo

Description

@ozuromo

Checked other resources

  • This is a bug, not a usage question.
  • I added a clear and descriptive title that summarizes this issue.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
  • This is not related to the langchain-community package.
  • I read what a minimal reproducible example is (https://stackoverflow.com/help/minimal-reproducible-example).
  • I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.

Example Code

By running the following code

from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
from langchain_core.messages.utils import trim_messages

messages = [
    HumanMessage("What's the weather in Florida?"),
    AIMessage(
        [
            {"type": "text", "text": "Let's check the weather in Florida"},
            {
                "type": "tool_use",
                "id": "abc123",
                "name": "get_weather",
                "input": {"location": "Florida"},
            },
        ],
        tool_calls=[
            {
                "name": "get_weather",
                "args": {"location": "Florida"},
                "id": "abc123",
                "type": "tool_call",
            },
        ],
    ),
    ToolMessage(
        "It's sunny.",
        name="get_weather",
        tool_call_id="abc123",
    ),
    HumanMessage("I see"),
    AIMessage("Do you want to know anything else?"),
    HumanMessage("No, thanks"),
    AIMessage("You're welcome! Have a great day!"),
]

trimmed_messages = trim_messages(
    messages,
    strategy="last",
    token_counter=len,
    max_tokens=5,
)

for message in trimmed_messages:
    message.pretty_print()

Output:

================================= Tool Message =================================
Name: get_weather

It's sunny.
================================ Human Message =================================

I see
================================== Ai Message ==================================

Do you want to know anything else?
================================ Human Message =================================

No, thanks
================================== Ai Message ==================================

You're welcome! Have a great day!

As you can see, the history is invalid, given that we have a ToolMessage without a corresponding AIMessage.

Error Message and Stack Trace (if applicable)

No response

Description

I'm trying to use trim_messages to select the last n messages while keeping the history valid. But I'm getting an invalid history as the returned value.

System Info

System Information
------------------
> OS:  Darwin
> OS Version:  Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:40 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T8132
> Python Version:  3.13.3 (main, May 30 2025, 05:45:55) [Clang 20.1.4 ]

Package Information
-------------------
> langchain_core: 0.3.77
> langchain: 0.3.27
> langsmith: 0.4.32
> langchain_text_splitters: 0.3.11

Optional packages not installed
-------------------------------
> langserve

Other Dependencies
------------------
> async-timeout<5.0.0,>=4.0.0;: Installed. No version info available.
> httpx<1,>=0.23.0: Installed. No version info available.
> jsonpatch<2.0.0,>=1.33.0: Installed. No version info available.
> langchain-anthropic;: Installed. No version info available.
> langchain-aws;: Installed. No version info available.
> langchain-azure-ai;: Installed. No version info available.
> langchain-cohere;: Installed. No version info available.
> langchain-community;: Installed. No version info available.
> langchain-core<1.0.0,>=0.3.72: Installed. No version info available.
> langchain-core<2.0.0,>=0.3.75: Installed. No version info available.
> langchain-deepseek;: Installed. No version info available.
> langchain-fireworks;: Installed. No version info available.
> langchain-google-genai;: Installed. No version info available.
> langchain-google-vertexai;: Installed. No version info available.
> langchain-groq;: Installed. No version info available.
> langchain-huggingface;: Installed. No version info available.
> langchain-mistralai;: Installed. No version info available.
> langchain-ollama;: Installed. No version info available.
> langchain-openai;: Installed. No version info available.
> langchain-perplexity;: Installed. No version info available.
> langchain-text-splitters<1.0.0,>=0.3.9: Installed. No version info available.
> langchain-together;: Installed. No version info available.
> langchain-xai;: Installed. No version info available.
> langsmith-pyo3>=0.1.0rc2;: Installed. No version info available.
> langsmith<1.0.0,>=0.3.45: Installed. No version info available.
> langsmith>=0.1.17: Installed. No version info available.
> openai-agents>=0.0.3;: Installed. No version info available.
> opentelemetry-api>=1.30.0;: Installed. No version info available.
> opentelemetry-exporter-otlp-proto-http>=1.30.0;: Installed. No version info available.
> opentelemetry-sdk>=1.30.0;: Installed. No version info available.
> orjson>=3.9.14;: Installed. No version info available.
> packaging<26.0.0,>=23.2.0: Installed. No version info available.
> packaging>=23.2: Installed. No version info available.
> pydantic<3,>=1: Installed. No version info available.
> pydantic<3.0.0,>=2.7.4: Installed. No version info available.
> pytest>=7.0.0;: Installed. No version info available.
> PyYAML<7.0.0,>=5.3.0: Installed. No version info available.
> PyYAML>=5.3: Installed. No version info available.
> requests-toolbelt>=1.0.0: Installed. No version info available.
> requests<3,>=2: Installed. No version info available.
> requests>=2.0.0: Installed. No version info available.
> rich>=13.9.4;: Installed. No version info available.
> SQLAlchemy<3,>=1.4: Installed. No version info available.
> tenacity!=8.4.0,<10.0.0,>=8.1.0: Installed. No version info available.
> typing-extensions<5.0.0,>=4.7.0: Installed. No version info available.
> vcrpy>=7.0.0;: Installed. No version info available.
> zstandard>=0.23.0: Installed. No version info available.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugRelated to a bug, vulnerability, unexpected error with an existing feature

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions