Overview
Context management in LangChain.js uses AsyncLocalStorage (Node.js) or equivalent mechanisms to maintain execution context without explicit parameter passing. This enables:- Scoped Variables: Share data between components without prop drilling
- Callback Hooks: Automatically attach callbacks to all executions
- Configuration Propagation: Pass settings down the execution tree
- Isolation: Each execution has its own context that doesn’t leak
Installation
Context Variables
Setting Context Variables
UsesetContextVariable() to store values that will be available to child runnables:
Getting Context Variables
UsegetContextVariable() to retrieve values set by parent runnables:
Context Scoping
Context variables follow these scoping rules:- Parent to Child: Child runnables inherit parent context
- Isolated Changes: Changes in child don’t affect parent
- Sibling Isolation: Sibling runnables have separate contexts
Formatted Strings with context
The context template tag provides clean, formatted string creation with automatic indentation handling:
Features
Automatic Indentation Stripping
Multi-line Value Alignment
Escape Sequences
Object Interpolation
Callback Hooks
Registering Configure Hooks
Automatically attach callback handlers to all runnable executions:Environment Variable Activation
Activate handlers based on environment variables:Hook Configuration Options
Common Patterns
User Context Tracking
Request-Scoped Logging
Feature Flags
A/B Testing
Environment Support
Context management requires AsyncLocalStorage or equivalent:- ✅ Node.js - Native AsyncLocalStorage support
- ✅ Deno - Compatible AsyncLocalStorage
- ✅ Cloudflare Workers - Supported
- ❌ Browser - Limited support (no AsyncLocalStorage)
- ⚠️ Edge Runtimes - Varies by platform
Best Practices
- Use for Cross-Cutting Concerns: Context variables are ideal for logging, tracing, auth, and configuration
- Don’t Overuse: For direct parent-child data passing, use function parameters
- Type Safety: Use TypeScript generics with
getContextVariable<T>() - Clean Naming: Use namespaced keys like
"app:user_id"to avoid collisions - Document Context Dependencies: Make it clear when functions depend on context
- Test Context Isolation: Verify that parallel executions don’t interfere
- Avoid Side Effects: Don’t use context variables for critical business logic
Debugging
Enable debugging to see context variable flow:Related
- Callbacks - Callback system for tracing and logging
- Runnables - Base runnable interface
- RunnableConfig - Configuration options for runnables
- LangSmith Tracing - Distributed tracing and observability
