Metadata-Version: 2.1
Name: acceldata-aio-tracer
Version: 1.1.4
Summary: Acceldata AIO instrumentation SDK — OpenTelemetry-native LLM application telemetry
License: Apache-2.0
Author: Acceldata
Requires-Python: >=3.10,<4.0
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Provides-Extra: db
Provides-Extra: http
Requires-Dist: opentelemetry-api (>=1.44.0,<2.0.0)
Requires-Dist: opentelemetry-exporter-otlp-proto-http (>=1.44.0,<2.0.0)
Requires-Dist: opentelemetry-instrumentation (>=0.65b0,<1.0.0)
Requires-Dist: opentelemetry-instrumentation-aiopg (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-instrumentation-asyncpg (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-instrumentation-dbapi (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-instrumentation-fastapi (>=0.65b0,<1.0.0) ; extra == "http"
Requires-Dist: opentelemetry-instrumentation-httpx (>=0.65b0,<1.0.0) ; extra == "http"
Requires-Dist: opentelemetry-instrumentation-mysql (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-instrumentation-mysqlclient (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-instrumentation-psycopg2 (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-instrumentation-pymssql (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-instrumentation-pymysql (>=0.65b0,<1.0.0) ; extra == "db"
Requires-Dist: opentelemetry-sdk (>=1.44.0,<2.0.0)
Requires-Dist: opentelemetry-semantic-conventions (>=0.65b0,<1.0.0)
Requires-Dist: pydantic (>=2.0.0,<3.0.0)
Requires-Dist: requests (>=2.31.0,<3.0.0)
Requires-Dist: wrapt (>=1.16.0,<2.0.0)
Description-Content-Type: text/markdown

# Acceldata AIO Python SDK

Trace model calls, agents, tools, and data access in
[Acceldata AIO](https://www.acceldata.io/) using OpenTelemetry.

Call `aio.init()` once at startup. Then wrap each chat turn or workflow in
`aio.root_span()`. Every span started inside it, from any instrumented library,
is grouped into one trace and attributed to a conversation and user.

- **Auto-instrumentation** for 70+ LLM providers, agent frameworks, vector
  stores, web frameworks, and database drivers.
- **Conversation and user attribution** on every span, including HTTP and
  tool spans that instrumentation libraries leave untagged.
- **Content redaction** applied when telemetry is exported, so one policy
  covers every integration.
- **Data-source detection** links traces to the tables and assets they read
  and write.
- **Tags** for filtering sessions, traces, and spans in AIO.

## Installation

Requires Python 3.10 or later.

```sh
pip install acceldata-aio-tracer
```

### Optional extras

The extras install OpenTelemetry instrumentation packages, which `aio.init()`
turns on automatically. Install the ones that match the libraries your
application uses:

| Extra | What it adds |
| --- | --- |
| `http` | Spans for incoming FastAPI requests and outgoing httpx requests. |
| `db` | SQL spans for psycopg2, PyMySQL, mysql-connector-python, asyncpg, aiopg, mysqlclient, and pymssql. Also adds DB-API tracing for Snowflake, Databricks, Trino, and PyAthena connectors, used directly or through SQLAlchemy. PyAthena hasn't been tested against a live Athena service yet. |

```sh
pip install 'acceldata-aio-tracer[http]'
pip install 'acceldata-aio-tracer[db]'
pip install 'acceldata-aio-tracer[http,db]'
```

psycopg (v3) and BigQuery instrumentation is built in, so they don't need `[db]`.
The extras add instrumentation only. You still install your database drivers,
model clients, and frameworks yourself.

## Quickstart

This example uses Anthropic. Every supported provider works the same way.

```sh
pip install anthropic
```

```python
import acceldata_aio_tracer as aio
from anthropic import Anthropic

aio.init(
    service="support-agent",
    tenant_id="your-tenant-id",
    project_id="your-project-uuid",
    endpoint="https://aio.example.com",
    access_key="your-access-key",
    secret_key="your-secret-key",
)
client = Anthropic(api_key="your-anthropic-api-key")  # create clients after init()

question = "What can AI observability tell me about my application?"
with aio.root_span(
    conversation_id="session-123",
    user_id="user-456",
    input_preview=question,
):
    response = client.messages.create(
        model="your-model-id",
        max_tokens=256,
        messages=[{"role": "user", "content": question}],
    )
    for block in response.content:
        if block.type == "text":
            print(block.text)
```

- Use one `root_span()` for each turn or workflow run.
- Reuse the same `conversation_id` for every turn in a conversation.
- `user_id` and `input_preview` are optional.
- For workflows, pass a fixed name such as `name="workflow_run"`, and keep IDs
  out of span names.
- Call `init()` **before** you create model clients or open database
  connections. Clients created earlier aren't instrumented.

### Async code

`root_span()` is a regular `with` block, and you use it the same way in async functions:

```python
import asyncio

import acceldata_aio_tracer as aio
from anthropic import AsyncAnthropic

aio.init(service="support-agent")  # remaining settings from the environment


async def main():
    async with AsyncAnthropic() as client:
        with aio.root_span(conversation_id="session-123"):
            response = await client.messages.create(
                model="your-model-id",
                max_tokens=256,
                messages=[{"role": "user", "content": "Explain distributed tracing."}],
            )
            print(response.content[0].text)


asyncio.run(main())
```

### Zero-code instrumentation

To instrument an application without changing its code, run it with
`aio-instrument` and set the configuration in the environment:

```sh
export AIO_TENANT_ID=your-tenant-id
export AIO_PROJECT_ID=your-project-uuid
export AIO_ENDPOINT=https://aio.example.com
export AIO_ACCESS_KEY=your-access-key
export AIO_SECRET_KEY=your-secret-key

aio-instrument --service-name support-agent python app.py
```

`aio-instrument` initializes the SDK before your application starts, the same
way `opentelemetry-instrument` does. To group spans into conversations, add
`root_span()` to your code. Run `aio-instrument --help` to see every option.

## Configuration

You can pass each setting to `aio.init()` or set it in the environment. An
argument you pass takes precedence over the environment variable.

| `init()` argument | Environment variable | Purpose |
| --- | --- | --- |
| `service` | `OTEL_SERVICE_NAME` | Application name. Defaults to `unknown_service`. |
| `tenant_id` | `AIO_TENANT_ID` | **Required.** Your AIO tenant ID. |
| `project_id` | `AIO_PROJECT_ID` | Project UUID. |
| `project_name` | — | Looks up the project by name instead of UUID. |
| `endpoint` | `AIO_ENDPOINT` | AIO server URL. Telemetry goes here too unless the collector is set separately. |
| `aio_collector_endpoint` | `AIO_COLLECTOR_ENDPOINT` | Collector URL, when it differs from `endpoint`. Falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`. |
| `access_key`, `secret_key` | `AIO_ACCESS_KEY`, `AIO_SECRET_KEY` | AIO credentials. |
| `environment` | `AIO_ENVIRONMENT` | Deployment environment. Defaults to `default`. |
| `redaction` | See [Content redaction](#content-redaction). | Content to withhold from telemetry. |
| `data_source_hosts` | `AIO_DATA_SOURCE_HOSTS` | Maps the hosts you connect to onto the hosts registered in the catalog. Format: `from=to,from=to`. |
| `instrument` | — | Set to `False` to turn off library auto-instrumentation while keeping the SDK's own setup. |

If you already use OpenTelemetry, you can set `aio.tenant_id`, `aio.project_id`
and `deployment.environment` in `OTEL_RESOURCE_ATTRIBUTES`. Those values take
precedence over the matching `AIO_*` variables.

### Selecting a project by name

```python
aio.init(service="support-agent", tenant_id="your-tenant-id", project_name="customer-support")
```

- Pass either `project_id` or `project_name`, not both.
- When you use a name, also unset `AIO_PROJECT_ID` and any `aio.project_id`
  resource attribute.
- The name must match exactly. If no project has that name, the SDK creates an
  Acceldata-hosted project with 60-day retention.

### Export defaults

These defaults differ from stock OpenTelemetry, so that bursts of traffic aren't dropped:
- **Span queue:** holds 10,000 spans instead of 2,048. Spans are still uploaded
  in batches of 512.
- **Compression:** traces, logs and metrics are sent gzip-compressed.

To override them, set the standard variables:
- `OTEL_BSP_MAX_QUEUE_SIZE` for the queue size.
- `OTEL_EXPORTER_OTLP_COMPRESSION` or `OTEL_EXPORTER_OTLP_<SIGNAL>_COMPRESSION`
  for compression: `none`, `gzip` or `deflate`.

## Supported integrations

The SDK detects which of these libraries are installed and instruments them during `init()`:

| Category | Libraries |
| --- | --- |
| Model providers | OpenAI, Anthropic, AWS Bedrock, Google AI Studio, Vertex AI, Azure AI Inference, Mistral, Cohere, Groq, Together, Ollama, LiteLLM, AI21, Reka, Sarvam, PremAI, OCI, GPT4All, Transformers, vLLM, ElevenLabs, AssemblyAI |
| Agent frameworks | LangChain, LangGraph, LlamaIndex, CrewAI, OpenAI Agents, Claude Agent SDK, Google ADK, AutoGen / AG2, Microsoft Agent Framework, Pydantic AI, smolagents, Strands, Agno, Haystack, Letta, Mem0, Dynamiq, ControlFlow, Julep, MultiOn, Browser Use, MCP |
| Vector stores | Chroma, Pinecone, Qdrant, Milvus, Astra |
| Web & HTTP | FastAPI, Flask, Django, Starlette, Falcon, Pyramid, Tornado, ASGI, requests, httpx, urllib, urllib3, aiohttp |
| Databases | psycopg (v3), BigQuery, DB-API, and the drivers in the `db` extra |
| Other | Firecrawl, Crawl4AI |

Web, HTTP and database coverage depends on the matching OpenTelemetry
instrumentation package being installed. See [Optional extras](#optional-extras).

## Tracing helpers

All of these are available on `import acceldata_aio_tracer as aio`.

| Helper | Usage |
| --- | --- |
| `aio.root_span(...)` | Groups one turn or workflow, and passes the conversation and user to every span inside it. |
| `aio.current_conversation_id()` | Returns the active conversation ID, or `None` outside a conversation. |
| `with aio.start_trace("lookup") as span:` | Adds a child operation. Use `span.set_metadata({...})` or `span.set_result(value)` to record details. |
| `@aio.trace` | Traces a sync function, recording its arguments and return value. For async functions, wrap the awaited work in `with aio.start_trace(...)`. |
| `@aio.langgraph_node` | Records a LangGraph node's input and output. See [LangGraph node content](#langgraph-node-content). |
| `with aio.using_attributes({...}):` | Adds attributes to supported auto-instrumented calls. Also works as a decorator on sync functions. |
| `with aio.agent_context("support"):` | Sets the agent name for supported instrumentation. |
| `with aio.agent_version_context("v2"):` | Sets the agent version for supported instrumentation. |
| `aio.declare_assets(reads=..., writes=...)` | Declares the data a span read or wrote. See [Data-source detection](#data-source-detection). |
| `aio.using_tags(...)` / `aio.set_tags(...)` / `aio.current_tags()` | Tag the current work. See [Tags](#tags). |

## Tags

A tag is a `"key:value"` label, such as `"escalated:yes"` or `"region:eu"`, that
you already know when a turn starts. Set it for a unit of work, and it's stamped
on every span started inside that work, whichever library created the span.
There's no process-wide default: a tag belongs to the work, not to the process.

```python
with aio.root_span(conversation_id="session-123"):
    with aio.using_tags("region:eu"):
        ...


@aio.using_tags("workflow:nightly")  # sync or async functions
def run_nightly():
    ...
```

- `using_tags` adds to the tags of the enclosing scope and restores them when
  the block exits.
- `set_tags` replaces the current set instead of adding to it. `set_tags()`
  with no arguments clears it.
- A tag applies only to spans started after it's set. A span that's already
  open isn't changed.
- `@using_tags` can't decorate a generator. Put a `with` block inside the generator instead.
- A valid tag is `"key:value"` with neither side blank, at most 200 characters
  long. Duplicates are merged, and at most 32 tags are kept.
- An invalid tag is logged as a warning and dropped, without raising.
  `using_tags()` with no arguments raises `TypeError`.

## Content redaction

Redaction changes what goes into telemetry. It doesn't change what the model,
tools or your application receive. Configure it in your first `aio.init()` call:

```python
aio.init(
    service="support-agent",
    redaction=aio.redaction_policy(
        hide_system_instructions=True,
        hide_tool_definitions=True,
        redact_tool_arguments=["run_query"],
        redact_tool_results=["lookup_customer"],
        redact_sql_literals=True,
    ),
)
```

`aio.redaction_policy(...)` builds an immutable `aio.RedactionPolicy`. Every
option is off by default. The rules apply to exported spans and GenAI log
records, including tool calls embedded in model messages.

| Option | What it does |
| --- | --- |
| `hide_system_instructions=True` | Replaces system instructions with a fingerprint, and removes system-role messages from message arrays. |
| `hide_tool_definitions=True` | Replaces recorded tool definitions with a fingerprint. |
| `redact_tool_arguments=["tool_name"]` | Withholds the arguments of the named tools. The names must match the ones the instrumentation records. |
| `redact_tool_results=["tool_name"]` | Withholds the results of the named tools. Set separately from arguments. If a message doesn't say which tool produced a result, every tool result in that payload is withheld. |
| `redact_attributes=["attribute.name"]` | Withholds whole attributes, such as `aio.input_preview`, `function.args` or `function.kwargs`. |
| `suppress_spans=["scratchpad"]` | Drops matching spans and all spans below them. Matches the full name or the part after the first space, so `scratchpad` matches `invoke_agent scratchpad`. |
| `redact_sql_literals=True` | Replaces string and number literals in SQL but keeps identifiers, so data-source detection still works. SQL comments aren't changed. |
| `patterns=[r"secret-[A-Za-z0-9]+"]` | Replaces regex matches in message text and in tool arguments and results with `__REDACTED__`. |
| `allow=lambda match: ...` | Keeps a regex match when this function returns `True`. |

Withheld values become `sha256:...` fingerprints, so identical content can still
be recognized across calls. These are deterministic hashes, not encryption.

If you don't pass `redaction`, the policy is built from these environment
variables. An explicit policy replaces them entirely; the two aren't merged.

| Variable | Same as |
| --- | --- |
| `AIO_HIDE_SYSTEM_INSTRUCTIONS=true` | `hide_system_instructions=True` |
| `AIO_HIDE_TOOL_DEFINITIONS=true` | `hide_tool_definitions=True` |
| `AIO_REDACT_TOOL_ARGUMENTS=run_query,lookup` | `redact_tool_arguments=[...]` |
| `AIO_REDACT_TOOL_RESULTS=lookup_customer` | `redact_tool_results=[...]` |

### Marking tools in code

```python
@aio.redact_arguments(name="run_query")
def run_query(connection, sql):
    ...

aio.redact_arguments(name="third_party_lookup")  # for a tool you don't own
```

- `@aio.redact_arguments` also works without parentheses on a function or tool
  class. It then uses that object's `name`, or its function or class name.
- The marks apply to the whole process and add to `redact_tool_arguments`.
- **A mark only takes effect when a redaction policy is active.**

### Hiding model inputs for one block

```python
@aio.redact_model_inputs
async def private_completion(client, prompt):
    return await client.messages.create(...)


def private_completion_sync(client, prompt):
    with aio.redact_model_inputs():
        return client.messages.create(...)
```

- What it hides: input messages and system instructions on model spans and log
  records, as fingerprints.
- What it doesn't hide: model outputs, tool content, graph-node content and
  `input_preview`. Use the policy options for those.
- No global policy is needed.
- Async tasks created inside the scope inherit it.
- Decorating a generator raises `TypeError`. Put the `with` block inside the generator instead.

### LangGraph node content

`@aio.langgraph_node` records a LangGraph node's input state and return value.
Apply the decorator before you register the node:

```python
@aio.langgraph_node
def normalize_request(state):
    return {"question": state["question"].strip()}


@aio.langgraph_node(
    input=lambda state: {"question": state["question"]},
    output=lambda state, result: result["answer"],
)
async def answer_node(state):
    ...
```

- Without selectors, the full state and return value are recorded, up to
  100,000 characters each.
- A selector that returns `None` leaves that side out. A selector that fails is
  logged and left out too.
- If the node raises, only its input is recorded.
- The recorded content follows the global redaction policy.

### What redaction covers

- **Call `aio.init()` before any other library installs a `TracerProvider`.**
  If an active policy can't be enforced, `init()` raises `aio.RedactionUnavailable`
  instead of exporting unredacted content.
- The rules cover the attributes listed above. They don't cover arbitrary logs,
  exception messages, or every copy of a value.
- Regex patterns don't scrub `aio.input_preview`, `function.args`, custom
  attributes or SQL text. Use `redact_attributes` for those fields, and
  `redact_sql_literals` for SQL values.

## Data-source detection

The SDK records database calls. AIO parses their SQL into the tables and columns
that were read and written, then matches those references to assets in your
catalog. Nothing needs to be called for each query:

```python
import psycopg

aio.init(
    service="orders-agent",
    redaction=aio.redaction_policy(redact_sql_literals=True),
    data_source_hosts={"localhost:5432": "orders-db.example.com:5432"},
)

with aio.root_span(conversation_id="session-123", name="lookup_order"):
    with psycopg.connect("postgresql://app@localhost:5432/sales") as conn:
        conn.execute("SELECT id, total FROM public.orders WHERE id = %s", (42,))
```

- Use schema-qualified table names where you can.
- SQLAlchemy is covered through the instrumented driver underneath it.
- `redact_sql_literals=True` turns `WHERE email = 'alice@example.com'` into
  `WHERE email = '?'`. Table and column names stay, so detection still works.

### Mapping tunnels and aliases

Use `data_source_hosts` when you connect through a tunnel, proxy or alias that
isn't the address registered in the catalog:

- A `host:port` key matches that exact endpoint. A key with only a host matches
  any port.
- When both kinds of key match, the `host:port` key wins.
- The original address stays in telemetry. The mapped address is used only for
  catalog matching.

### Declaring reads and writes

When data is accessed through an API, tool or custom connector whose SQL the
SDK can't see, declare it inside the span that does the access:

```python
with aio.start_trace("lookup_orders"):
    aio.declare_assets(
        reads=[("snowflake://acme-prod", "SALES.PUBLIC.ORDERS")],
        writes=[{
            "namespace": "snowflake://acme-prod",
            "name": "SALES.PUBLIC.AUDIT",
            "source_type": "snowflake",
            "kind": "table",
            "columns": ["ID", "TOTAL"],
        }],
    )
```

Each asset is either a tuple or a dict:
- A `(namespace, name)` tuple.
- A dict with `namespace` and `name`, and optionally `source_type`, `kind`
  (`table`, `view`, `file`, `endpoint` or `collection`), `columns` and `evidence`.

Declarations attach to the current span only. If no span is recording, the call does nothing.

### Support by database

| Database | SQL parsing | Catalog matching |
| --- | --- | --- |
| PostgreSQL, Redshift, Snowflake, Databricks, MySQL, SQL Server | Yes | Yes |
| Trino | ANSI SQL | Yes |
| BigQuery | Yes | Not yet |
| Athena | ANSI SQL | Not yet |

## Troubleshooting

- **`init()` returned `False`.** Setup failed, and the reason is in the logs.
  Check the tenant ID, the project, the endpoint and the credentials.
  `init()` never raises for these setup problems, so your application keeps
  running without telemetry. The one exception is a redaction policy that
  can't be enforced, which raises `aio.RedactionUnavailable`.
- **Calls aren't traced.** Call `init()` before you create clients, and install
  the [extra](#optional-extras) for your HTTP or database library.
- **Configuration changes have no effect.** Only the first `init()` call
  configures the SDK. Later calls return `True` and change nothing.
- **Tags are missing.** Set tags before the span starts.

