The init() function initializes the Gentrace SDK with your API credentials and configuration options. This function must be called early in your application setup to configure the SDK globally before using any other Gentrace functionality. Starting with the latest SDK versions, init() also automatically configures OpenTelemetry by default, eliminating the need for manual OpenTelemetry setup in most cases.

Basic usage

init.ts
import { init } from 'gentrace';

// Basic initialization with API key
init({
  apiKey: 'your-gentrace-api-key',
});

// Or using environment variable
init({
  apiKey: process.env.GENTRACE_API_KEY,
});
Getting an API Key: You can generate an API key by visiting https://gentrace.ai/s/api-keys

Overview

The init() function:
  1. Configures authentication with your Gentrace API key
  2. Sets up global client instances for making API requests
  3. Establishes connection settings like base URL, timeouts, and retry behavior
  4. Enables SDK functionality by making other Gentrace functions available
  5. Automatically configures OpenTelemetry (by default) with proper exporters and settings

Parameters

Stainless SDK Generation: The parameters and client options described in this section are automatically generated by the Stainless API SDK generation platform.

Function signatures

interface InitOptions extends ClientOptions {
  otelSetup?: boolean | SetupConfig;
}

function init(options: InitOptions = {}): void;

Parameters

options
ClientOptions
default:"{}"
Configuration options for initializing the Gentrace SDK client.

Advanced configuration

Automatic OpenTelemetry setup (default)

auto-otel.ts
import { init } from 'gentrace';

// OpenTelemetry is automatically configured by default
init({
  apiKey: process.env.GENTRACE_API_KEY,
});

// Same as explicitly setting otelSetup: true
init({
  apiKey: process.env.GENTRACE_API_KEY,
  otelSetup: true,
});

Custom OpenTelemetry configuration

custom-otel.ts
import { init, GentraceSampler } from 'gentrace';

init({
  apiKey: process.env.GENTRACE_API_KEY,
  otelSetup: {
    serviceName: 'my-ai-service',
    sampler: new GentraceSampler(),
    resourceAttributes: {
      'service.version': '1.0.0',
      'deployment.environment': 'production',
      'team': 'ai-platform',
    },
    // Add custom instrumentations if needed
    instrumentations: [],
  },
});

Custom OTEL collector endpoint

If you’re using your own OpenTelemetry collector, configure the trace exporter in the otelSetup configuration:
custom-collector.ts
import { init, GentraceSampler, interaction } from 'gentrace';
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';

init({
  apiKey: process.env.GENTRACE_API_KEY,
  otelSetup: {
    serviceName: 'my-ai-service',
    sampler: new GentraceSampler(),
    
    // Configure your custom OTEL collector endpoint
    traceEndpoint: 'http://localhost:4318/v1/traces',
    
    resourceAttributes: {
      'service.version': '1.0.0',
      'deployment.environment': 'production',
    },
  },
});

// Your instrumented functions will now send traces to your collector
const generateResponse = interaction(
  'generate-response',
  async (prompt: string) => {
    const result = await generateText({
      model: openai('gpt-4o'),
      prompt,
      experimental_telemetry: {
        isEnabled: true,
      },
    });
    return result.text;
  },
  {
    pipelineId: process.env.GENTRACE_PIPELINE_ID!,
  },
);
Common OTEL Collector configurations:
  • Local development: http://localhost:4318/v1/traces
  • Docker: http://otel-collector:4318/v1/traces
  • Kubernetes: http://otel-collector.observability.svc.cluster.local:4318/v1/traces
  • Cloud providers: Check your provider’s documentation for the correct endpoint

Disable automatic OpenTelemetry setup

manual-otel.ts
import { init } from 'gentrace';

// Disable automatic OpenTelemetry configuration
init({
  apiKey: process.env.GENTRACE_API_KEY,
  otelSetup: false,
});

// You must configure OpenTelemetry manually
// See the OpenTelemetry Setup guide for details

Custom base URL and timeout

custom-config.ts
import { init } from 'gentrace';

init({
  apiKey: process.env.GENTRACE_API_KEY,
  baseURL: 'https://your-custom-domain.com/api',
  timeout: 30000, // 30 seconds
  maxRetries: 5,
});

Custom headers and logging

headers-logging.ts
import { init } from 'gentrace';

init({
  apiKey: process.env.GENTRACE_API_KEY,
  defaultHeaders: {
    'X-Custom-Header': 'your-value',
    'User-Agent': 'MyApp/1.0.0',
  },
  logLevel: 'debug',
  logger: console, // or your custom logger
});

Environment variables

Instead of passing configuration options directly to init(), you can use environment variables:
  • GENTRACE_API_KEY: Your Gentrace API key
  • GENTRACE_BASE_URL: Custom base URL for the API (useful for self-hosted instances)
  • GENTRACE_LOG (TypeScript only): Log level setting
.env
# Set environment variables
export GENTRACE_API_KEY="your-gentrace-api-key"
export GENTRACE_BASE_URL="https://your-custom-domain.com/api"
env-init.ts
import { init } from 'gentrace';

// Initialize without parameters - uses environment variables
init();

Error handling

The init() function will throw an error if required configuration is missing:
error-handling.ts
import { init } from 'gentrace';

try {
  init({
    // Missing apiKey - will throw error if GENTRACE_API_KEY env var not set
  });
} catch (error) {
  console.error('Failed to initialize Gentrace:', error.message);
}
Automatic OpenTelemetry Setup: Starting with the latest SDK versions, init() automatically configures OpenTelemetry by default. This eliminates the need for manual OpenTelemetry setup in most cases. If you need custom OpenTelemetry configuration or want to disable automatic setup, use the otelSetup (TypeScript) or otel_setup (Python) parameter.

Best practices

1. Initialize early

Call init() before your main execution logic to ensure Gentrace is configured before using any tracing functionality:
early-init.ts
import { init, experiment, evalOnce } from 'gentrace';

// Initialize before using Gentrace functionality
init({
  apiKey: process.env.GENTRACE_API_KEY,
});

// Now you can use Gentrace functions
async function main() {
  await experiment('pipeline-id', async () => {
    // Your experiment code
  });
}

main();

2. Use environment variables

Store sensitive configuration like API keys in environment variables rather than hardcoding them:
# .env file
GENTRACE_API_KEY=your-gentrace-api-key
GENTRACE_BASE_URL=https://gentrace.ai/api

Requirements

  • API Key: A valid Gentrace API key is required. You can generate one at https://gentrace.ai/s/api-keys
  • Network Access: The SDK needs to communicate with the Gentrace API
  • Environment: Node.js 20+ (TypeScript) or Python 3.8+ (Python)