Skip to content

Make ModelRequest, ModelResponse, and AgentMiddleware generic over Context type #33956

Description

@liam-langchain

Checked other resources

  • This is a feature request, not a bug report or usage question.
  • I added a clear and descriptive title that summarizes the feature request.
  • I used the GitHub search to find a similar feature request and didn't find it.
  • I checked the LangChain documentation and API reference to see if this feature already exists.
  • This is not related to the langchain-community package.

Package (Required)

  • langchain
  • langchain-openai
  • langchain-anthropic
  • langchain-classic
  • langchain-core
  • langchain-cli
  • langchain-model-profiles
  • langchain-tests
  • langchain-text-splitters
  • langchain-chroma
  • langchain-deepseek
  • langchain-exa
  • langchain-fireworks
  • langchain-groq
  • langchain-huggingface
  • langchain-mistralai
  • langchain-nomic
  • langchain-ollama
  • langchain-perplexity
  • langchain-prompty
  • langchain-qdrant
  • langchain-xai
  • Other / not sure / general

Feature Description

ModelRequest contains a runtime: Runtime[Context] parameter, but ModelRequest itself is not generic over the Context type. This forces developers to cast request.runtime.context to their specific context type when implementing middleware, breaking type safety.

The same issue applies to ModelResponse and the AgentMiddleware base class - they should all be generic over Context to provide proper type checking throughout the middleware chain.

Use Case

When implementing custom middleware with typed contexts, developers are forced to cast:

@dataclass
class MyContext:
    user_id: str
    session_data: dict

class MyMiddleware(AgentMiddleware):
    async def awrap_model_call(
        self,
        request: ModelRequest,  # Not generic over Context
        handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
    ) -> ModelCallResult:
        # Have to cast - no type safety!
        context = cast(MyContext, request.runtime.context)
        user_id = context.user_id  # IDE can't autocomplete, type checker can't validate

        response = await handler(request)
        return response

This breaks type safety because:

  • IDE autocomplete doesn't work for context attributes
  • Type checkers (mypy, pyright) can't validate context usage
  • Refactoring context types is error-prone
  • Runtime errors possible if cast is incorrect

Proposed Solution

No response

Alternatives Considered

No response

Additional Context

No response

Metadata

Metadata

Labels

candidateFeature candidatesfeature requestRequest for an enhancement / additional functionalityinternallangchain`langchain` package issues & PRs

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions