core: fix trim_messages token_counter detection for lambdas and postponed annotations#35657
Conversation
… subclasses, and postponed annotations The per-message vs per-list token_counter detection in trim_messages used `annotation is BaseMessage` (identity check), which failed for lambdas, unannotated functions, string annotations, subclass annotations (e.g. HumanMessage), and postponed annotations via `from __future__ import annotations`. Replace with a robust _is_per_message_counter() helper that: 1. Uses typing.get_type_hints() to resolve string/postponed annotations 2. Uses issubclass() instead of identity to handle subclass annotations 3. Falls back to probing with a dummy message for lambdas and unannotated callables Fixes langchain-ai#35629
Merging this PR will not alter performance
|
|
Hi! Creator of the issue here :) Thanks for working on this. However, I already have a PR open to fix it from when I originally opened the issue. Plelase try to avoid duplicates |
ccurme (ccurme)
left a comment
There was a problem hiding this comment.
Duplicated with #35630.
|
Sorry about this — I should have checked for existing PRs before submitting. I didn't realize you already had #35630 open for the same issue. Won't happen again. Thanks for the fix! |
Description
Fixes a bug where
trim_messagesmisclassifies per-messagetoken_countercallables as per-list counters, causingAttributeError: 'list' object has no attribute 'content'at runtime.Root cause
The detection logic used
annotation is BaseMessage(identity check) to determine iftoken_counteraccepts a singleBaseMessageor a list. This fails for:inspect.Parameter.empty"BaseMessage", not the classmsg: HumanMessage—HumanMessage is not BaseMessagefrom __future__ import annotationsturns all annotations into stringsFix
Added a
_is_per_message_counter()helper that:typing.get_type_hints()to resolve string and postponed annotationsissubclass()instead of identity to handle subclass annotationsBefore
After
All forms work correctly, including
lenas a list counter.Issue
Fixes #35629
Tests
Verified with the reproduction script from the issue — all five cases now pass. List counters (
len, annotated list functions) continue to work correctly.