LangChain/Advanced
Intermediate7 min

Runtime & Context Injection

The Runtime object provides dependency injection for tools and middleware. Pass context_schema to create_agent, inject per-invocation data (user ID, connections) via context=, and access it anywhere via runtime.context.

Quick Reference

  • context_schema=MyContext on create_agent — defines the injectable context shape
  • agent.invoke(..., context=MyContext(user_id='u1')) — pass context at call time
  • runtime.context — access context in tools (via ToolRuntime) and middleware (via Runtime)
  • runtime.store — BaseStore for long-term memory (same object across tools and middleware)
  • runtime.stream_writer — emit custom stream events from tools

What Runtime Is

create_agent runs on LangGraph's runtime under the hood. The Runtime object carries three things into every tool and middleware call: context (static per-invocation config), store (long-term memory), and stream_writer (custom stream events). This is LangChain's dependency injection system — instead of hardcoding user IDs or database connections, you inject them at invocation time.

runtime.XWhat it isAccess in
runtime.contextImmutable config passed at invoke time — user ID, DB connection, tenantToolRuntime, Runtime
runtime.storeBaseStore for long-term persistent memoryToolRuntime, Runtime
runtime.stream_writerEmit arbitrary data to the 'custom' streamToolRuntime, Runtime