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.
Installation
Section titled “Installation”npm install @sapiom/langchain-classicpnpm add @sapiom/langchain-classicyarn add @sapiom/langchain-classicPeer Dependencies
Section titled “Peer Dependencies”The LangChain Classic integration requires these peer dependencies:
npm install @langchain/core @langchain/langgraphQuick Start
Section titled “Quick Start”Creating an Agent
Section titled “Creating an Agent”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 toolsconst tools = [ new TavilySearchResults({ maxResults: 3 })];
// Create Sapiom-tracked agent with one function callconst 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 trackedconst result = await agent.invoke({ messages: [ { role: 'user', content: 'What is the weather in San Francisco?' } ]});
console.log(result.messages);Using Component Wrappers
Section titled “Using Component Wrappers”For more granular control, wrap individual components:
import { SapiomChatOpenAI, wrapSapiomTool, wrapSapiomAgent } from '@sapiom/langchain-classic';
// Wrap modelconst model = new SapiomChatOpenAI( { model: 'gpt-4' }, { apiKey: process.env.SAPIOM_API_KEY });
// Wrap toolsconst wrappedTool = wrapSapiomTool(myTool, { apiKey: process.env.SAPIOM_API_KEY, serviceName: 'weather-api'});
// Wrap agentconst agent = wrapSapiomAgent(graph, { apiKey: process.env.SAPIOM_API_KEY, traceId: 'agent-workflow'});Streaming Responses
Section titled “Streaming Responses”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);}Configuration Options
Section titled “Configuration Options”createSapiomReactAgent Options
Section titled “createSapiomReactAgent 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'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
SapiomChatOpenAI Options
Section titled “SapiomChatOpenAI Options”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
wrapSapiomTool Options
Section titled “wrapSapiomTool Options”apiKey string required Your Sapiom API key
serviceName string Service identifier for the tool’s transactions
Environment Variables
Section titled “Environment Variables”# RequiredOPENAI_API_KEY=sk-...SAPIOM_API_KEY=spk_...What Gets Tracked
Section titled “What Gets Tracked”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
Best Practices
Section titled “Best Practices”Use Environment Variables
Never hardcode API keys:
import { SapiomChatOpenAI } from '@sapiom/langchain-classic';
// ✅ Goodconst model = new SapiomChatOpenAI({ apiKey: process.env.OPENAI_API_KEY, sapiomApiKey: process.env.SAPIOM_API_KEY});
// ❌ Badconst model = new SapiomChatOpenAI({ apiKey: 'sk-...', sapiomApiKey: 'spk-...'});Choose the Right Integration Level
// Use createSapiomReactAgent for simplest setupconst agent = await createSapiomReactAgent( { llm, tools }, { apiKey: process.env.SAPIOM_API_KEY });
// Use component wrappers for granular controlconst 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', });