Skip to main content
All examples are available on GitHub: respan-example-projects/typescript/tracing_sdk_example

Setup

All examples require:
npm install @respan/tracing
Configure your .env file:
.env
RESPAN_API_KEY=your_respan_api_key
RESPAN_BASE_URL=https://api.respan.ai
OPENAI_API_KEY=your_openai_api_key  # Optional
ANTHROPIC_API_KEY=your_anthropic_api_key  # Optional

Basic Usage

From basic_usage.ts. Core concepts: withWorkflow, withTask, withAgent, withTool.
import { RespanTelemetry } from '@respan/tracing';

const respanAi = new RespanTelemetry({
    apiKey: process.env.RESPAN_API_KEY,
    baseURL: process.env.RESPAN_BASE_URL,
    appName: 'basic-example',
    disableBatch: true,
    logLevel: 'info'
});

const generateResponse = async (prompt: string) => {
    return await respanAi.withTask(
        { name: 'generate_response', version: 1 },
        async () => {
            await new Promise(resolve => setTimeout(resolve, 100));
            return `Response to: ${prompt}`;
        }
    );
};

const chatWorkflow = async (userMessage: string) => {
    return await respanAi.withWorkflow(
        { 
            name: 'chat_workflow', 
            version: 1,
            associationProperties: { 'user_type': 'demo' }
        },
        async () => {
            const response = await generateResponse(userMessage);
            
            await respanAi.withTask(
                { name: 'log_interaction' },
                async () => {
                    console.log(`User: ${userMessage}`);
                    console.log(`Assistant: ${response}`);
                    return 'logged';
                }
            );
            
            return response;
        }
    );
};

async function main() {
    await respanAi.initialize();
    
    console.log('=== Workflow Example ===');
    const workflowResponse = await chatWorkflow('What is the weather like?');
    console.log('Workflow Response:', workflowResponse);
    
    await respanAi.shutdown();
}

main();
Run it:
npx tsx basic_usage.ts

OpenAI Integration

From openai_integration.ts. Automatic instrumentation of the OpenAI SDK.
import OpenAI from "openai";
import { RespanTelemetry } from "@respan/tracing";

const respan = new RespanTelemetry({
  apiKey: process.env.RESPAN_API_KEY,
  appName: "openai-integration-test",
  instrumentModules: {
    openAI: OpenAI,  // Automatically instrument OpenAI SDK
  },
  logLevel: 'info'
});

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function runOpenAIIntegrationTest() {
  console.log("🚀 Starting OpenAI Integration Test\n");

  await respan.initialize();

  await respan.withWorkflow(
    { name: "openai_chat_completion" },
    async () => {
      console.log("📝 Sending request to OpenAI...");
      
      const completion = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "Tell me a short joke about programming." }
        ],
      });

      console.log("📥 OpenAI Response:", completion.choices[0].message.content);
    }
  );

  await respan.shutdown();
  console.log("✅ Done!");
}

runOpenAIIntegrationTest();
Run it:
npx tsx openai_integration.ts

Advanced Agentic Workflow

From advanced_tracing.ts. Demonstrates withAgent, withTool, and custom metadata for complex agent workflows.
import { RespanTelemetry } from '@respan/tracing';
import OpenAI from 'openai';

const respanAi = new RespanTelemetry({
    apiKey: process.env.RESPAN_API_KEY,
    baseURL: process.env.RESPAN_BASE_URL,
    appName: 'advanced-tracing-example',
    instrumentModules: {
        openAI: OpenAI,
    },
    disableBatch: true,
    logLevel: 'info'
});

const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
});

const runAgentExample = async (query: string) => {
    return await respanAi.withAgent(
        { 
            name: 'research_assistant',
            associationProperties: { 
                'user_id': 'user_123',
                'session_id': 'session_abc' 
            }
        },
        async () => {
            console.log(`🤖 Agent received query: ${query}`);

            // Tool 1: Query analyzer
            const analysis = await respanAi.withTool(
                { name: 'query_analyzer' },
                async () => {
                    console.log('🔍 Analyzing query...');
                    await new Promise(resolve => setTimeout(resolve, 300));
                    return {
                        topic: query.toLowerCase().includes('ai') ? 'technology' : 'general',
                        sentiment: 'neutral'
                    };
                }
            );

            // Tool 2: Web search
            const searchResults = await respanAi.withTool(
                { name: 'web_search' },
                async () => {
                    console.log('🌐 Searching the web...');
                    return `Found some information about ${analysis.topic}`;
                }
            );

            // Task: Final generation with OpenAI
            const finalResponse = await respanAi.withTask(
                { name: 'final_generation' },
                async () => {
                    console.log('✍️ Generating final response...');
                    const completion = await openai.chat.completions.create({
                        model: 'gpt-3.5-turbo',
                        messages: [
                            { role: 'system', content: `You are a research assistant. Topic: ${analysis.topic}. Info: ${searchResults}` },
                            { role: 'user', content: query }
                        ],
                    });
                    return completion.choices[0].message.content;
                }
            );

            return {
                analysis,
                searchResults,
                finalResponse
            };
        }
    );
};

async function main() {
    await respanAi.initialize();
    console.log('🚀 Starting Advanced Tracing Example\n');

    const result = await runAgentExample('How is AI changing software development?');
    console.log('\n✨ Agent Execution Result:', JSON.stringify(result, null, 2));

    await respanAi.shutdown();
}

main();
Run it:
npx tsx advanced_tracing.ts

Span Management

Using getClient() API to manually update spans, add events, and record exceptions.
import { RespanTelemetry } from '@respan/tracing';

const respanAi = new RespanTelemetry({
    apiKey: process.env.RESPAN_API_KEY,
    appName: 'span-management-example',
});

await respanAi.initialize();

await respanAi.withTask(
    { name: 'data_processing' },
    async () => {
        const client = respanAi.getClient();
        
        // Update current span with custom metadata
        client.updateCurrentSpan({
            respan_params: {
                customer_identifier: 'user_123',
                metadata: { stage: 'processing' }
            },
            attributes: { 'custom.stage': 'validation' }
        });
        
        // Add an event to the span
        client.addSpanEvent('validation_started', { 
            input_length: 100 
        });
        
        try {
            // Your processing logic here
            const data = await processData();
            
            // Record success
            client.updateCurrentSpan({
                status: 'OK',
                attributes: { 'validation.result': 'success' }
            });
            
            return data;
        } catch (error) {
            // Record exception
            client.recordSpanException(error);
            client.updateCurrentSpan({
                status: 'ERROR',
                attributes: { 'validation.result': 'failed' }
            });
            throw error;
        }
    }
);

await respanAi.shutdown();

Multi-Provider Tracing

From multi_provider.ts. Trace across multiple AI providers (OpenAI + Anthropic) in a single workflow.
import OpenAI from 'openai';
import Anthropic from '@anthropic-ai/sdk';
import { RespanTelemetry } from '@respan/tracing';

const respanAi = new RespanTelemetry({
    apiKey: process.env.RESPAN_API_KEY,
    appName: 'multi-provider-example',
    instrumentModules: {
        openAI: OpenAI,
        anthropic: Anthropic
    }
});

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

await respanAi.initialize();

await respanAi.withWorkflow(
    { name: 'multi_provider_comparison' },
    async () => {
        // OpenAI call
        const openaiResponse = await respanAi.withTask(
            { name: 'openai_completion' },
            async () => {
                return await openai.chat.completions.create({
                    model: 'gpt-3.5-turbo',
                    messages: [{ role: 'user', content: 'Hello!' }]
                });
            }
        );

        // Anthropic call
        const anthropicResponse = await respanAi.withTask(
            { name: 'anthropic_completion' },
            async () => {
                return await anthropic.messages.create({
                    model: 'claude-3-haiku-20240307',
                    max_tokens: 100,
                    messages: [{ role: 'user', content: 'Hello!' }]
                });
            }
        );

        return { openaiResponse, anthropicResponse };
    }
);

await respanAi.shutdown();
Run it:
npx tsx multi_provider.ts

Agent with Multiple Tools

Example of an assistant agent using multiple tools for analysis and response generation.
const assistantAgent = async (query: string) => {
    return await respanAi.withAgent(
        { 
            name: 'assistant_agent',
            associationProperties: { 'agent_type': 'general' }
        },
        async () => {
            // Tool 1: Query analyzer
            const analysis = await respanAi.withTool(
                { name: 'query_analyzer' },
                async () => {
                    return {
                        intent: query.includes('?') ? 'question' : 'statement',
                        length: query.length,
                        complexity: query.split(' ').length > 10 ? 'high' : 'low'
                    };
                }
            );
            
            // Tool 2: Response generator
            const response = await respanAi.withTool(
                { name: 'response_generator' },
                async () => {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    return `Response based on analysis: ${JSON.stringify(analysis)}`;
                }
            );
            
            return {
                analysis,
                response
            };
        }
    );
};

// Usage
const result = await assistantAgent('Can you explain quantum computing?');
console.log('Agent Response:', result);

API Reference

MethodDescription
withWorkflowHigh-level grouping of tasks (top-level trace)
withTaskDiscrete step within a workflow
withAgentSpecialized for agentic patterns
withToolTool/function calls within agents
getClient()Access manual span management methods
initialize()Initialize tracing (required)
shutdown()Gracefully shutdown and flush spans

Client Methods

MethodDescription
updateCurrentSpanUpdate name, attributes, status, Respan params
addSpanEventAdd a timestamped event to current span
recordSpanExceptionRecord an error on current span
getCurrentTraceIdGet the current trace ID
getCurrentSpanIdGet the current span ID
flushManually flush pending spans

More Examples

Explore additional examples in the GitHub repository: View all TypeScript examples on GitHub →