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

# traced()

> Wrap any function with OpenTelemetry tracing to automatically track its execution

The `traced()` function wraps any function with [OpenTelemetry tracing](https://opentelemetry.io/docs/concepts/signals/traces/) to automatically track its execution. It creates a [span](https://opentelemetry.io/docs/concepts/signals/traces/#spans) for each function call, records input arguments and return values, and captures any exceptions that occur during execution.

<Tip>
  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](/reference/opentelemetry-guide).
</Tip>

## Basic usage

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

  ```python theme={null}
  import asyncio
  import os
  from gentrace import init, traced
  from openai import OpenAI

  init(api_key=os.environ["GENTRACE_API_KEY"])

  openai = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

  @traced(name="generate_response")
  async def generate_response(prompt: str) -> str:
      response = await openai.chat.completions.create(
          model="o3",
          messages=[{"role": "user", "content": prompt}]
      )
      return response.choices[0].message.content or ""

  # Run the async function
  async def main():
      ai_response = await generate_response("What is the capital of France?")
      print(ai_response)

  asyncio.run(main())
  ```
</CodeGroup>

The Gentrace SDK automatically configures the `GentraceSpanProcessor` when you call `init()`, which simplifies the process of converting [baggage](https://opentelemetry.io/docs/concepts/signals/baggage/) values to span attributes, ensuring proper trace routing to Gentrace. For manual configuration details, see the [OpenTelemetry setup guide](../reference/opentelemetry-guide).

## Overview

The `traced()` function provides automatic instrumentation for any function in your codebase. It:

1. **Creates [OpenTelemetry spans](https://opentelemetry.io/docs/concepts/signals/traces/#spans)** for each function execution with customizable names
2. **Records function arguments** as [span events](https://opentelemetry.io/docs/concepts/signals/traces/#span-events) for debugging and analysis
3. **Captures return values** as [span events](https://opentelemetry.io/docs/concepts/signals/traces/#span-events) to track function outputs
4. **Handles errors automatically** by recording exceptions and setting appropriate [span status](https://opentelemetry.io/docs/concepts/signals/traces/#span-status)
5. **Supports both sync and async functions** with proper typing preservation
6. **Allows [custom attributes](https://opentelemetry.io/docs/concepts/signals/traces/#attributes)** to be attached to spans for enhanced observability

## Parameters

<CodeGroup dropdown>
  ```typescript theme={null}
  /**
   * 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;
  ```

  ```python theme={null}
  def traced(
      *,
      name: Optional[str] = None,
      attributes: Optional[Dict[str, Any]] = None,
  ) -> Callable[[F], F]:
      """
      Decorator to wrap a function with OpenTelemetry tracing

      Args:
          name: Custom name for the OpenTelemetry span.
                If not provided, uses the function's __name__
                or "anonymous_function" as fallback
          attributes: Custom attributes to attach to the span.
                      These will be formatted for OTLP compatibility

      Returns:
          A decorator that, when applied to a function,
          returns a new function with the same signature
          but enhanced with tracing capabilities
      """
  ```
</CodeGroup>
