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

ModelRequest.Override Rejects List[BaseMessage] Due To Invariant List Typing

Passing a filtered list[BaseMessage] to ModelRequest.override(messages=...) triggers a static type error because _ModelRequestOverrides.messages and ModelRequest.messages are typed as list[AnyMessage]; list is invariant, so list[BaseMessage] is not assignable even though BaseMessage is a valid message type.

mediumConfidence 95%LangchainChat ModelsMemoryChainsAffected V1.2.12Affected V1.2.19

Origin Analysis

In langchain.agents.middleware, the dataclass fields `_ModelRequestOverrides.messages` and `ModelRequest.messages` are annotated as `list[AnyMessage]`. Python's `list` is invariant in its type parameter, so `list[BaseMessage]` is not considered a subtype of `list[AnyMessage]`, despite `BaseMessage` being a subtype of the union `AnyMessage`. This type error occurs at static analysis time (Pyright/mypy) and does not reflect a runtime failure. The correct fix is to use the covariant `Sequence[BaseMessage]` type instead of `list[AnyMessage]`, matching the read-only usage in `override()`.
Run the following code with Pyright or mypy: ```python from langchain.agents.middleware import before_model, ModelRequest from langchain_core.messages import BaseMessage, AIMessage, HumanMessage @before_model def trim_messages(request: ModelRequest) -> ModelRequest: trimmed: list[BaseMessage] = [ m for m in request.messages if isinstance(m, (AIMessage, HumanMessage)) ] return request.override(messages=trimmed) ``` The type checker reports: Argument of type "list[BaseMessage]" cannot be assigned to parameter "messages" of type "list[AIMessage | HumanMessage | ...]".

Fixing Code Block

from typing import Sequence # In _ModelRequestOverrides, replace: messages: list[AnyMessage] | None = None # with: messages: Sequence[BaseMessage] | None = None # In ModelRequest, replace: messages: list[AnyMessage] # with: messages: Sequence[BaseMessage]
Change the type annotation of `messages` from `list[AnyMessage]` to `Sequence[BaseMessage]` in both `_ModelRequestOverrides` and `ModelRequest`. `Sequence` is covariant and read-only, which correctly models the input-only usage in `override()`. This allows `list[BaseMessage]` and other `Sequence[BaseMessage]` subtypes to be accepted. The `ModelRequest` dataclass field also needs the change so that `dataclasses.replace()` does not raise a type error.

Edge Case Audit

Changing to `Sequence` is type-only and does not alter runtime behavior, but code that previously relied on `request.messages` being a mutable list (e.g., calling `.append()` or other list-specific methods) will now trigger type errors and may need adjustment. If this change unexpectedly breaks internal code that mutates messages, revert to the original `list[AnyMessage]` and consider a custom covariant protocol or a helper function that accepts `Sequence[BaseMessage]`. Rollback: simply revert the two type annotations.

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