Inject request-scoped dependencies
A tool needs to query a database selected for the current request.
AI Agents · Const
Context is static, per-run information made available to an agent through its Runtime. Define its shape with contextSchema, pass values via the invocation context option, and access them in tools or middleware.
A Context object is per-run information supplied separately from conversation state, such as a user identifier, database connection, or feature flag. Define its shape with contextSchema, pass values through the context invocation option, and read them from runtime.context in tools or middleware.
const agent = createAgent({ contextSchema });
await agent.invoke(input, { context });| Name | Type | Description |
|---|---|---|
contextSchema | Zod schema | Zod schema describing the runtime context shape. |
context | ContextType | Per-run values supplied in the invocation options. |
An agent result containing the invocation output; the documentation does not specify a distinct return type for the context object.
import { createAgent } from "langchain";
import * as z from "zod";
const ContextSchema = z.object({
userId: z.string(),
});
const agent = createAgent({
model: "openai:gpt-4.1-mini",
tools: [],
contextSchema: ContextSchema,
});
const result = await agent.invoke(
{ messages: [{ role: "user", content: "Hello" }] },
{ context: { userId: "user-123" } },
);
console.log(result);
Defines per-run context and supplies it when invoking the agent; tools or middleware can read it through the runtime.
A tool needs to query a database selected for the current request.
Middleware personalizes behavior using the authenticated account.
A deployment enables or disables behavior per invocation.
Define a schema with contextSchema when creating the agent, then provide matching values in the context field of the invocation options. Tools and middleware access those values through the runtime context.
Follow-up: How should conversation identity differ from runtime configuration? Use thread_id for message history and checkpoints, and context for data needed only during that run.
Context carries static information such as user metadata, database connections, or other dependencies for one agent invocation. It avoids putting those dependencies in global state, which supports stateless and reusable code.
Follow-up: What should happen when a value must evolve during execution? Put mutable run data in graph state rather than static runtime context.
The context schema describes the structure of the context stored in the agent runtime. The invocation supplies the actual context object, and application code can consume it through runtime.context.
Follow-up: Is context automatically visible to the model? No; a tool, middleware, or other logic must read it and add relevant information to the prompt or messages.
Runtimeruntime.contextcontextSchemathread_idStateGraph