Skip to content
Go To Dashboard

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.


Terminal window
npm install @sapiom/langchain

The LangChain integration requires LangChain v1.x:

Terminal window
npm install langchain

The LangChain v1.x integration uses a middleware-based approach for seamless tracking:

import { createAgent } from 'langchain';
import { createSapiomMiddleware } from '@sapiom/langchain';
// Define your tools
const tools = [getWeather, sendEmail];
// Create agent with Sapiom middleware
const 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);

Override configuration on individual calls using the context parameter:

await agent.invoke(
{ messages: [...] },
{
context: {
sapiomTraceId: 'conversation-456',
sapiomAgentId: 'AG-002',
},
}
);

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

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

Terminal window
# Required
SAPIOM_API_KEY=spk_...
# Your LLM provider keys
OPENAI_API_KEY=sk-...

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

Use Environment Variables

Never hardcode API keys:

// ✅ Good
createSapiomMiddleware({
apiKey: process.env.SAPIOM_API_KEY,
});
// ❌ Bad
createSapiomMiddleware({
apiKey: 'spk_...',
});
Choose Appropriate Failure Mode
// For production - prioritize availability
createSapiomMiddleware({
apiKey: process.env.SAPIOM_API_KEY,
failureMode: 'open', // Continues even if tracking fails
});
// For sensitive operations - prioritize security
createSapiomMiddleware({
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',
});