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

# Python SDK

> Installation, initialization, and full API reference for the TraceRoot Python SDK

The TraceRoot Python SDK provides automatic and manual instrumentation for AI agents using OpenTelemetry.

## Instrumentation

```python theme={null}
import traceroot
from traceroot import Integration

traceroot.initialize(
    integrations=[
        Integration.OPENAI,
        Integration.ANTHROPIC,
        Integration.LANGCHAIN,
        Integration.GOOGLE_GENAI,
    ],
)
```

## The Observe Decorator

Wrap any function to create a span, works with sync functions, async functions, and generators.

```python theme={null}
from traceroot import observe

@observe(name="my_function", type="tool")
def my_function(query: str) -> str:
    return do_work(query)

@observe(name="async_agent", type="agent")
async def async_agent(query: str) -> str:
    return await process(query)
```

### Parameters

| Parameter        | Type              | Default       | Description                                                                                           |
| ---------------- | ----------------- | ------------- | ----------------------------------------------------------------------------------------------------- |
| `name`           | `str`             | function name | Span name                                                                                             |
| `type`           | `SpanKind \| str` | `"span"`      | Span kind: `"llm"`, `"agent"`, `"tool"`, or `"span"` (accepts both `SpanKind` enum and string values) |
| `metadata`       | `dict`            | `None`        | Static metadata to attach                                                                             |
| `tags`           | `list[str]`       | `None`        | Tags to attach                                                                                        |
| `capture_input`  | `bool`            | `True`        | Whether to auto-capture function arguments as input                                                   |
| `capture_output` | `bool`            | `True`        | Whether to auto-capture the return value as output                                                    |
| `session_id`     | `str`             | `None`        | Session identifier to attach to the trace                                                             |
| `user_id`        | `str`             | `None`        | User identifier to attach to the trace                                                                |

## Setting Trace Context

Use `using_attributes` to set user and session context for all spans created within a block:

```python theme={null}
from traceroot import using_attributes

with using_attributes(
    user_id="user-123",
    session_id="sess-456",
    tags=["production", "v2"],
    metadata={"feature": "chat"},
):
    result = run_agent("What is the weather?")
```

### Parameters

| Parameter    | Type        | Description                 |
| ------------ | ----------- | --------------------------- |
| `user_id`    | `str`       | User identifier             |
| `session_id` | `str`       | Session / conversation ID   |
| `tags`       | `list[str]` | Tags to attach to all spans |
| `metadata`   | `dict`      | Arbitrary metadata          |

## Updating Spans and Traces

Update the current span or trace programmatically:

```python theme={null}
from traceroot import update_current_span, update_current_trace

# Update the current span
update_current_span(
    name="custom_name",
    input={"query": "hello"},
    output={"response": "world"},
    metadata={"custom_key": "custom_value"},
    # LLM-specific attributes (useful for custom/unsupported providers)
    model="gpt-4o",
    model_parameters={"temperature": 0.7, "max_tokens": 1024},
    usage={"input_tokens": 100, "output_tokens": 50},
    prompt=[{"role": "user", "content": "hello"}],
)

# Update the current trace
update_current_trace(
    user_id="user-123",
    session_id="sess-456",
    tags=["production", "v2"],
    metadata={"plan": "pro", "region": "us-east-1"},
)
```

### `update_current_span` Parameters

| Parameter          | Type   | Description                                                      |
| ------------------ | ------ | ---------------------------------------------------------------- |
| `name`             | `str`  | Update the span name                                             |
| `input`            | `Any`  | Input data                                                       |
| `output`           | `Any`  | Output data                                                      |
| `metadata`         | `dict` | Custom metadata key-value pairs                                  |
| `model`            | `str`  | LLM model name (e.g., `"gpt-4o"`)                                |
| `model_parameters` | `dict` | Model parameters (e.g., temperature, max\_tokens)                |
| `usage`            | `dict` | Token usage (e.g., `{"input_tokens": 100, "output_tokens": 50}`) |
| `prompt`           | `Any`  | Prompt/messages sent to the LLM                                  |

### `update_current_trace` Parameters

| Parameter    | Type        | Description                            |
| ------------ | ----------- | -------------------------------------- |
| `user_id`    | `str`       | User who initiated the trace           |
| `session_id` | `str`       | Session identifier for grouping traces |
| `metadata`   | `dict`      | Trace-level metadata                   |
| `tags`       | `list[str]` | Tags to categorize the trace           |

## Environment Variables

All parameters can be set via environment variables:

| Variable                   | Default                    | Description                                               |
| -------------------------- | -------------------------- | --------------------------------------------------------- |
| `TRACEROOT_API_KEY`        | (required)                 | API key                                                   |
| `TRACEROOT_HOST_URL`       | `https://app.traceroot.ai` | API endpoint                                              |
| `TRACEROOT_ENABLED`        | `true`                     | Enable/disable tracing                                    |
| `TRACEROOT_ENVIRONMENT`    | —                          | Deployment environment tag (e.g. `production`, `staging`) |
| `TRACEROOT_FLUSH_INTERVAL` | `5.0`                      | Flush interval in seconds                                 |
| `TRACEROOT_FLUSH_AT`       | `100`                      | Batch size before flush                                   |
| `TRACEROOT_TIMEOUT`        | `30.0`                     | HTTP timeout in seconds                                   |
| `TRACEROOT_GIT_REPO`       | auto-detected              | Git repository (`owner/repo`)                             |
| `TRACEROOT_GIT_REF`        | auto-detected              | Git reference                                             |
