UserContextMiddleware Class — langchain Architecture
Architecture documentation for the UserContextMiddleware class in test_middleware_typing.py from the langchain codebase.
Entity Profile
Dependency Diagram
graph TD 3c3b5386_19a6_3675_81a6_f2b04cf3c889["UserContextMiddleware"] 689eac1f_5845_440c_f60b_988968e02ee6["test_middleware_typing.py"] 3c3b5386_19a6_3675_81a6_f2b04cf3c889 -->|defined in| 689eac1f_5845_440c_f60b_988968e02ee6 6da020a2_43a2_7603_b53a_4d95dafc06e3["before_model()"] 3c3b5386_19a6_3675_81a6_f2b04cf3c889 -->|method| 6da020a2_43a2_7603_b53a_4d95dafc06e3 00fd3d3f_625e_3a68_8936_4823e0ec86b9["wrap_model_call()"] 3c3b5386_19a6_3675_81a6_f2b04cf3c889 -->|method| 00fd3d3f_625e_3a68_8936_4823e0ec86b9
Relationship Graph
Source Code
libs/langchain_v1/tests/unit_tests/agents/middleware_typing/test_middleware_typing.py lines 116–134
class UserContextMiddleware(AgentMiddleware[AgentState[Any], UserContext, Any]):
"""Middleware with correctly specified UserContext."""
def before_model(
self, state: AgentState[Any], runtime: Runtime[UserContext]
) -> dict[str, Any] | None:
# Full type safety - IDE knows these fields exist
_user_id: str = runtime.context["user_id"]
_user_name: str = runtime.context["user_name"]
return None
def wrap_model_call(
self,
request: ModelRequest[UserContext], # Correctly parameterized!
handler: Callable[[ModelRequest[UserContext]], ModelResponse[Any]],
) -> ModelResponse[Any]:
# request.runtime.context is UserContext - fully typed!
_user_id: str = request.runtime.context["user_id"]
return handler(request)
Source
Frequently Asked Questions
What is the UserContextMiddleware class?
UserContextMiddleware is a class in the langchain codebase, defined in libs/langchain_v1/tests/unit_tests/agents/middleware_typing/test_middleware_typing.py.
Where is UserContextMiddleware defined?
UserContextMiddleware is defined in libs/langchain_v1/tests/unit_tests/agents/middleware_typing/test_middleware_typing.py at line 116.
Analyze Your Own Codebase
Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.
Try Supermodel Free