langchain-ai/langchain · error · ValueError

Unrecognized {strategy=}. Supported strategies are 'last' an

Error message

Unrecognized {strategy=}. Supported strategies are 'last' and 'first'.

What it means

Raised by `trim_messages` after the if-chain dispatch when `strategy` is neither 'last' nor 'first'. This is the final guard; earlier validation only covers `start_on`/`include_system`, so an unrecognized strategy reaches this line.

Source

Thrown at libs/core/langchain_core/messages/utils.py:1520

            max_tokens=max_tokens,
            token_counter=list_token_counter,
            text_splitter=text_splitter_fn,
            partial_strategy="first" if allow_partial else None,
            end_on=end_on,
        )
    if strategy == "last":
        return _last_max_tokens(
            messages,
            max_tokens=max_tokens,
            token_counter=list_token_counter,
            allow_partial=allow_partial,
            include_system=include_system,
            start_on=start_on,
            end_on=end_on,
            text_splitter=text_splitter_fn,
        )
    msg = f"Unrecognized {strategy=}. Supported strategies are 'last' and 'first'."  # type: ignore[unreachable]
    raise ValueError(msg)


_SingleMessage = BaseMessage | str | dict[str, Any]
_T = TypeVar("_T", bound=_SingleMessage)
# A sequence of _SingleMessage that is NOT a bare str
_MultipleMessages = Sequence[_T]


@overload
def convert_to_openai_messages(
    messages: _SingleMessage,
    *,
    text_format: Literal["string", "block"] = "string",
    include_id: bool = False,
    pass_through_unknown_blocks: bool = True,
) -> dict[str, Any]: ...

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Use `strategy='last'` (keep the most recent messages) or `strategy='first'` (keep the earliest)
  2. Validate strategy against `{'last', 'first'}` in your config layer before calling

Example fix

# before
trim_messages(msgs, max_tokens=500, strategy='recent')

# after
trim_messages(msgs, max_tokens=500, strategy='last')
Defensive patterns

Strategy: validation

Validate before calling

def valid_strategy(s: str) -> bool:
    return s in {'last', 'first'}

assert valid_strategy(strategy), f"strategy must be 'last' or 'first', got {strategy!r}"

Type guard

def is_trim_strategy(s: object) -> bool:
    return isinstance(s, str) and s in {'last', 'first'}

Prevention

When it happens

Trigger: Calling `trim_messages(msgs, strategy='middle')`, `strategy='last '` (trailing space), or passing a None/default value that was never overridden.

Common situations: Config-driven strategy strings with typos or unsupported values; code written against wrappers offering more strategies than langchain-core implements.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/5d12027a497d9bbd. Report an issue: GitHub.