Skip to content
Go To Dashboard

LangChain Classic

The @sapiom/langchain-classic package provides component wrapper-based integration for LangChain v0.3+, enabling automatic cost tracking, session management, and payment handling by wrapping individual components.


Terminal window
npm install @sapiom/langchain-classic

The LangChain Classic integration requires these peer dependencies:

Terminal window
npm install @langchain/core @langchain/langgraph

Use createSapiomReactAgent for the simplest agent integration:

import { createSapiomReactAgent } from '@sapiom/langchain-classic';
import { ChatOpenAI } from '@langchain/openai';
import { TavilySearchResults } from '@langchain/community/tools/tavily_search';
// Define your tools
const tools = [
new TavilySearchResults({ maxResults: 3 })
];
// Create Sapiom-tracked agent with one function call
const agent = await createSapiomReactAgent(
{
llm: new ChatOpenAI({
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4',
temperature: 0
}),
tools
},
{
apiKey: process.env.SAPIOM_API_KEY,
traceId: 'agent-workflow', // optional
agentName: 'customer-support-bot',
failureMode: 'open'
}
);
// All operations (model + tools) are automatically tracked
const result = await agent.invoke({
messages: [
{ role: 'user', content: 'What is the weather in San Francisco?' }
]
});
console.log(result.messages);

For more granular control, wrap individual components:

import { SapiomChatOpenAI, wrapSapiomTool, wrapSapiomAgent } from '@sapiom/langchain-classic';
// Wrap model
const model = new SapiomChatOpenAI(
{ model: 'gpt-4' },
{ apiKey: process.env.SAPIOM_API_KEY }
);
// Wrap tools
const wrappedTool = wrapSapiomTool(myTool, {
apiKey: process.env.SAPIOM_API_KEY,
serviceName: 'weather-api'
});
// Wrap agent
const agent = wrapSapiomAgent(graph, {
apiKey: process.env.SAPIOM_API_KEY,
traceId: 'agent-workflow'
});

Enable streaming for real-time responses:

import { SapiomChatOpenAI } from '@sapiom/langchain-classic';
const model = new SapiomChatOpenAI({
apiKey: process.env.OPENAI_API_KEY,
sapiomApiKey: process.env.SAPIOM_API_KEY,
model: 'gpt-4',
streaming: true
});
const stream = await model.stream('Write a short poem about AI');
for await (const chunk of stream) {
process.stdout.write(chunk.content);
}

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
  • 'closed': Throw errors, block operations
traceId string

Workflow trace identifier for grouping related transactions

agentId string

Existing agent UUID/ID

agentName string

Agent name for find-or-create behavior

All standard ChatOpenAI options plus Sapiom-specific configuration:

apiKey string required

Your OpenAI API key

model string default: gpt-3.5-turbo

OpenAI model to use (e.g., gpt-4, gpt-4-turbo, gpt-3.5-turbo)

sapiomApiKey string required

Your Sapiom API key. Can also be set via SAPIOM_API_KEY environment variable

temperature number default: 0.7

Controls randomness (0-2). Lower values make output more focused

maxTokens number

Maximum tokens to generate in the response

streaming boolean default: false

Enable streaming responses

apiKey string required

Your Sapiom API key

serviceName string

Service identifier for the tool’s transactions

Terminal window
# Required
OPENAI_API_KEY=sk-...
SAPIOM_API_KEY=spk_...

The component wrappers automatically track:

  • Agent lifecycle - Start and end of agent transactions via wrapSapiomAgent
  • Model calls - Token estimation and actual usage via SapiomChatOpenAI
  • Tool calls - Pre-authorization via wrapSapiomTool
  • Payment handling - MCP x402 payment required responses with retry
  • Trace grouping - Workflow correlation across operations

Use Environment Variables

Never hardcode API keys:

import { SapiomChatOpenAI } from '@sapiom/langchain-classic';
// ✅ Good
const model = new SapiomChatOpenAI({
apiKey: process.env.OPENAI_API_KEY,
sapiomApiKey: process.env.SAPIOM_API_KEY
});
// ❌ Bad
const model = new SapiomChatOpenAI({
apiKey: 'sk-...',
sapiomApiKey: 'spk-...'
});
Choose the Right Integration Level
// Use createSapiomReactAgent for simplest setup
const agent = await createSapiomReactAgent(
{ llm, tools },
{ apiKey: process.env.SAPIOM_API_KEY }
);
// Use component wrappers for granular control
const model = new SapiomChatOpenAI({ ... });
const tool = wrapSapiomTool(myTool, { ... });
Use Trace IDs for Correlation

Group related operations with trace IDs:

import { createSapiomReactAgent } from '@sapiom/langchain-classic';
const agent = await createSapiomReactAgent(
{ llm, tools },
{
apiKey: process.env.SAPIOM_API_KEY,
traceId: `session-${sessionId}`,
agentName: 'customer-support',
}
);