The traced() function wraps any function with OpenTelemetry tracing to automatically track its execution. It creates a span for each function call, records input arguments and return values, and captures any exceptions that occur during execution.
The Gentrace SDK automatically configures OpenTelemetry when you call init(). If you have an existing OpenTelemetry setup or need custom configuration, see the manual setup guide.

Basic usage

import { init, traced } from 'gentrace';
import OpenAI from 'openai';

init({
  apiKey: process.env.GENTRACE_API_KEY,
});

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

async function generateResponse(prompt: string): Promise<string> {
  const response = await openai.chat.completions.create({
    model: 'o3',
    messages: [{ role: 'user', content: prompt }],
  });
  return response.choices[0].message.content || '';
}

const tracedGenerateResponse = traced('generateResponse', generateResponse);
const aiResponse = await tracedGenerateResponse('What is the capital of France?');
The Gentrace SDK automatically configures the GentraceSpanProcessor when you call init(), which simplifies the process of converting baggage values to span attributes, ensuring proper trace routing to Gentrace. For manual configuration details, see the OpenTelemetry setup guide.

Overview

The traced() function provides automatic instrumentation for any function in your codebase. It:
  1. Creates OpenTelemetry spans for each function execution with customizable names
  2. Records function arguments as span events for debugging and analysis
  3. Captures return values as span events to track function outputs
  4. Handles errors automatically by recording exceptions and setting appropriate span status
  5. Supports both sync and async functions with proper typing preservation
  6. Allows custom attributes to be attached to spans for enhanced observability

Parameters

/**
 * Wrap a function with OpenTelemetry tracing
 * 
 * @param name - The name for the OpenTelemetry span.
 *               This will appear in your tracing dashboard
 * @param fn - The function to wrap with tracing.
 *             Can be synchronous or asynchronous
 * @param config - Additional configuration options
 * @param config.attributes - Custom attributes to attach
 *                            to the span for additional context
 * 
 * @returns The wrapped function with the same signature
 *          but enhanced with tracing capabilities
 */
function traced<F extends (...args: any[]) => any>(
  name: string,
  fn: F,
  config?: {
    attributes?: Record<string, any>
  }
): F