Runtime context automatically injected into tools.
When a tool function has a parameter named tool_runtime with type hint
ToolRuntime, the tool execution system will automatically inject an instance
containing:
state: The current graph statetoolCallId: The ID of the current tool callconfig: RunnableConfig for the current executioncontext: Runtime contextstore: BaseStore instance for persistent storagewriter: Stream writer for streaming outputNo Annotated wrapper is needed - just use runtime: ToolRuntime
as a parameter.
ToolRuntime: RunnableConfig __typeimport { tool, type ToolRuntime } from "@langchain/core/tools";
import { z } from "zod";
const stateSchema = z.object({
messages: z.array(z.any()),
userId: z.string().optional(),
});
const greet = tool(
async ({ name }, runtime: ToolRuntime<typeof stateSchema>) => {
// Access state
const messages = runtime.state.messages;
// Access tool_call_id
console.log(`Tool call ID: ${runtime.toolCallId}`);
// Access config
console.log(`Run ID: ${runtime.config.runId}`);
// Access runtime context
const userId = runtime.context?.userId;
// Access store
await runtime.store?.mset([["key", "value"]]);
// Stream output
runtime.writer?.("Processing...");
return `Hello! User ID: ${runtime.state.userId || "unknown"} ${name}`;
},
{
name: "greet",
description: "Use this to greet the user once you found their info.",
schema: z.object({ name: z.string() }),
stateSchema,
}
);
const agent = createAgent({
model,
tools: [greet],
stateSchema,
contextSchema,
});