AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Trim_messages Misclassifies Per-Message Token_counter When Annotation Is Missing, String, Subclass, Or Postponed

`trim_messages` wrongly treats a per-message `token_counter` as a list counter when the function lacks a `BaseMessage` annotation or the annotation is not directly resolvable, causing `AttributeError: 'list' object has no attribute 'content'`.

highConfidence 85%Langchain-CoreRetrieversVector StoresChat ModelsAffected V1.2.17

Origin Analysis

The detection logic in `trim_messages` relies on a raw annotation identity check against `BaseMessage`, which fails for lambdas, unannotated callables, string annotations, subclass annotations, and postponed annotations (PEP 563). As a result, the callable is invoked with a list of messages instead of a single message.
Define a token_counter that accepts a single message (e.g., lambda msg: len(msg.content.split()) or any function without BaseMessage annotation), then call trim_messages(messages, max_tokens=5, token_counter=counter). The counter is called with a list, leading to AttributeError.

Fixing Code Block

Edge Case Audit

Probing the callable has side effects if the counter is stateful or has external effects. The probe may also misclassify a function that accepts both a single message and a list. To avoid extra calls, the annotation check is attempted first. Users with ambiguous counters should add explicit annotations. Rollback: revert to previous version if probe causes unexpected behavior; alternatively, add an explicit parameter to specify counter type.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state