Hi guys, so I’m working with create_agent from langchain.agents and I’m trying to make use of both a custom context_schema (to pass runtime data like page_context) and SummarizationMiddleware.
Setup
from langchain.agents import AgentState, create_agent
from langchain.agents.middleware import AgentMiddleware, SummarizationMiddleware
class Context(BaseModel):
page_context: Optional[Dict[str, Any]] = None
class ToolMonitoringMiddleware(AgentMiddleware[AgentState, Context]):
async def awrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
) -> ToolMessage | Command:
print(f"Executing tool: {request.tool_call['name']}")
print(f"Arguments: {request.tool_call['args']}")
print(f"Runtime context: {request.runtime.context}")
try:
result = await handler(request)
print(f"{request.tool_call['name']} tool completed successfully")
return result
except Exception as e:
print(f"Tool failed: {e}")
raise
# ...
agent_executor = create_agent(
model=qwen3_model.chatModel,
tools=tools,
system_prompt=system_message,
checkpointer=checkpointer,
context_schema=Context,
middleware=[
ToolMonitoringMiddleware(), # This one works fine with context
SummarizationMiddleware(
model=qwen3_model.chat_model,
max_tokens_before_summary=40000,
messages_to_keep=15,
),
],
)
Issue
However, when I specify a context_schema=Context, Pyright gives me this error:
"SummarizationMiddleware" is not assignable to "AgentMiddleware[AgentState[Unknown], Context]"
Type parameter "ContextT@AgentMiddleware" is invariant, but "None" is not the same as "Context" Pyright (reportArgumentType)
Discussion
Is there a recommended pattern for making built-in middlewares like SummarizationMiddleware compatible with custom context schemas?
Alternatively, should SummarizationMiddleware be updated to support being parameterized with AgentMiddleware[StateT, ContextT]?
Thanks in advance!