docs
Complete API reference for managing execution context across async operations in LangChain applications.
/**
* Context utilities for managing execution context
*/
const context: {
/**
* Get a value from the current context
* @param key - Context key
* @returns Value or undefined if not found
*/
get<T>(key: string): T | undefined;
/**
* Set a value in the current context
* @param key - Context key
* @param value - Value to store
*/
set<T>(key: string, value: T): void;
/**
* Run a function with the current context
* @param callback - Function to execute
* @returns Return value of callback
*/
run<T>(callback: () => T): T;
/**
* Run an async function with the current context
* @param callback - Async function to execute
* @returns Promise resolving to callback return value
*/
runAsync<T>(callback: () => Promise<T>): Promise<T>;
};import { context } from "langchain";
// Set context value
context.set("userId", "user123");
context.set("sessionId", "session456");
// Get context value
const userId = context.get<string>("userId");
const sessionId = context.get<string>("sessionId");
console.log(userId); // "user123"
console.log(sessionId); // "session456"import { context } from "langchain";
// Run synchronous function with context
const result = context.run(() => {
context.set("operation", "process");
// Context is available within this scope
const operation = context.get<string>("operation");
console.log(operation); // "process"
return "result";
});import { context } from "langchain";
// Run async function with context
await context.runAsync(async () => {
context.set("requestId", "req123");
// Make async call - context is preserved
await someAsyncOperation();
// Context still available
const requestId = context.get<string>("requestId");
console.log(requestId); // "req123"
});import { createAgent, context } from "langchain";
// Create agent
const agent = createAgent({
model: "openai:gpt-4o",
tools: [],
});
// Run with context
await context.runAsync(async () => {
// Set context for this invocation
context.set("userId", "user123");
context.set("traceId", "trace456");
// Invoke agent - context propagates through execution
const result = await agent.invoke({
messages: [{ role: "user", content: "Hello" }],
});
// Context available after invocation
const traceId = context.get<string>("traceId");
console.log(`Completed with trace: ${traceId}`);
});import { tool, context } from "langchain";
import { z } from "zod";
const contextAwareTool = tool(
async ({ input }) => {
// Access context within tool execution
const userId = context.get<string>("userId");
const sessionId = context.get<string>("sessionId");
console.log(`Tool called by user ${userId} in session ${sessionId}`);
return `Processed: ${input}`;
},
{
name: "context_aware_tool",
description: "A tool that uses execution context",
schema: z.object({
input: z.string(),
}),
}
);
// Use with agent and context
await context.runAsync(async () => {
context.set("userId", "user123");
context.set("sessionId", "session456");
const agent = createAgent({
model: "openai:gpt-4o",
tools: [contextAwareTool],
});
await agent.invoke({
messages: [{ role: "user", content: "Test the tool" }],
});
});import { context } from "langchain";
function log(message: string) {
const requestId = context.get<string>("requestId");
const userId = context.get<string>("userId");
console.log(`[${requestId}] [${userId}] ${message}`);
}
await context.runAsync(async () => {
context.set("requestId", "req-123");
context.set("userId", "user-456");
log("Starting operation"); // [req-123] [user-456] Starting operation
await performOperation();
log("Operation completed"); // [req-123] [user-456] Operation completed
});import { context, createAgent } from "langchain";
async function handleRequest(userId: string, message: string) {
await context.runAsync(async () => {
// Set request context
context.set("requestId", crypto.randomUUID());
context.set("userId", userId);
context.set("timestamp", Date.now());
try {
const agent = createAgent({
model: "openai:gpt-4o",
tools: [],
});
const result = await agent.invoke({
messages: [{ role: "user", content: message }],
});
// Context available for logging
const requestId = context.get<string>("requestId");
console.log(`Request ${requestId} completed successfully`);
return result;
} catch (error) {
const requestId = context.get<string>("requestId");
console.error(`Request ${requestId} failed:`, error);
throw error;
}
});
}import { context } from "langchain";
await context.runAsync(async () => {
context.set("level", "outer");
console.log(context.get("level")); // "outer"
await context.runAsync(async () => {
// Inner context inherits from outer
console.log(context.get("level")); // "outer"
// Set in inner context
context.set("level", "inner");
console.log(context.get("level")); // "inner"
});
// Outer context unchanged
console.log(context.get("level")); // "outer"
});runAsync for async operationsrun/runAsync