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.
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 | ...]".