@convivainc/conviva-node-agent-sdk
v1.0.4
Published
Conviva NodeJS Agent SDK
Maintainers
Keywords
Readme
ConvivaAgentSDK Integration Guide
Overview
The ConvivaAgentSDK is a comprehensive Node.js SDK that provides automatic instrumentation, baggage propagation, and trace export for AI agent applications. It integrates seamlessly with popular frameworks like LangChain, OpenAI, and Anthropic.
Quick Start
1. Installation
npm install @convivainc/conviva-node-agent-sdk2. Basic Integration
import { ConvivaAgentSDK } from '@convivainc/conviva-node-agent-sdk';
// Initialize the SDK
await ConvivaAgentSDK.init({
customerKey: 'your-customer-key',
serviceName: 'your-service-name',
serviceVersion: '1.0.0'
});
// Your application code here
// SDK automatically instruments HTTP requests, database calls, and AI operations3. Environment Variables
Set these environment variables for configuration:
# Required
CONVIVA_CUSTOMER_KEY=your-customer-key
CONVIVA_SERVICE_NAME=your-service-name
CONVIVA_SERVICE_VERSION=1.0.0
# Optional - Custom endpoints
CONVIVA_TRACES_ENDPOINT=http://localhost:4317/v1/traces
CONVIVA_LOGS_ENDPOINT=http://localhost:4317/v1/logs
# Optional - Configuration
CONVIVA_AUTO_INSTRUMENTATION=true
CONVIVA_AUTO_BAGGAGE=true
CONVIVA_LOG_LEVEL=info
CONVIVA_SILENCE_INIT=falseCore APIs
ConvivaAgentSDK.init(options)
Initializes the SDK with configuration options.
Parameters:
customerKey(string): Your Conviva customer keyserviceName(string): Name of your serviceserviceVersion(string): Version of your servicetracesEndpoint(string, optional): Custom traces endpointlogsEndpoint(string, optional): Custom logs endpointautoInstrumentation(boolean, optional): Enable auto-instrumentation (default: true)autoBaggage(boolean, optional): Enable automatic baggage propagation (default: true)
Example:
await ConvivaAgentSDK.init({
customerKey: 'test-key',
serviceName: 'my-ai-agent',
serviceVersion: '1.0.0',
tracesEndpoint: 'http://localhost:4317/v1/traces'
});ConvivaAgentSDK.flush()
Manually flushes traces to the configured endpoint.
Example:
// Flush traces before application shutdown
await ConvivaAgentSDK.flush();ConvivaAgentSDK.shutdown()
Gracefully shuts down the SDK and flushes remaining traces.
Example:
// Shutdown SDK
await ConvivaAgentSDK.shutdown();ConvivaAgentSDK.attachTracingContext(key, value)
Attaches a single baggage key-value pair to the current context.
Parameters:
key(string): Baggage key (must be in allowed keys:c3.client_id,c3.convID)value(string): Baggage value
Example:
ConvivaAgentSDK.attachTracingContext('c3.client_id', 'client-123');
ConvivaAgentSDK.attachTracingContext('c3.convID', 'conv-456');ConvivaAgentSDK.attachMultipleTracingContext(baggageMap)
Attaches multiple baggage key-value pairs to the current context.
Parameters:
baggageMap(Map): Map of baggage key-value pairs
Example:
const baggageMap = new Map([
['c3.client_id', 'client-123'],
['c3.convID', 'conv-456']
]);
ConvivaAgentSDK.attachMultipleTracingContext(baggageMap);Framework Integration
LangChain Integration
The SDK automatically instruments LangChain operations. For manual integration:
import { ConvivaAgentSDK } from '@convivainc/conviva-node-agent-sdk';
// Initialize SDK
await ConvivaAgentSDK.init({
customerKey: process.env.CONVIVA_CUSTOMER_KEY,
serviceName: 'langchain-agent',
serviceVersion: '1.0.0'
});
// Your LangChain code is automatically instrumented
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor } from 'langchain/agents';
const llm = new ChatOpenAI({ modelName: 'gpt-3.5-turbo' });
// All LLM calls are automatically tracedExpress.js Integration
For Express.js applications, the SDK automatically instruments HTTP requests:
import express from 'express';
import { ConvivaAgentSDK } from '@convivainc/conviva-node-agent-sdk';
const app = express();
// Initialize SDK before defining routes
await ConvivaAgentSDK.init({
customerKey: process.env.CONVIVA_CUSTOMER_KEY,
serviceName: 'express-api',
serviceVersion: '1.0.0'
});
app.post('/api/chat', async (req, res) => {
// HTTP requests are automatically traced
// Baggage is automatically extracted from headers
const response = await processMessage(req.body.message);
res.json({ response });
});Baggage Propagation
The SDK automatically handles baggage propagation for distributed tracing:
Automatic Baggage Extraction
The SDK automatically extracts baggage from HTTP headers and makes it available throughout your application:
Manual Baggage Management
// Set baggage manually
ConvivaAgentSDK.attachTracingContext('c3.client_id', 'client-123');
// Set multiple baggage entries
const baggageMap = new Map([
['c3.client_id', 'client-123'],
['c3.convID', 'conv-456']
]);
ConvivaAgentSDK.attachMultipleTracingContext(baggageMap);
// Get baggage
const baggage = ConvivaAgentSDK.getBaggage('c3.client_id');
console.log('Client ID:', baggage);
// Get all baggage
const allBaggage = ConvivaAgentSDK.getAllBaggage();
console.log('All baggage:', allBaggage);Configuration Options
Environment Variables
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| CONVIVA_CUSTOMER_KEY | Your Conviva customer key | - | Yes |
| CONVIVA_SERVICE_NAME | Service name | - | Yes |
| CONVIVA_SERVICE_VERSION | Service version | - | Yes |
| CONVIVA_TRACES_ENDPOINT | Custom traces endpoint | Auto-detected | No |
| CONVIVA_LOGS_ENDPOINT | Custom logs endpoint | Auto-detected | No |
| CONVIVA_AUTO_INSTRUMENTATION | Enable auto-instrumentation | true | No |
| CONVIVA_AUTO_BAGGAGE | Enable automatic baggage | true | No |
| CONVIVA_LOG_LEVEL | Log level (debug, info, warn, error) | info | No |
| CONVIVA_SILENCE_INIT | Silence initialization messages | false | No |
| CONVIVA_SDK_DISABLED | Disable SDK completely | false | No |
InitOptions Interface
interface InitOptions {
customerKey?: string;
serviceName?: string;
serviceVersion?: string;
tracesEndpoint?: string;
logsEndpoint?: string;
autoInstrumentation?: boolean;
autoBaggage?: boolean;
logLevel?: 'debug' | 'info' | 'warn' | 'error';
silenceInitializationMessage?: boolean;
enabled?: boolean;
}Error Handling
The SDK includes comprehensive error handling:
try {
await ConvivaAgentSDK.init({
customerKey: 'invalid-key',
serviceName: 'test-service'
});
} catch (error) {
console.error('SDK initialization failed:', error.message);
// Handle initialization error
}
// SDK continues to work even if some features fail
// Check if SDK is available before using features
if (ConvivaAgentSDK.isAvailable()) {
ConvivaAgentSDK.attachTracingContext('c3.client_id', 'client-123');
}Performance Considerations
Batch Processing
The SDK uses batch processing for trace export by default:
// Disable batch processing for immediate export
await ConvivaAgentSDK.init({
customerKey: 'your-key',
serviceName: 'your-service',
disableBatch: true
});Periodic Flushing
For long-running applications, consider periodic flushing:
// Flush traces every 30 seconds
setInterval(async () => {
await ConvivaAgentSDK.flush();
}, 30000);Graceful Shutdown
Always flush traces before application shutdown:
process.on('SIGTERM', async () => {
await ConvivaAgentSDK.flush();
process.exit(0);
});
process.on('SIGINT', async () => {
await ConvivaAgentSDK.flush();
process.exit(0);
});Troubleshooting
Common Issues
SDK not initializing
- Check that
CONVIVA_CUSTOMER_KEYis set - Verify network connectivity to Conviva endpoints
- Check logs for initialization errors
- Check that
Traces not appearing
- Ensure
CONVIVA_TRACES_ENDPOINTis correctly configured - Check that the endpoint is accessible
- Verify that traces are being flushed
- Ensure
Baggage not propagating
- Ensure
CONVIVA_AUTO_BAGGAGEis enabled - Check that baggage keys are in the allowed list
- Verify that baggage is being set in the correct context
- Ensure
Debug Mode
Enable debug logging for troubleshooting:
await ConvivaAgentSDK.init({
customerKey: 'your-key',
serviceName: 'your-service',
logLevel: 'debug'
});Health Checks
Check SDK status:
// Check if SDK is available
if (ConvivaAgentSDK.isAvailable()) {
console.log('SDK is ready');
} else {
console.log('SDK is not available');
}
// Get SDK configuration
const config = ConvivaAgentSDK.getConfig();
console.log('SDK config:', config);Examples
Complete Express.js Example
import express from 'express';
import { ConvivaAgentSDK } from '@convivainc/conviva-node-agent-sdk';
const app = express();
app.use(express.json());
// Initialize SDK
await ConvivaAgentSDK.init({
customerKey: process.env.CONVIVA_CUSTOMER_KEY,
serviceName: 'ai-chat-api',
serviceVersion: '1.0.0',
tracesEndpoint: process.env.CONVIVA_TRACES_ENDPOINT
});
app.post('/api/chat', async (req, res) => {
try {
// Baggage is automatically extracted from headers
const response = await processAIRequest(req.body.message);
res.json({ response });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Graceful shutdown
process.on('SIGTERM', async () => {
await ConvivaAgentSDK.flush();
process.exit(0);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});LangChain Agent Example
import { ConvivaAgentSDK } from '@convivainc/conviva-node-agent-sdk';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor } from 'langchain/agents';
// Initialize SDK
await ConvivaAgentSDK.init({
customerKey: process.env.CONVIVA_CUSTOMER_KEY,
serviceName: 'langchain-agent',
serviceVersion: '1.0.0'
});
// Create LangChain components (automatically instrumented)
const llm = new ChatOpenAI({ modelName: 'gpt-3.5-turbo' });
const agent = new AgentExecutor({
agent: createAgent(llm),
tools: [calculatorTool, webSearchTool]
});
// Use agent (all operations are traced)
const result = await agent.call({
input: "What is 15 + 27?",
// Baggage is automatically propagated through the agent execution
});Support
For additional support and documentation:
- Check the Quick Start Guide
- Review the API Documentation
- See the Architecture Overview
- Explore the Sample Applications
License
This SDK is proprietary software. Please refer to your Conviva license agreement for usage terms and conditions.
