> ## Documentation Index
> Fetch the complete documentation index at: https://next.gentrace.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Initialization

> Use init() to setup the Gentrace SDK with your API credentials and configuration

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

<CodeGroup dropdown>
  ```typescript init.ts theme={null}
  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,
  });
  ```

  ```python init.py theme={null}
  from gentrace import init

  # Basic initialization with API key
  init(api_key="your-gentrace-api-key")

  # Or using environment variable
  import os
  from gentrace import init

  init(api_key=os.environ["GENTRACE_API_KEY"])
  ```
</CodeGroup>

<Tip>
  **Getting an API Key**: Generate an API key by visiting
  [https://gentrace.ai/s/api-keys](https://gentrace.ai/s/api-keys)
</Tip>

## 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

<Info>
  **Stainless SDK Generation**: The parameters and client options
  described in this section are automatically generated by the
  [Stainless](https://www.stainless.com/) API SDK generation platform.
</Info>

### Function signatures

<CodeGroup dropdown>
  ```typescript theme={null}
  interface InitOptions extends ClientOptions {
    otelSetup?: boolean | SetupConfig;
  }

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

  ```python theme={null}
  def init(
      *,
      api_key: Optional[str] = None,
      base_url: Optional[str] = None,
      otel_setup: Union[bool, Dict[str, Any]] = True,
      **kwargs: Any
  ) -> None
  ```
</CodeGroup>

### Parameters

<Tabs>
  <Tab title="TypeScript">
    <ResponseField name="options" type="ClientOptions" default="{}">
      Configuration options for initializing the Gentrace SDK client.

      <Expandable title="ClientOptions" defaultOpen>
        <ResponseField name="apiKey" type="string">
          Your Gentrace API key. If not provided, the SDK will attempt to use the `GENTRACE_API_KEY` environment variable.

          Generate an API key at [https://gentrace.ai/s/api-keys](https://gentrace.ai/s/api-keys)
        </ResponseField>

        <ResponseField name="baseURL" type="string | null">
          Override the default base URL for the API.

          Defaults to `GENTRACE_BASE_URL` environment variable or `https://gentrace.ai/api`.

          This is particularly useful for self-hosted Gentrace instances (e.g., `http://self-hosted-gentrace.example.com/api`)
        </ResponseField>

        <ResponseField name="timeout" type="number">
          Maximum time in milliseconds to wait for a response from the server before timing out a single request.
        </ResponseField>

        <ResponseField name="maxRetries" type="number" default="2">
          Maximum number of times to retry a request in case of temporary failure.
        </ResponseField>

        <ResponseField name="defaultHeaders" type="HeadersLike">
          Default headers to include with every request to the API.

          Example:

          ```typescript theme={null}
          {
            'X-Custom-Header': 'your-value',
            'User-Agent': 'MyApp/1.0.0'
          }
          ```
        </ResponseField>

        <ResponseField name="defaultQuery" type="Record<string, string | undefined>">
          Default query parameters to include with every request to the API.
        </ResponseField>

        <ResponseField name="logLevel" type="'debug' | 'info' | 'warn' | 'error'">
          Set the log level for SDK operations.

          Defaults to `GENTRACE_LOG` environment variable or `'warn'`
        </ResponseField>

        <ResponseField name="logger" type="Logger">
          Custom logger instance for SDK logging.

          Defaults to `globalThis.console`
        </ResponseField>

        <ResponseField name="fetchOptions" type="RequestInit">
          Additional options to be passed to underlying `fetch` calls.
        </ResponseField>

        <ResponseField name="fetch" type="Fetch">
          Custom `fetch` function implementation for making HTTP requests.
        </ResponseField>

        <ResponseField name="otelSetup" type="boolean | SetupConfig" default="true">
          OpenTelemetry setup configuration. Controls automatic OpenTelemetry configuration.

          * `true` (default): Automatically configures OpenTelemetry with default settings
          * `false`: Disables automatic OpenTelemetry configuration
          * `SetupConfig`: Custom configuration object for OpenTelemetry

          <Expandable title="SetupConfig" defaultOpen>
            <ResponseField name="serviceName" type="string">
              The service name for your application. If not provided, attempts to auto-detect from package.json.
            </ResponseField>

            <ResponseField name="sampler" type="Sampler">
              Custom sampler instance. Defaults to `new GentraceSampler()` which samples traces with `gentrace.sample=true` in baggage. Gentrace wrapper functions add this flag automatically.

              When running experiments, the SDK also adds `gentrace.in_experiment=true` to the baggage to mark test spans, preventing production evaluations from running on test data.
            </ResponseField>

            <ResponseField name="resourceAttributes" type="Record<string, string | number>">
              Additional resource attributes to include with all spans.

              Example:

              ```typescript theme={null}
              {
                'service.version': '1.0.0',
                'deployment.environment': 'production'
              }
              ```
            </ResponseField>

            <ResponseField name="instrumentations" type="Instrumentation[]">
              Array of OpenTelemetry instrumentations to enable. Useful for auto-instrumenting libraries.
            </ResponseField>

            <ResponseField name="traceEndpoint" type="string">
              Custom OTLP endpoint URL. Defaults to Gentrace's OTLP endpoint.

              Example: `http://localhost:4318/v1/traces`
            </ResponseField>

            <ResponseField name="spanProcessors" type="SpanProcessor[]">
              Additional span processors to add to the tracer provider.
            </ResponseField>

            <ResponseField name="contextManager" type="ContextManager">
              Custom context manager. Defaults to `AsyncLocalStorageContextManager`.
            </ResponseField>

            <ResponseField name="propagator" type="TextMapPropagator">
              Custom propagator for context propagation. Defaults to W3C Trace Context propagator.
            </ResponseField>
          </Expandable>
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Tab>

  <Tab title="Python">
    <ResponseField name="api_key" type="string">
      Your Gentrace API key. If not provided, the SDK will attempt to use
      the `GENTRACE_API_KEY` environment variable. Generate an API key at
      [https://gentrace.ai/s/api-keys](https://gentrace.ai/s/api-keys)
    </ResponseField>

    <ResponseField name="base_url" type="string">
      Override the default base URL for the API. Defaults to
      `GENTRACE_BASE_URL` environment variable or
      `https://gentrace.ai/api`. This is particularly useful for
      self-hosted Gentrace instances (e.g.,
      `http://self-hosted-gentrace.example.com/api`)
    </ResponseField>

    <ResponseField name="otel_setup" type="bool | dict" default="True">
      OpenTelemetry setup configuration. Controls automatic OpenTelemetry configuration.

      * `True` (default): Automatically configures OpenTelemetry with default settings
      * `False`: Disables automatic OpenTelemetry configuration
      * `dict`: Custom configuration dictionary for OpenTelemetry

      <Expandable title="Configuration options" defaultOpen>
        <ResponseField name="service_name" type="str">
          The service name for your application. If not provided, attempts to auto-detect from pyproject.toml or setup.py.
        </ResponseField>

        <ResponseField name="sampler" type="Sampler">
          Custom sampler instance. Defaults to `GentraceSampler()` which samples traces with `gentrace.sample=true` in baggage. Gentrace wrapper functions add this flag automatically.

          When running experiments, the SDK also adds `gentrace.in_experiment=true` to the baggage to mark test spans, preventing production evaluations from running on test data.
        </ResponseField>

        <ResponseField name="resource_attributes" type="Dict[str, Union[str, int, float, bool]]">
          Additional resource attributes to include with all spans.

          Example:

          ```python theme={null}
          {
              "service.version": "1.0.0",
              "deployment.environment": "production"
          }
          ```
        </ResponseField>

        <ResponseField name="instrumentations" type="List[BaseInstrumentor]">
          List of OpenTelemetry instrumentation instances to enable. Useful for auto-instrumenting libraries like OpenAI, Anthropic, etc.

          Example:

          ```python theme={null}
          from openinference.instrumentation.openai import OpenAIInstrumentor

          instrumentations=[OpenAIInstrumentor()]
          ```
        </ResponseField>

        <ResponseField name="trace_endpoint" type="str">
          Custom OTLP endpoint URL. Defaults to Gentrace's OTLP endpoint.
        </ResponseField>

        <ResponseField name="debug" type="bool" default="False">
          Enable console exporter for debugging. When `True`, spans are also printed to console.
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="**kwargs" type="Any">
      Additional keyword arguments passed to the underlying client constructors.

      <Expandable title="Additional options">
        <ResponseField name="timeout" type="float | Timeout">
          Maximum time to wait for a response from the server.

          Can be a float representing seconds or a more complex timeout configuration.
        </ResponseField>

        <ResponseField name="max_retries" type="int" default="2">
          Maximum number of times to retry a request in case of temporary failure.
        </ResponseField>

        <ResponseField name="default_headers" type="Mapping[str, str]">
          Default headers to include with every request to the API.

          Example:

          ```python theme={null}
          {
              "X-Custom-Header": "your-value",
              "User-Agent": "MyApp/1.0.0"
          }
          ```
        </ResponseField>

        <ResponseField name="default_query" type="Mapping[str, object]">
          Default query parameters to include with every request to the API.
        </ResponseField>

        <ResponseField name="http_client" type="httpx.Client">
          Custom HTTP client instance for making requests.

          This allows for advanced customization of the underlying HTTP behavior.
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Tab>
</Tabs>

## Advanced configuration

### Automatic OpenTelemetry setup (default)

<CodeGroup dropdown>
  ```typescript auto-otel.ts theme={null}
  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,
  });
  ```

  ```python auto_otel.py theme={null}
  import gentrace
  import os

  # OpenTelemetry is automatically configured by default
  gentrace.init(
      api_key=os.environ["GENTRACE_API_KEY"],
  )

  # Same as explicitly setting otel_setup=True
  gentrace.init(
      api_key=os.environ["GENTRACE_API_KEY"],
      otel_setup=True,
  )
  ```
</CodeGroup>

### Custom OpenTelemetry configuration

<CodeGroup dropdown>
  ```typescript custom-otel.ts theme={null}
  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: [],
    },
  });
  ```

  ```python custom_otel.py theme={null}
  import gentrace
  from gentrace import GentraceSampler
  from openinference.instrumentation.openai import OpenAIInstrumentor
  import os

  gentrace.init(
      api_key=os.environ["GENTRACE_API_KEY"],
      otel_setup={
          "service_name": "my-ai-service",
          "sampler": GentraceSampler(),
          "resource_attributes": {
              "service.version": "1.0.0",
              "deployment.environment": "production",
              "team": "ai-platform",
          },
          # Add OpenAI instrumentation for automatic tracing
          "instrumentations": [OpenAIInstrumentor()],
          # Enable debug mode to see spans in console
          "debug": True,
      },
  )
  ```
</CodeGroup>

### Custom OTEL collector endpoint

If you're using your own OpenTelemetry collector, configure the trace exporter in the `otelSetup` configuration:

<CodeGroup dropdown>
  ```typescript custom-collector.ts theme={null}
  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!,
    },
  );
  ```

  ```python custom_collector.py theme={null}
  import gentrace
  from gentrace import GentraceSampler, interaction
  from openai import AsyncOpenAI
  import os

  gentrace.init(
      api_key=os.environ["GENTRACE_API_KEY"],
      otel_setup={
          "service_name": "my-ai-service",
          "sampler": GentraceSampler(),

          # Configure your custom OTEL collector endpoint
          "trace_endpoint": "http://localhost:4318/v1/traces",

          "resource_attributes": {
              "service.version": "1.0.0",
              "deployment.environment": "production",
          },

          # Enable debug mode to see spans in console while testing
          "debug": True,
      },
  )

  # Your instrumented functions will now send traces to your collector
  client = AsyncOpenAI()

  @interaction(name="generate-response")
  async def generate_response(prompt: str) -> str:
      response = await client.chat.completions.create(
          model="gpt-4o",
          messages=[{"role": "user", "content": prompt}],
      )
      return response.choices[0].message.content
  ```
</CodeGroup>

<Note>
  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
</Note>

### Disable automatic OpenTelemetry setup

<CodeGroup dropdown>
  ```typescript manual-otel.ts theme={null}
  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
  ```

  ```python manual_otel.py theme={null}
  import gentrace
  import os

  # Disable automatic OpenTelemetry configuration
  gentrace.init(
      api_key=os.environ["GENTRACE_API_KEY"],
      otel_setup=False,
  )

  # You must configure OpenTelemetry manually
  # See the OpenTelemetry Setup guide for details
  ```
</CodeGroup>

### Custom base URL and timeout

<CodeGroup dropdown>
  ```typescript custom-config.ts theme={null}
  import { init } from 'gentrace';

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

  ```python custom_config.py theme={null}
  from gentrace import init
  import os

  init(
      api_key=os.environ["GENTRACE_API_KEY"],
      base_url="https://your-custom-domain.com/api",
      timeout=30.0,  # 30 seconds
      max_retries=5
  )
  ```
</CodeGroup>

### Custom headers and logging

<CodeGroup dropdown>
  ```typescript headers-logging.ts theme={null}
  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
  });
  ```

  ```python headers_logging.py theme={null}
  from gentrace import init
  import os

  init(
      api_key=os.environ["GENTRACE_API_KEY"],
      default_headers={
          "X-Custom-Header": "your-value",
          "User-Agent": "MyApp/1.0.0"
      }
  )
  ```
</CodeGroup>

## Environment variables

Instead of passing configuration options directly to `init()`, consider using 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

```bash .env theme={null}
# Set environment variables
export GENTRACE_API_KEY="your-gentrace-api-key"
export GENTRACE_BASE_URL="https://your-custom-domain.com/api"
```

<CodeGroup dropdown>
  ```typescript env-init.ts theme={null}
  import { init } from 'gentrace';

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

  ```python env_init.py theme={null}
  from gentrace import init

  # Initialize without parameters - uses environment variables
  init()
  ```
</CodeGroup>

## Error handling

The `init()` function will throw an error if required configuration is missing:

<CodeGroup dropdown>
  ```typescript error-handling.ts theme={null}
  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);
  }
  ```

  ```python error_handling.py theme={null}
  from gentrace import init, GentraceError

  try:
      init()
      # Missing api_key - will throw error if GENTRACE_API_KEY env var not set
  except GentraceError as e:
      print(f"Failed to initialize Gentrace: {e}")
  ```
</CodeGroup>

<Note>
  **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.
</Note>

## Best practices

### 1. Initialize early

Call `init()` before your main execution logic to ensure Gentrace is configured before using any tracing functionality:

<CodeGroup dropdown>
  ```typescript early-init.ts theme={null}
  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(async () => {
      // Your experiment code
    });
  }

  main();
  ```

  ```python early_init.py theme={null}
  from gentrace import init, experiment, eval
  import os

  # Initialize before using Gentrace functionality
  init(api_key=os.environ["GENTRACE_API_KEY"])

  # Now you can use Gentrace functions
  @experiment
  async def main():
      # Your experiment code
      pass

  if __name__ == "__main__":
      import asyncio
      asyncio.run(main())
  ```
</CodeGroup>

### 2. Use environment variables

Store sensitive configuration like API keys in environment variables rather than hardcoding them:

```bash theme={null}
# .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. Generate one at [https://gentrace.ai/s/api-keys](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)

## Related functions

* [`traced()`](../tracing/traced) - Lower-level function tracing
* [`interaction()`](../tracing/interactions) - Instrument AI functions for tracing
* [`experiment()`](../evaluation/experiments) - Create testing contexts for grouping evaluations
* [`evalDataset()` / `eval_dataset()`](../evaluation/dataset-tests) - Run tests against datasets
* [`eval()` / `evalOnce()`](../evaluation/unit-tests) - Run individual test cases
