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

# Overview

> Complete API reference for the Netra Python SDK. Covers Netra.init(), decorators, manual spans, context tracking, evaluation, and usage queries.

<CardGroup cols={2}>
  <Card title="View on PyPI" icon="box-open" href="https://pypi.org/project/netra-sdk/">
    netra-sdk on Python Package Index
  </Card>

  <Card title="Source on GitHub" icon="github" href="https://github.com/KeyValueSoftwareSystems/netra-sdk-py">
    View source code and contribute
  </Card>
</CardGroup>

## Installation

<CodeGroup>
  ```bash pip theme={null}
  pip install netra-sdk
  ```

  ```bash poetry theme={null}
  poetry add netra-sdk
  ```
</CodeGroup>

## Netra Class

The `Netra` class is the main entry point for all SDK operations. All methods are static and can be called directly on the class.

### init

Initialize the Netra SDK with configuration options. Call this once at the start of your application.

```python theme={null}
from netra import Netra, NetraInstruments

Netra.init(
    app_name="my-ai-app",
    headers=f"x-api-key={os.getenv('NETRA_API_KEY')}",
    environment="production",
    trace_content=True,
    instruments={NetraInstruments.OPENAI, NetraInstruments.LANGCHAIN},
)
```

**Parameters:**

| Parameter                    | Type                              | Description                                                                                                                                                                                                                                     |                                                       |
| ---------------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| `app_name`                   | `Optional[str]`                   | Name of your application for identification in the dashboard                                                                                                                                                                                    |                                                       |
| `headers`                    | \`Optional\[str                   | Dict\[str, str]]\`                                                                                                                                                                                                                              | Headers for API requests (e.g., `x-api-key=your-key`) |
| `disable_batch`              | `Optional[bool]`                  | Disable batch processing of spans (default: `False`)                                                                                                                                                                                            |                                                       |
| `trace_content`              | `Optional[bool]`                  | Enable tracing of prompt/completion content (default: `True`)                                                                                                                                                                                   |                                                       |
| `resource_attributes`        | `Optional[Dict[str, Any]]`        | Additional OpenTelemetry resource attributes                                                                                                                                                                                                    |                                                       |
| `environment`                | `Optional[str]`                   | Application environment (e.g., "production", "staging")                                                                                                                                                                                         |                                                       |
| `instruments`                | `Optional[Set[NetraInstruments]]` | Set of instrumentations to enable. Defaults to `DEFAULT_INSTRUMENTS` when not specified. Pass `{NetraInstruments.ALL}` to instrument every supported library (legacy behavior).                                                                 |                                                       |
| `block_instruments`          | `Optional[Set[NetraInstruments]]` | Set of instrumentations to exclude from both `instruments` and `root_instruments`. Defaults to `None`.                                                                                                                                          |                                                       |
| `root_instruments`           | `Optional[Set[NetraInstruments]]` | Set of instrumentations allowed to produce root-level spans. Defaults to `DEFAULT_INSTRUMENTS_FOR_ROOT`. When a root span is blocked, its entire subtree is discarded. Pass `{NetraInstruments.ALL}` to allow all root spans (legacy behavior). |                                                       |
| `enable_root_span`           | `Optional[bool]`                  | Create a root span wrapping all traces                                                                                                                                                                                                          |                                                       |
| `debug_mode`                 | `Optional[bool]`                  | Enable debug logging                                                                                                                                                                                                                            |                                                       |
| `enable_scrubbing`           | `Optional[bool]`                  | Enable PII scrubbing                                                                                                                                                                                                                            |                                                       |
| `blocked_spans`              | `Optional[List[str]]`             | Span names to filter out globally (supports wildcards)                                                                                                                                                                                          |                                                       |
| `enable_metrics`             | `Optional[bool]`                  | Enable metrics for dashboard                                                                                                                                                                                                                    |                                                       |
| `metrics_export_interval_ms` | `Optional[int]`                   | Interval for exporting metrics                                                                                                                                                                                                                  |                                                       |
| `export_auto_metrics`        | `Optional[bool]`                  | Whether to export OTel auto-instrumented metrics                                                                                                                                                                                                |                                                       |

**Returns:** `None`

***

### start\_span

Create a new span for manual tracing. Use as a context manager for automatic span lifecycle management.

```python theme={null}
from netra import Netra, SpanType

# Basic usage
with Netra.start_span("process-document") as span:
    result = process_document(doc)
    span.set_attribute("pages", result.page_count)

# With span type and attributes
with Netra.start_span(
    "generate-response",
    as_type=SpanType.GENERATION,
    attributes={"model": "gpt-4"},
    module_name="chat"
) as span:
    response = generate_response(prompt)
```

**Parameters:**

| Parameter     | Type                       | Description                     |
| ------------- | -------------------------- | ------------------------------- |
| `name`        | `str`                      | Name of the span (required)     |
| `as_type`     | `Optional[SpanType]`       | Type of span for categorization |
| `attributes`  | `Optional[Dict[str, Any]]` | Initial attributes to set       |
| `module_name` | `Optional[str]`            | Module name for organization    |

**Returns:** `SpanWrapper` instance

***

### set\_session\_id

Set the session ID for the current context. All subsequent spans will be associated with this session.

```python theme={null}
Netra.set_session_id("session-abc123")
```

**Parameters:**

| Parameter    | Type  | Description                       |
| ------------ | ----- | --------------------------------- |
| `session_id` | `str` | Unique identifier for the session |

**Returns:** `None`

***

### set\_user\_id

Set the user ID for the current context.

```python theme={null}
Netra.set_user_id("user-456")
```

**Parameters:**

| Parameter | Type  | Description                    |
| --------- | ----- | ------------------------------ |
| `user_id` | `str` | Unique identifier for the user |

**Returns:** `None`

***

### set\_tenant\_id

Set the tenant ID for multi-tenant applications.

```python theme={null}
Netra.set_tenant_id("tenant-org-789")
```

**Parameters:**

| Parameter   | Type  | Description                      |
| ----------- | ----- | -------------------------------- |
| `tenant_id` | `str` | Unique identifier for the tenant |

**Returns:** `None`

***

### set\_custom\_attributes

Add custom key-value attributes to the current context.

```python theme={null}
Netra.set_custom_attributes(key="customer_tier", value="premium")
Netra.set_custom_attributes(key="region", value="us-east")
```

**Parameters:**

| Parameter | Type  | Description     |
| --------- | ----- | --------------- |
| `key`     | `str` | Attribute key   |
| `value`   | `Any` | Attribute value |

**Returns:** `None`

***

### set\_custom\_event

Record a custom event in the current context.

```python theme={null}
Netra.set_custom_event(
    event_name="user_feedback",
    attributes={
        "rating": 5,
        "comment": "Great response!",
        "category": "positive"
    }
)
```

**Parameters:**

| Parameter    | Type  | Description       |
| ------------ | ----- | ----------------- |
| `event_name` | `str` | Name of the event |
| `attributes` | `Any` | Event attributes  |

**Returns:** `None`

***

### add\_conversation

Append a conversation entry to the current span. Useful for tracking multi-turn conversations.

```python theme={null}
from netra import Netra
from netra.session_manager import ConversationType

Netra.add_conversation(
    conversation_type=ConversationType.INPUT,
    role="user",
    value="What is the weather today?"
)

Netra.add_conversation(
    conversation_type=ConversationType.OUTPUT,
    role="assistant",
    value="The weather is sunny with a high of 72°F."
)
```

**Parameters:**

| Parameter           | Type               | Description                                     |
| ------------------- | ------------------ | ----------------------------------------------- |
| `conversation_type` | `ConversationType` | Type of message (`INPUT`, `OUTPUT`)             |
| `role`              | `str`              | Role name (e.g., "user", "assistant", "system") |
| `value`             | `Any`              | Message content                                 |

**Returns:** `None`

<Note>
  If you're using Netra's auto-instrumentation for LLM calls, conversation messages are captured automatically. Using this method may result in duplicate messages.
</Note>

***

### set\_input

Set the input value on the current active span. Useful for explicitly recording what was passed into a step or function.

```python theme={null}
Netra.set_input("What is the capital of France?")
# Dicts and lists are automatically JSON-serialized
Netra.set_input({"query": "capital of France", "language": "en"})
```

**Parameters:**

| Parameter | Type  | Description                                                                                            |
| --------- | ----- | ------------------------------------------------------------------------------------------------------ |
| `value`   | `Any` | The input value to record. Dicts and lists are JSON-serialized; other types are converted via `str()`. |

**Returns:** `None`

<Note>
  The value is truncated to the SDK's maximum attribute length. If you're using auto-instrumentation for LLM calls, inputs may already be captured — use this method only when you need to set or override the input explicitly.
</Note>

***

### set\_output

Set the output value on the current active span. Useful for explicitly recording the result produced by a step or function.

```python theme={null}
Netra.set_output("The capital of France is Paris.")
# Dicts and lists are automatically JSON-serialized
Netra.set_output({"answer": "Paris", "confidence": 0.98})
```

**Parameters:**

| Parameter | Type  | Description                                                                                             |
| --------- | ----- | ------------------------------------------------------------------------------------------------------- |
| `value`   | `Any` | The output value to record. Dicts and lists are JSON-serialized; other types are converted via `str()`. |

**Returns:** `None`

<Note>
  The value is truncated to the SDK's maximum attribute length. If you're using auto-instrumentation for LLM calls, outputs may already be captured — use this method only when you need to set or override the output explicitly.
</Note>

***

### set\_root\_input

Set the input value on the root span of the current trace. This is useful for recording the top-level input to your entire pipeline, regardless of which nested span is currently active.

```python theme={null}
from netra import Netra
# Inside a nested span, set the root-level input
with Netra.start_span("sub-step") as span:
    Netra.set_root_input("Summarize the quarterly earnings report.")
```

**Parameters:**

| Parameter | Type  | Description                                                                                                             |
| --------- | ----- | ----------------------------------------------------------------------------------------------------------------------- |
| `value`   | `Any` | The input value to record on the root span. Dicts and lists are JSON-serialized; other types are converted via `str()`. |

**Returns:** `None`

<Note>
  The root span is the oldest span in the current trace. If no root span has been registered, this falls back to the current active span. The value is truncated to the SDK's maximum attribute length.
</Note>

***

### set\_root\_output

Set the output value on the root span of the current trace. This is useful for recording the final result of your entire pipeline, regardless of which nested span is currently active.

```python theme={null}
from netra import Netra
# At the end of your pipeline, record the top-level output
Netra.set_root_output({
    "summary": "Revenue increased 12% year-over-year...",
    "tokens_used": 1250
})
```

**Parameters:**

| Parameter | Type  | Description                                                                                                              |
| --------- | ----- | ------------------------------------------------------------------------------------------------------------------------ |
| `value`   | `Any` | The output value to record on the root span. Dicts and lists are JSON-serialized; other types are converted via `str()`. |

**Returns:** `None`

<Note>
  The root span is the oldest span in the current trace. If no root span has been registered, this falls back to the current active span. The value is truncated to the SDK's maximum attribute length.
</Note>

***

### shutdown

Gracefully shutdown the SDK, flushing any pending spans.

```python theme={null}
Netra.shutdown()
```

**Returns:** `None`

***

## SpanWrapper Class

The `SpanWrapper` class provides methods for enriching spans with additional context. It's returned by `Netra.start_span()` and supports method chaining.

### set\_attribute

Add a custom attribute to the span.

```python theme={null}
span.set_attribute("query", user_query)
span.set_attribute("results.count", len(results))
```

**Parameters:**

| Parameter | Type  | Description     |
| --------- | ----- | --------------- |
| `key`     | `str` | Attribute key   |
| `value`   | `Any` | Attribute value |

**Returns:** `SpanWrapper` (for chaining)

***

### add\_event

Record a timestamped event within the span.

```python theme={null}
span.add_event("validation-started")
span.add_event("validation-completed", {"valid": True, "errors": 0})
```

**Parameters:**

| Parameter    | Type                       | Description      |
| ------------ | -------------------------- | ---------------- |
| `name`       | `str`                      | Event name       |
| `attributes` | `Optional[Dict[str, Any]]` | Event attributes |

**Returns:** `SpanWrapper` (for chaining)

***

### set\_prompt

Set the input prompt for LLM spans.

```python theme={null}
span.set_prompt("Summarize this article: ...")
```

**Parameters:**

| Parameter | Type  | Description     |
| --------- | ----- | --------------- |
| `prompt`  | `str` | The prompt text |

**Returns:** `SpanWrapper` (for chaining)

***

### set\_negative\_prompt

Set the negative prompt (commonly used for image generation).

```python theme={null}
span.set_negative_prompt("blurry, low quality, distorted")
```

**Parameters:**

| Parameter | Type  | Description              |
| --------- | ----- | ------------------------ |
| `prompt`  | `str` | The negative prompt text |

**Returns:** `SpanWrapper` (for chaining)

***

### set\_model

Set the model name used in the operation.

```python theme={null}
span.set_model("gpt-4-turbo")
```

**Parameters:**

| Parameter | Type  | Description |
| --------- | ----- | ----------- |
| `model`   | `str` | Model name  |

**Returns:** `SpanWrapper` (for chaining)

***

### set\_llm\_system

Set the LLM provider/system name.

```python theme={null}
span.set_llm_system("openai")
```

**Parameters:**

| Parameter | Type  | Description     |
| --------- | ----- | --------------- |
| `system`  | `str` | LLM system name |

**Returns:** `SpanWrapper` (for chaining)

***

### set\_usage

Record token usage and cost metrics.

```python theme={null}
from netra import UsageModel

span.set_usage([
    UsageModel(
        model="gpt-4",
        cost_in_usd=0.006,
        usage_type="chat",
        units_used=1
    )
])
```

**Parameters:**

| Parameter    | Type               | Description           |
| ------------ | ------------------ | --------------------- |
| `usage_data` | `List[UsageModel]` | List of usage records |

**Returns:** `SpanWrapper` (for chaining)

***

### set\_action

Track actions or tool calls within the span.

```python theme={null}
from netra import ActionModel

span.set_action([
    ActionModel(
        action="DB",
        action_type="INSERT",
        affected_records=[
            {"record_id": "123", "record_type": "user"}
        ],
        metadata={"table": "users"},
        success=True
    )
])
```

**Parameters:**

| Parameter | Type                | Description            |
| --------- | ------------------- | ---------------------- |
| `actions` | `List[ActionModel]` | List of action records |

**Returns:** `SpanWrapper` (for chaining)

***

### set\_success

Mark the span as successful.

```python theme={null}
span.set_success()
```

**Returns:** `SpanWrapper` (for chaining)

***

### set\_error

Mark the span as failed with an error message.

```python theme={null}
span.set_error("Failed to connect to database")
```

**Parameters:**

| Parameter | Type  | Description   |
| --------- | ----- | ------------- |
| `message` | `str` | Error message |

**Returns:** `SpanWrapper` (for chaining)

***

## Models

### SpanType

Enum for categorizing spans.

```python theme={null}
from netra import SpanType

SpanType.SPAN        # General operations (default)
SpanType.GENERATION  # LLM completions, image generation
SpanType.EMBEDDING   # Vector embedding operations
SpanType.TOOL        # Function calls, API requests
SpanType.AGENT       # AI agent operations
```

***

### UsageModel

Model for tracking token usage and costs.

```python theme={null}
from netra import UsageModel

usage = UsageModel(
    model="gpt-4",
    cost_in_usd=0.0045,
    usage_type="chat",
    units_used=1
)
```

**Fields:**

| Field         | Type              | Description    |
| ------------- | ----------------- | -------------- |
| `model`       | `str`             | Model name     |
| `cost_in_usd` | `Optional[float]` | Cost in USD    |
| `usage_type`  | `Optional[str]`   | Type of usage  |
| `units_used`  | `Optional[int]`   | Units consumed |

***

### ActionModel

Model for tracking actions and tool calls.

```python theme={null}
from netra import ActionModel

action = ActionModel(
    action="API",
    action_type="CALL",
    affected_records=[
        {"record_id": "order-123", "record_type": "order"}
    ],
    metadata={
        "endpoint": "/api/orders",
        "method": "POST",
        "status_code": "201"
    },
    success=True
)
```

**Fields:**

| Field              | Type                       | Description                                  |
| ------------------ | -------------------------- | -------------------------------------------- |
| `action`           | `str`                      | Action category (e.g., "DB", "API", "CACHE") |
| `action_type`      | `str`                      | Action subtype (e.g., "INSERT", "CALL")      |
| `affected_records` | `Optional[List[Dict]]`     | Records affected by the action               |
| `metadata`         | `Optional[Dict[str, str]]` | Additional metadata                          |
| `success`          | `bool`                     | Whether the action succeeded                 |

***

### ConversationType

Enum for conversation entry types.

```python theme={null}
from netra.session_manager import ConversationType

ConversationType.INPUT   # User input messages
ConversationType.OUTPUT  # Model output messages
```

***

## Decorators

The SDK provides decorators for easy function instrumentation.

### @agent

Mark a function or class as an AI agent.

```python theme={null}
from netra.decorators import agent

@agent
def research_agent(query: str):
    return perform_research(query)

@agent(name="customer-support")
def support_agent(request: dict):
    return handle_request(request)
```

### @task

Mark a function or class as a task or tool.

```python theme={null}
from netra.decorators import task

@task
def fetch_data(query: str):
    return database.query(query)

@task(name="web-search")
def search_web(query: str):
    return search_api.search(query)
```

### @workflow

Mark a function or class as a workflow.

```python theme={null}
from netra.decorators import workflow

@workflow
def process_order(order: dict):
    validate_order(order)
    process_payment(order)
    fulfill_order(order)
```

### Capture Internal Methods

All decorators support the optional parameter `capture_internal_methods` that let's you trace both private and dunder methods when used on a Class

```python theme={null}
from netra.decorators import workflow

@workflow(name="WorkflowRobot", capture_internal_methods=True)
class WorkflowRobot:
    """Wraps: workflow entity, span type SPAN (default for workflow)."""
    
	def __init__(self, label: str) -> None:
        self.label = label

    def __str__(self) -> str:
        return f"WorkflowRobot({self.label})"
```

***

## Dashboard Client

The `dashboard` client provides methods to query dashboard data, session summaries, and session statistics programmatically.

### query\_data

Fetch dashboard data with customizable metrics, dimensions, and filters.

```python theme={null}
from netra import Netra
from netra.dashboard import *

Netra.init(app_name="my-app")

result = Netra.dashboard.query_data(
    scope=Scope.SPANS,
    chart_type=ChartType.LINE_TIME_SERIES,
    metrics=Metrics(
        measure=Measure.TOTAL_COST,
        aggregation=Aggregation.TOTAL_COUNT,
    ),
    dimension=Dimension(field=DimensionField.SERVICE),
    filter=FilterConfig(
        start_time="2026-01-01T00:00:00.000Z",
        end_time="2026-01-31T23:59:59.000Z",
        group_by=GroupBy.DAY,
    ),
)
```

**Parameters:**

| Parameter    | Type                  | Description                                                             |
| ------------ | --------------------- | ----------------------------------------------------------------------- |
| `scope`      | `Scope`               | Data scope (`SPANS` or `TRACES`)                                        |
| `chart_type` | `ChartType`           | Visualization type (`LINE_TIME_SERIES`, `BAR_TIME_SERIES`, `PIE`, etc.) |
| `metrics`    | `Metrics`             | What to measure and how to aggregate                                    |
| `filter`     | `FilterConfig`        | Time range, grouping, and filter conditions                             |
| `dimension`  | `Optional[Dimension]` | Optional grouping dimension                                             |

**Returns:** `dict | Any`

***

### get\_session\_summary

Retrieve aggregated session metrics including total sessions, costs, and latency.

```python theme={null}
from netra import Netra
from netra.dashboard import *

result = Netra.dashboard.get_session_summary(
    filter=SessionFilterConfig(
        start_time="2026-01-01T00:00:00.000Z",
        end_time="2026-01-31T23:59:59.000Z",
        filters=[
            SessionFilter(
                field=SessionFilterField.TENANT_ID,
                operator=SessionFilterOperator.ANY_OF,
                type=SessionFilterType.ARRAY,
                value=["TenantA", "TenantB"]
            )
        ]
    )
)
```

**Parameters:**

| Parameter | Type                  | Description                                               |
| --------- | --------------------- | --------------------------------------------------------- |
| `filter`  | `SessionFilterConfig` | Filter configuration with time range and optional filters |

**Returns:** `dict | Any`

***

### get\_session\_stats

Fetch a paginated list of sessions with individual metrics.

```python theme={null}
from netra import Netra
from netra.dashboard import *

stats = Netra.dashboard.get_session_stats(
    start_time="2026-01-01T00:00:00.000Z",
    end_time="2026-01-31T23:59:59.000Z",
    limit=10,
    sort_field=SortField.TOTAL_COST,
    sort_order=SortOrder.DESC
)

for session in stats.data:
    print(session)

# Handle pagination
if stats.has_next_page:
    next_stats = Netra.dashboard.get_session_stats(
        start_time="2026-01-01T00:00:00.000Z",
        end_time="2026-01-31T23:59:59.000Z",
        cursor=stats.next_cursor
    )
```

**Parameters:**

| Parameter    | Type                            | Description                                                             |
| ------------ | ------------------------------- | ----------------------------------------------------------------------- |
| `start_time` | `str`                           | Start of time window (ISO 8601 UTC)                                     |
| `end_time`   | `str`                           | End of time window (ISO 8601 UTC)                                       |
| `filters`    | `Optional[List[SessionFilter]]` | Optional filter conditions                                              |
| `limit`      | `Optional[int]`                 | Maximum results per page                                                |
| `cursor`     | `Optional[str]`                 | Pagination cursor                                                       |
| `sort_field` | `Optional[SortField]`           | Sort field (`SESSION_ID`, `START_TIME`, `TOTAL_REQUESTS`, `TOTAL_COST`) |
| `sort_order` | `Optional[SortOrder]`           | Sort direction (`ASC`, `DESC`)                                          |

**Returns:** `SessionStatsResult`

***

### iter\_session\_stats

Iterator that automatically handles pagination for session stats.

```python theme={null}
from netra import Netra
from netra.dashboard import *

for session in Netra.dashboard.iter_session_stats(
    start_time="2026-01-01T00:00:00.000Z",
    end_time="2026-01-31T23:59:59.000Z",
    sort_field=SortField.TOTAL_COST,
    sort_order=SortOrder.DESC
):
    print(session)
```

**Parameters:**

| Parameter    | Type                            | Description                         |
| ------------ | ------------------------------- | ----------------------------------- |
| `start_time` | `str`                           | Start of time window (ISO 8601 UTC) |
| `end_time`   | `str`                           | End of time window (ISO 8601 UTC)   |
| `filters`    | `Optional[List[SessionFilter]]` | Optional filter conditions          |
| `sort_field` | `Optional[SortField]`           | Sort field                          |
| `sort_order` | `Optional[SortOrder]`           | Sort direction                      |

**Returns:** `Iterator[SessionStatsResult]`

<Note>
  For detailed documentation on all dashboard enums, types, and filtering options, see [Dashboard Query](/sdk-reference/dashboard-query/python).
</Note>

***

## Usage Client

The `usage` client provides methods to query usage metrics, list traces, and fetch span data.

### get\_session\_usage

Fetch usage metrics for a single session.

```python theme={null}
from netra import Netra

Netra.init(app_name="my-app")

session_usage = Netra.usage.get_session_usage(
    session_id="session-123",
    start_time="2026-01-01T00:00:00.000Z",
    end_time="2026-01-31T23:59:59.000Z",
)
print(session_usage)
```

**Parameters:**

| Parameter    | Type  | Description                         |
| ------------ | ----- | ----------------------------------- |
| `session_id` | `str` | Unique session identifier           |
| `start_time` | `str` | Start of time window (ISO 8601 UTC) |
| `end_time`   | `str` | End of time window (ISO 8601 UTC)   |

**Returns:** `SessionUsageData | Any`

***

### get\_tenant\_usage

Fetch aggregated usage metrics for a tenant.

```python theme={null}
from netra import Netra

tenant_usage = Netra.usage.get_tenant_usage(
    tenant_id="AceTech",
    start_time="2026-01-01T00:00:00.000Z",
    end_time="2026-01-31T23:59:59.000Z",
)

print(tenant_usage)
```

**Parameters:**

| Parameter    | Type  | Description                         |
| ------------ | ----- | ----------------------------------- |
| `tenant_id`  | `str` | Tenant identifier                   |
| `start_time` | `str` | Start of time window (ISO 8601 UTC) |
| `end_time`   | `str` | End of time window (ISO 8601 UTC)   |

**Returns:** `TenantUsageData | Any`

***

### list\_traces

Query traces for a time range with optional filtering and pagination.

```python theme={null}
from netra import Netra

traces_page = Netra.usage.list_traces(
    start_time="2026-01-01T00:00:00.000Z",
    end_time="2026-01-31T23:59:59.000Z",
    tenant_id="AceTech",
    limit=10,
    sort_field="start_time",
    sort_order="desc",
)

for trace in traces_page.traces:
    print(trace)

# Handle pagination
if traces_page.has_next_page:
    next_page = Netra.usage.list_traces(
        start_time="2026-01-01T00:00:00.000Z",
        end_time="2026-01-31T23:59:59.000Z",
        cursor=traces_page.next_cursor
    )
```

**Parameters:**

| Parameter    | Type                               | Description                        |
| ------------ | ---------------------------------- | ---------------------------------- |
| `start_time` | `str`                              | Start of time range (ISO 8601 UTC) |
| `end_time`   | `str`                              | End of time range (ISO 8601 UTC)   |
| `tenant_id`  | `Optional[str]`                    | Filter by tenant                   |
| `user_id`    | `Optional[str]`                    | Filter by user                     |
| `session_id` | `Optional[str]`                    | Filter by session                  |
| `limit`      | `Optional[int]`                    | Maximum traces per page            |
| `cursor`     | `Optional[str]`                    | Pagination cursor                  |
| `direction`  | `Optional[Literal["up", "down"]]`  | Pagination direction               |
| `sort_field` | `Optional[str]`                    | Field to sort by                   |
| `sort_order` | `Optional[Literal["asc", "desc"]]` | Sort order                         |

**Returns:** `TracesPage | Any`

***

### iter\_traces

Iterator that automatically handles pagination for traces.

```python theme={null}
from netra import Netra

for trace in Netra.usage.iter_traces(
    start_time="2026-01-01T00:00:00.000Z",
    end_time="2026-01-31T23:59:59.000Z",
    tenant_id="AceTech",
    sort_field="start_time",
    sort_order="desc",
):
    print(trace)
```

**Returns:** `Iterator[TraceSummary]`

***

### list\_spans\_by\_trace\_id

Fetch spans within a single trace.

```python theme={null}
from netra import Netra

spans_page = Netra.usage.list_spans_by_trace_id(
    trace_id="728c1de6fa4c53de143a7d7fef33ff91",
    limit=10,
    span_name="openai.chat",
)

for span in spans_page.spans:
    print(span)
```

**Parameters:**

| Parameter   | Type                              | Description            |
| ----------- | --------------------------------- | ---------------------- |
| `trace_id`  | `str`                             | ID of the trace        |
| `cursor`    | `Optional[str]`                   | Pagination cursor      |
| `direction` | `Optional[Literal["up", "down"]]` | Pagination direction   |
| `limit`     | `Optional[int]`                   | Maximum spans per page |
| `span_name` | `Optional[str]`                   | Filter by span name    |

**Returns:** `SpansPage | Any`

***

### iter\_spans\_by\_trace\_id

Iterator that automatically handles pagination for spans.

```python theme={null}
from netra import Netra

for span in Netra.usage.iter_spans_by_trace_id(
    trace_id="728c1de6fa4c53de143a7d7fef33ff91",
    span_name="generation_pipeline",
):
    print(span)
```

**Returns:** `Iterator[TraceSpan]`

<Note>
  For detailed documentation on response types and all filtering options, see [Usage, Traces & Spans](/usage/usage-utilities).
</Note>

***

## Instruments

Available instrumentations for auto-tracing.

<Note>
  When `instruments` is not specified in `Netra.init()`, only the curated `DEFAULT_INSTRUMENTS` set is enabled — not every library listed below. Pass `InstrumentSet.ALL` to instrument all supported libraries, or pass an explicit set to pick exactly what you need. See [Instrumentation Selection](/Observability/Traces/configuration/instrumentation-selection) for details.
</Note>

### ALL Sentinel

```python theme={null}
from netra.instrumentation.instruments import NetraInstruments

NetraInstruments.ALL  # Enables all supported instrumentations (legacy behavior)
```

### LLM Providers

```python theme={null}
NetraInstruments.OPENAI            # OpenAI
NetraInstruments.ANTHROPIC         # Anthropic Claude
NetraInstruments.GOOGLE_GENERATIVEAI  # Google Generative AI
NetraInstruments.COHEREAI          # Cohere
NetraInstruments.MISTRALAI         # Mistral AI
NetraInstruments.GROQ              # Groq
NetraInstruments.BEDROCK           # AWS Bedrock
NetraInstruments.VERTEXAI          # Google Vertex AI
NetraInstruments.OLLAMA            # Ollama
NetraInstruments.REPLICATE         # Replicate
NetraInstruments.TOGETHER          # Together AI
NetraInstruments.LITELLM           # LiteLLM
NetraInstruments.CEREBRAS          # Cerebras
NetraInstruments.CARTESIA          # Cartesia
NetraInstruments.DEEPGRAM          # Deepgram
NetraInstruments.ELEVENLABS        # ElevenLabs
NetraInstruments.ALEPHALPHA        # Aleph Alpha
NetraInstruments.WATSONX           # IBM WatsonX
NetraInstruments.SAGEMAKER         # AWS SageMaker
NetraInstruments.WRITER            # Writer
NetraInstruments.TRANSFORMERS      # Hugging Face Transformers
```

### AI Frameworks

```python theme={null}
NetraInstruments.LANGCHAIN         # LangChain
NetraInstruments.LLAMA_INDEX       # LlamaIndex
NetraInstruments.HAYSTACK          # Haystack
NetraInstruments.CREW              # CrewAI
NetraInstruments.DSPY              # DSPy
NetraInstruments.PYDANTIC_AI       # Pydantic AI
NetraInstruments.ADK               # Google ADK
NetraInstruments.AGNO              # Agno
NetraInstruments.MCP               # Model Context Protocol
NetraInstruments.CLAUDE_AGENT_SDK  # Claude Agent SDK
NetraInstruments.OPENAI_AGENTS     # OpenAI Agents SDK
```

### Vector Databases

```python theme={null}
NetraInstruments.PINECONE          # Pinecone
NetraInstruments.WEAVIATEDB        # Weaviate
NetraInstruments.QDRANTDB          # Qdrant
NetraInstruments.CHROMA            # ChromaDB
NetraInstruments.MILVUS            # Milvus
NetraInstruments.LANCEDB           # LanceDB
NetraInstruments.MARQO             # Marqo
```

### HTTP Clients

```python theme={null}
NetraInstruments.HTTPX             # HTTPX
NetraInstruments.AIOHTTP           # AIOHTTP
NetraInstruments.REQUESTS          # Requests
NetraInstruments.URLLIB             # urllib
NetraInstruments.URLLIB3            # urllib3
NetraInstruments.GRPC              # gRPC
```

### Web Frameworks

```python theme={null}
NetraInstruments.FASTAPI           # FastAPI
NetraInstruments.FLASK             # Flask
NetraInstruments.DJANGO            # Django
NetraInstruments.STARLETTE         # Starlette
NetraInstruments.TORNADO           # Tornado
NetraInstruments.FALCON            # Falcon
NetraInstruments.PYRAMID           # Pyramid
NetraInstruments.ASGI              # ASGI
NetraInstruments.WSGI              # WSGI
NetraInstruments.AIOHTTP_SERVER    # AIOHTTP Server
```

### Databases

```python theme={null}
NetraInstruments.SQLALCHEMY        # SQLAlchemy
NetraInstruments.SQLITE3           # SQLite3
NetraInstruments.PSYCOPG           # PostgreSQL (psycopg)
NetraInstruments.PSYCOPG2          # PostgreSQL (psycopg2)
NetraInstruments.ASYNCPG           # PostgreSQL (asyncpg)
NetraInstruments.AIOPG             # PostgreSQL (aiopg)
NetraInstruments.PYMYSQL           # MySQL (PyMySQL)
NetraInstruments.MYSQL             # MySQL (mysql-connector)
NetraInstruments.MYSQLCLIENT       # MySQL (mysqlclient)
NetraInstruments.PYMONGO           # MongoDB
NetraInstruments.PYMSSQL           # Microsoft SQL Server
NetraInstruments.REDIS             # Redis
NetraInstruments.ELASTICSEARCH     # Elasticsearch
NetraInstruments.CASSANDRA         # Cassandra
NetraInstruments.PYMEMCACHE        # Memcached
```

### Message Queues

```python theme={null}
NetraInstruments.CELERY            # Celery
NetraInstruments.PIKA              # RabbitMQ (pika)
NetraInstruments.AIO_PIKA          # RabbitMQ (aio-pika)
NetraInstruments.KAFKA_PYTHON      # Kafka (kafka-python)
NetraInstruments.CONFLUENT_KAFKA   # Confluent Kafka
NetraInstruments.AIOKAFKA          # Kafka (aiokafka)
NetraInstruments.BOTO3SQS          # AWS SQS
```

### Other

```python theme={null}
NetraInstruments.AWS_LAMBDA        # AWS Lambda
NetraInstruments.BOTO              # AWS SDK (boto)
NetraInstruments.BOTOCORE          # AWS SDK (botocore)
NetraInstruments.JINJA2            # Jinja2
NetraInstruments.LOGGING           # Python logging
NetraInstruments.THREADING         # Python threading
NetraInstruments.ASYNCIO           # Python asyncio
NetraInstruments.CLICK             # Click CLI
NetraInstruments.ASYNCCLICK        # AsyncClick CLI
NetraInstruments.SYSTEM_METRICS    # System metrics
NetraInstruments.DBAPI             # Python DB-API 2.0
NetraInstruments.TORTOISEORM       # Tortoise ORM
NetraInstruments.REMOULADE         # Remoulade
```

### Default Instruments

When `instruments` is not specified, Netra uses the following curated set (`DEFAULT_INSTRUMENTS`):

| Category                     | Instruments                                                                                                                                                                                    |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **LLM / AI Providers**       | Anthropic, Bedrock, Cartesia, Cerebras, Cohere AI, Deepgram, ElevenLabs, Google Generative AI, Groq, LiteLLM, Mistral AI, Ollama, OpenAI, Replicate, Together, Vertex AI, Aleph Alpha, WatsonX |
| **Agent Frameworks**         | Agno, Claude Agent SDK, CrewAI, DSPy, Google ADK, Haystack, LangChain, LlamaIndex, MCP, Pydantic AI                                                                                            |
| **Vector Databases**         | Chroma, LanceDB, Marqo, Milvus, Pinecone, Qdrant, Weaviate                                                                                                                                     |
| **Web Frameworks**           | FastAPI                                                                                                                                                                                        |
| **HTTP Clients & Databases** | HTTPX, Requests, PyMySQL, SQLAlchemy                                                                                                                                                           |

### Default Root Instruments

When `root_instruments` is not specified, Netra uses the following curated subset (`DEFAULT_INSTRUMENTS_FOR_ROOT`). Libraries in this set are allowed to produce root-level spans (top-level traces):

| Category               | Instruments                                                                                                                                                                                    |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **LLM / AI Providers** | Anthropic, Bedrock, Cartesia, Cerebras, Cohere AI, Deepgram, ElevenLabs, Google Generative AI, Groq, LiteLLM, Mistral AI, Ollama, OpenAI, Replicate, Together, Vertex AI, Aleph Alpha, WatsonX |
| **Agent Frameworks**   | Agno, Claude Agent SDK, CrewAI, DSPy, Google ADK, Haystack, LangChain, LlamaIndex, MCP, Pydantic AI                                                                                            |
| **Web Frameworks**     | FastAPI                                                                                                                                                                                        |

***

<Note>
  In agentic applications, a single invocation can be captured by multiple instrumentations across frameworks and LLM providers. For example, an OpenAI call made through Agno may be traced by both the Agno and OpenAI instrumentations. This can lead to duplicated telemetry data, such as token usage and cost, within the same trace. Review your traces carefully to identify such overlaps, and disable unnecessary instrumentations when required to ensure accurate observability data.
</Note>

## Complete Example

```python theme={null}
import os
from netra import Netra, NetraInstruments, SpanType, UsageModel
from openai import OpenAI

# Initialize SDK
Netra.init(
    app_name="my-ai-app",
    headers=f"x-api-key={os.getenv('NETRA_API_KEY')}",
    environment="production",
    instruments={NetraInstruments.OPENAI},
)

# Set context
Netra.set_user_id("user-123")
Netra.set_session_id("session-abc")

# Create a traced operation
def chat_with_ai(user_message: str) -> str:
    with Netra.start_span("chat-completion", as_type=SpanType.GENERATION) as span:
        span.set_prompt(user_message)
        span.set_model("gpt-4")
        span.set_llm_system("openai")

        client = OpenAI()
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": user_message}]
        )

        # Calculate cost based on token usage
        prompt_cost = (response.usage.prompt_tokens / 1000) * 0.03
        completion_cost = (response.usage.completion_tokens / 1000) * 0.06
        total_cost = prompt_cost + completion_cost

        span.set_usage([
            UsageModel(
                model="gpt-4",
                cost_in_usd=total_cost,
                usage_type="chat",
                units_used=1
            )
        ])

        span.set_success()
        return response.choices[0].message.content

# Use the function
result = chat_with_ai("What is the capital of France?")
print(result)

# Shutdown gracefully
Netra.shutdown()
```

## Next Steps

* [TypeScript SDK Reference](/sdk-reference/sdk/typescript) - TypeScript/JavaScript API reference
* [Dashboard Query](/sdk-reference/dashboard-query/python) - Complete dashboard API reference
* [Usage Utilities](/usage/usage-utilities) - Query traces and usage data
* [Auto-Instrumentation](/Observability/Traces/auto-instrumentation) - Automatic tracing setup
* [Instrumentation Selection](/Observability/Traces/configuration/instrumentation-selection) - Control which libraries are instrumented
* [Manual Tracing](/Observability/Traces/manual-tracing) - Advanced tracing patterns
* [Decorators](/Observability/Traces/decorators) - Using decorators effectively
