LangChain
The @sapiom/langchain package provides middleware-based integration for LangChain v1.x, enabling automatic cost tracking, session management, and payment handling with minimal setup.
Installation
Section titled “Installation”npm install @sapiom/langchainpnpm add @sapiom/langchainyarn add @sapiom/langchainPeer Dependencies
Section titled “Peer Dependencies”The LangChain integration requires LangChain v1.x:
npm install langchainQuick Start
Section titled “Quick Start”Using the Middleware
Section titled “Using the Middleware”The LangChain v1.x integration uses a middleware-based approach for seamless tracking:
import { createAgent } from 'langchain';import { createSapiomMiddleware } from '@sapiom/langchain';
// Define your toolsconst tools = [getWeather, sendEmail];
// Create agent with Sapiom middlewareconst agent = createAgent({ model: 'gpt-4', tools, middleware: [ createSapiomMiddleware({ apiKey: process.env.SAPIOM_API_KEY, failureMode: 'open', // 'open' (graceful) or 'closed' (strict) traceId: 'my-workflow', agentName: 'customer-support-bot', }), ],});
// All tracking happens automatically!const result = await agent.invoke({ messages: [{ role: 'user', content: 'What is the weather in Tokyo?' }],});
console.log(result.messages);Per-Invocation Overrides
Section titled “Per-Invocation Overrides”Override configuration on individual calls using the context parameter:
await agent.invoke( { messages: [...] }, { context: { sapiomTraceId: 'conversation-456', sapiomAgentId: 'AG-002', }, });Configuration Options
Section titled “Configuration Options”createSapiomMiddleware Options
Section titled “createSapiomMiddleware Options”apiKey string required Your Sapiom API key. Can also be set via SAPIOM_API_KEY environment variable
enabled boolean default: true Enable or disable Sapiom tracking
failureMode 'open' | 'closed' default: open How to handle tracking failures:
'open'(default): Log errors, continue without tracking (prioritizes availability)'closed': Throw errors, block operations (prioritizes security)
Note: Authorization denials always throw regardless of failure mode
traceId string Workflow trace identifier for grouping related transactions
agentId string Existing agent UUID/ID to use
agentName string Agent name for find-or-create behavior
serviceName string Service identifier for transactions
Per-Invocation Context Options
Section titled “Per-Invocation Context Options”These can be passed in the context parameter when invoking the agent:
sapiomTraceId string Override trace ID for this invocation
sapiomAgentId string Override agent ID for this invocation
Environment Variables
Section titled “Environment Variables”# RequiredSAPIOM_API_KEY=spk_...
# Your LLM provider keysOPENAI_API_KEY=sk-...What Gets Tracked
Section titled “What Gets Tracked”The middleware automatically tracks:
- Agent lifecycle - Start and end of agent transactions
- Model calls - Token estimation and actual usage
- Tool calls - Pre-authorization before execution
- Payment handling - MCP x402 payment required responses
- Trace grouping - Workflow correlation across operations
Best Practices
Section titled “Best Practices”Use Environment Variables
Never hardcode API keys:
// ✅ GoodcreateSapiomMiddleware({ apiKey: process.env.SAPIOM_API_KEY,});
// ❌ BadcreateSapiomMiddleware({ apiKey: 'spk_...',});Choose Appropriate Failure Mode
// For production - prioritize availabilitycreateSapiomMiddleware({ apiKey: process.env.SAPIOM_API_KEY, failureMode: 'open', // Continues even if tracking fails});
// For sensitive operations - prioritize securitycreateSapiomMiddleware({ apiKey: process.env.SAPIOM_API_KEY, failureMode: 'closed', // Blocks if tracking fails});Use Trace IDs for Correlation
Group related operations with trace IDs:
const middleware = createSapiomMiddleware({ apiKey: process.env.SAPIOM_API_KEY, traceId: `session-${sessionId}`, agentName: 'customer-support',});