This release is a pre-release and may not be stable for production use.
Acceldata AIO Python SDK
Trace model calls, agents, and tools in Acceldata AIO using OpenTelemetry.
Initialize once at startup, then wrap each chat turn or workflow in a
root_span() to group its spans and attribute them to a conversation and user.
Installation
Requires Python 3.10 or later.
pip install acceldata-aio-tracer
Optional instrumentation
Extras install OpenTelemetry instrumentation packages that the SDK activates
during aio.init(). Choose them based on the libraries your application uses:
| Extra | What it enables | When to install |
|---|---|---|
http |
Incoming FastAPI request spans and outgoing httpx request spans. | Your application uses FastAPI or httpx and you want HTTP calls included in traces. |
db |
SQL spans for psycopg2, PyMySQL, mysql-connector-python, asyncpg, aiopg, mysqlclient, and pymssql. | Your application uses one of these drivers and you want database tracing and automatic SQL-based data-source analysis. |
db |
DB-API tracing for Snowflake, Databricks, Trino, and PyAthena. | Your application queries these systems through their Python connectors, directly or through SQLAlchemy. PyAthena has not yet been validated against a live Athena service. |
pip install 'acceldata-aio-tracer[http]'
pip install 'acceldata-aio-tracer[db]'
# Or install both:
pip install 'acceldata-aio-tracer[http,db]'
The base SDK already includes instrumentation for psycopg v3 and BigQuery;
these do not need [db]. Install your database drivers, model clients, and
frameworks separately—the extras supply instrumentation, not those libraries.
Without an extra (or its instrumentation packages installed separately), the
corresponding calls are not automatically traced by the SDK. SQL-based
data-source analysis needs spans containing query text and database connection
attributes; a root or model span alone does not provide that information.
Call init() before constructing clients or opening database connections.
Quickstart
This example uses Anthropic; AIO also instruments other supported providers and frameworks. Install the client:
pip install anthropic
Initialize with your project UUID, then create the model client. Replace the placeholder values with your configuration and a model you can access. For omitted arguments, see the environment fallbacks.
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")
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() per turn or workflow. Reuse the conversation ID across
turns in the same conversation; user_id and input_preview are optional.
For workflows, pass a fixed name such as name="workflow_run"; keep IDs out
of span names.
Async usage
root_span() uses a regular with block, including inside async functions:
import asyncio
import acceldata_aio_tracer as aio
from anthropic import AsyncAnthropic
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",
)
async def main():
async with AsyncAnthropic(api_key="your-anthropic-api-key") 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."}],
)
for block in response.content:
if block.type == "text":
print(block.text)
asyncio.run(main())
Configuration
Pass values directly to aio.init(). If an argument is omitted, the SDK reads
the environment fallback below. Nonempty arguments take precedence.
init() argument |
Environment fallback when omitted | Purpose |
|---|---|---|
service |
OTEL_SERVICE_NAME |
Application name; defaults to unknown_service. |
tenant_id |
AIO_TENANT_ID |
Required tenant ID. |
project_id |
AIO_PROJECT_ID |
Project UUID; skips project lookup. |
project_name |
None; pass explicitly. | Resolve a project by name instead of UUID. |
endpoint |
AIO_ENDPOINT |
AIO server URL; also the default telemetry destination. |
aio_collector_endpoint |
AIO_COLLECTOR_ENDPOINT |
Override when the Collector has a separate URL. |
access_key, secret_key |
AIO_ACCESS_KEY, AIO_SECRET_KEY |
AIO credentials. |
environment |
AIO_ENVIRONMENT |
Deployment environment; defaults to default. |
redaction |
See redaction settings. | Control which recorded content is withheld. |
data_source_hosts |
AIO_DATA_SOURCE_HOSTS |
Map connection addresses to catalog addresses; format: from=to,from=to. |
The Collector URL also falls back to OTEL_EXPORTER_OTLP_ENDPOINT before
endpoint. Existing OpenTelemetry setups can supply aio.tenant_id,
aio.project_id, and deployment.environment through OTEL_RESOURCE_ATTRIBUTES;
these take precedence over their AIO_* environment variables.
Export defaults differ from stock OpenTelemetry so that bursts are not dropped
inside your app: the span queue holds 10,000 spans instead of 2,048 (uploads
still go every 512), and traces, logs and metrics are sent gzip-compressed. The
standard variables override them: OTEL_BSP_MAX_QUEUE_SIZE for the queue, and
OTEL_EXPORTER_OTLP_COMPRESSION or OTEL_EXPORTER_OTLP_<SIGNAL>_COMPRESSION
(none, gzip, deflate) for compression.
To select a project by name instead of UUID, replace your initial init()
call with:
import acceldata_aio_tracer as aio
aio.init(
service="support-agent",
tenant_id="your-tenant-id",
project_name="customer-support",
endpoint="https://aio.example.com",
access_key="your-access-key",
secret_key="your-secret-key",
)
Supply exactly one of project_id or project_name. When using a name, also
unset AIO_PROJECT_ID and any aio.project_id resource attribute. A name is
matched exactly; if no project matches, the SDK creates an Acceldata-hosted
project with 60-day retention.
Content redaction
Redaction changes recorded telemetry, not model requests, tool arguments, or
application return values. Configure it in your first aio.init() call:
import acceldata_aio_tracer as aio
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",
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. Options
default to off. Rules apply to supported content attributes on exported spans
and GenAI log records, including tool calls embedded in model messages.
Policy options
| Option | What it does |
|---|---|
hide_system_instructions=True |
Replace the system-instructions attribute with a fingerprint and remove system-role messages from message arrays. |
hide_tool_definitions=True |
Replace recorded tool definitions with a fingerprint. |
redact_tool_arguments=["tool_name"] |
Withhold arguments for the named tools. Names must match those recorded by instrumentation. |
redact_tool_results=["tool_name"] |
Withhold results separately from arguments. If a message does not identify which tool produced its result, all tool-result messages in that payload are withheld. |
redact_attributes=["attribute.name"] |
Withhold entire named attributes, such as aio.input_preview, function.args, or function.kwargs. |
suppress_spans=["scratchpad"] |
Drop matching spans and their descendant spans. Matches the full name or the part after its first space, e.g. scratchpad matches invoke_agent scratchpad. |
redact_sql_literals=True |
Replace SQL string and numeric literals while retaining identifiers for data-source detection. SQL comments remain unchanged. |
patterns=[r"secret-[A-Za-z0-9]+"] |
Replace regex matches in supported message text and tool arguments/results with __REDACTED__. Accepts strings or compiled regexes. |
allow=lambda match: match == "secret-example" |
Keep a regex match when the predicate returns True; it receives only the matched string. |
Whole withheld values generally become sha256:... fingerprints, allowing
identical content to be recognized across calls. These are deterministic hashes,
not encryption. Pattern replacement uses __REDACTED__ instead.
Mark tool arguments with a decorator
Use the initialized policy above, then mark tools where they are defined:
@aio.redact_arguments(name="run_query")
def run_query(connection, sql):
cursor = connection.cursor()
cursor.execute(sql)
return cursor.fetchall()
# Register a tool whose implementation you do not control:
aio.redact_arguments(name="third_party_lookup")
@aio.redact_arguments also works without parentheses on a function or tool
class: the SDK uses its name or function/class name. Use explicit name= when
the framework exposes a different tool name. The decorator returns the original
object; it does not register a framework tool or create a span.
Tool marks are process-wide and add to redact_tool_arguments. Import or mark
tools before their telemetry is emitted. A mark alone does not activate the
policy: use an active policy, such as the one above. Results remain visible
unless separately covered by redact_tool_results.
Hide model inputs within a function or block
This scope works without a global redaction policy, provided AIO installed its own tracing provider:
@aio.redact_model_inputs
async def private_completion(client, prompt):
return await client.messages.create(
model="your-model-id",
max_tokens=256,
messages=[{"role": "user", "content": prompt}],
)
def private_completion_sync(client, prompt):
with aio.redact_model_inputs():
return client.messages.create(
model="your-model-id",
max_tokens=256,
messages=[{"role": "user", "content": prompt}],
)
Both @aio.redact_model_inputs and @aio.redact_model_inputs() support sync and
async functions. Use a regular with inside async code too. For generators, put
the with block inside the generator; decorating a generator raises TypeError.
The scope fingerprints input messages and system instructions for model spans
and log records marked chat or text_completion. Model outputs, tool content,
graph-node content, and root-span input_preview are not hidden by this scope.
Use policy options for those fields. Async tasks created within the scope
inherit it.
LangGraph node content
aio.langgraph_node opts a node into recording its input state and return value.
Decorate before registering the function with LangGraph. It works on sync and
async nodes and relies on AIO's LangGraph instrumentation to create the span.
@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):
response = await state["model"].ainvoke(state["question"])
return {"answer": response.content}
Without selectors, the full state and return value are recorded, up to 100,000
characters per side. A selector returning None omits that side; a failing
selector is logged and omitted. If the node raises, only its input is recorded.
Recording follows the instrumentation's content-capture setting and the global
redaction policy. redact_model_inputs() does not hide node content.
Environment settings
If init(redaction=...) is omitted, these variables build the policy. An explicit
policy replaces these settings rather than merging with them.
| Variable | Equivalent policy option |
|---|---|
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=["run_query", "lookup"] |
AIO_REDACT_TOOL_RESULTS=lookup_customer |
redact_tool_results=["lookup_customer"] |
Other policy options require Python configuration.
Coverage and initialization
Call aio.init() before another library installs an OpenTelemetry
TracerProvider. An active policy raises aio.RedactionUnavailable if AIO
cannot enforce it on an existing provider. A scoped redact_model_inputs() call
instead warns when span redaction is unavailable; its log-record path remains
covered when log setup succeeded.
Rules cover the documented attributes, not arbitrary logs, exception messages,
or every copy of a value. Regex patterns do not automatically scrub
aio.input_preview, function.args, custom attributes, or SQL text. Use
redact_attributes for whole fields and redact_sql_literals for SQL values.
Suppressing a parent span also removes useful descendant spans, so choose names
carefully.
For the interaction between SQL redaction and catalog matching, see [Data-source detection].
Data-source detection
The SDK records database calls. The AIO server parses their SQL to derive table reads, writes, and column usage, then matches references to catalog assets. The SDK does not query the catalog or register data sources itself.
Automatic SQL detection
Install your database client and any required instrumentation extra. Initialize AIO before opening connections. For example, with psycopg v3:
import acceldata_aio_tracer as aio
import psycopg
aio.init(
service="orders-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",
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:password@localhost:5432/sales") as connection:
with connection.cursor() as cursor:
cursor.execute(
"SELECT id, total FROM public.orders WHERE id = %s",
(42,),
)
print(cursor.fetchone())
No per-query SDK call is required. SQLAlchemy is covered through supported, instrumented underlying drivers; using SQLAlchemy alone does not add coverage for an unsupported driver.
The server needs SQL text (db.query.text or db.statement), database system,
and connection identity. Unsupported SQL or missing required identity can
prevent extraction. Use schema-qualified table names where possible.
Map tunnels and connection aliases
Use init(data_source_hosts={...}) when the application connects through a
tunnel, private alias, or proxy that differs from the catalog's address. In the
example above, localhost:5432 maps to the registered PostgreSQL host.
- A
host:portkey matches that endpoint; a host-only key matches any port. - A
host:portmatch takes precedence over a host-only match. - A target without a port keeps the driver-reported port.
- The original connection address remains in telemetry; the mapping supplies a separate address for catalog matching.
If the argument is omitted, AIO_DATA_SOURCE_HOSTS accepts comma-separated pairs:
localhost:5432=orders-db.example.com:5432,tunnel=snowflake-account.snowflakecomputing.com.
An explicit map replaces the environment map. Host mapping requires AIO's span
exporter; initialize AIO before configuring another OpenTelemetry provider.
Declare reads and writes explicitly
Use aio.declare_assets(reads=..., writes=...) when access goes through a tool,
API, or custom connector whose SQL the SDK cannot observe. Call it inside the
span that performs the access. With AIO already initialized:
with aio.root_span(conversation_id="session-123"):
with aio.start_trace("lookup_orders"):
aio.declare_assets(
reads=[("snowflake://acme-prod", "SALES.PUBLIC.ORDERS")],
writes=[("snowflake://acme-prod", "SALES.PUBLIC.AUDIT")],
)
# Perform the corresponding data access here.
A tuple is (namespace, name). To include columns or other details, use a dict:
with aio.start_trace("read_order_totals"):
aio.declare_assets(
reads=[{
"namespace": "snowflake://acme-prod",
"name": "SALES.PUBLIC.ORDERS",
"source_type": "snowflake",
"kind": "table",
"columns": ["ID", "TOTAL"],
}],
)
| Field | Meaning |
|---|---|
namespace |
Required source identity, e.g. postgres://orders-db.example.com:5432 or snowflake://acme-prod. |
name |
Required qualified asset name, e.g. sales.public.orders or SALES.PUBLIC.ORDERS. |
source_type |
Optional source type, e.g. postgres, snowflake, or sqlserver. |
kind |
Optional object kind: table, view, file, endpoint, or collection. Catalog resolution still depends on server support. |
columns |
Optional list of column names; duplicates are removed. |
evidence |
Optional explanation supplied by the application. |
Declarations attach only to the current span; they do not propagate to child spans or create spans. Repeated calls add references and deduplicate identical ones. With no recording span, the call does nothing. A declaration describes access; it neither executes a query nor grants access to the data.
Detection and catalog matching
| Database | SQL reference extraction | Catalog asset matching |
|---|---|---|
| PostgreSQL, Redshift, Snowflake, Databricks, MySQL, SQL Server | Supported dialects. | Supported when the source and asset are registered and their identities match. |
| Trino | ANSI SQL parsing; dialect-specific statements may be skipped. | Supported when catalog identities match. |
| BigQuery | Supported dialect. | Not currently implemented. |
| Athena | ANSI SQL parsing; PyAthena instrumentation has not been validated against a live service. | Not currently implemented. |
Catalog resolution runs separately from trace ingestion. A visible SQL span does not guarantee a resolved asset: the source may be unregistered, its address may differ, the asset may be absent, or multiple catalog sources may match. Declarations also need matching namespace/name values; they do not bypass these requirements.
Preserve detection while hiding SQL values
aio.redaction_policy(redact_sql_literals=True) turns:
SELECT total FROM public.orders WHERE email = 'alice@example.com' AND id = 42
into:
SELECT total FROM public.orders WHERE email = '?' AND id = ?
Table and column identifiers remain available for parsing. SQL comments remain
unchanged. If you hide the whole db.query.text / db.statement attribute or
suppress the database span, the server cannot derive references from that SQL;
use explicit declarations on a retained span when appropriate.
Hiding tool arguments alone does not hide SQL copied onto database spans. Use both the tool redaction and SQL literal options when both channels carry values you want withheld. See Content redaction.
Tracing helpers
These helpers are available through import acceldata_aio_tracer as aio.
| Helper | Usage |
|---|---|
aio.root_span(...) |
Group one turn or workflow and propagate conversation/user attribution. |
aio.current_conversation_id() |
Get the active conversation ID, or None outside a conversation scope. |
with aio.start_trace("lookup") as span: |
Add a child operation; use span.set_metadata({...}) or span.set_result(value). |
@aio.trace |
Trace a synchronous function and record arguments and its return value. For async functions, use a with aio.start_trace(...) block around the awaited work. |
@aio.langgraph_node |
Opt a LangGraph node into input/output capture; see node examples. |
with aio.using_attributes({...}): |
Add attributes to supported auto-instrumented calls; also works as a synchronous-function decorator. |
aio.inject_additional_attributes(fn, {...}) |
Call a synchronous zero-argument function with those attributes in context. |
with aio.agent_context("support"): |
Set agent-name context for supported instrumentation. |
with aio.agent_version_context("v2"): |
Set agent-version context for supported instrumentation. |
with aio.using_tags("key:value"): |
Stamp "key:value" on spans started inside the scope; also a sync or async decorator. Adds to an enclosing set. |
aio.set_tags(...) |
Replace the current tag set. set_tags() with no arguments clears. |
aio.current_tags() |
Tags that would be stamped on a span started now. |
Tags
A tag is a "key:value" label the application already knows when the turn
starts — "escalated:yes", "region:eu". It uses the same context-variable
mechanism as the conversation id: set it for a unit of work and it is stamped
on every span started inside, whichever library produced the span. There is no
process-wide default. A tag belongs to the work, not to the process.
using_tags is the usual call. It adds to whatever an enclosing scope already
set, and restores that outer set on exit — as a context manager or as a
decorator on a sync or async function:
with aio.root_span(conversation_id="session-123"):
with aio.using_tags("region:eu"):
...
@aio.using_tags("workflow:nightly")
def run_nightly():
...
set_tags replaces the set rather than adding to it. set_tags() with no
arguments clears. Use it when this turn's tags should not inherit.
Tags apply to spans started after they are set; they do not rewrite a span that
is already open. A generator function cannot take @using_tags — use with
inside it, the same restriction as redaction.
A tag must be "key:value" with both sides nonblank, and at most 200
characters. Duplicates are collapsed; at most 32 tags are kept. Anything that
fails those rules is logged at warning and dropped, not raised, so a bad tag
cannot break the application. Empty using_tags() is the exception: that is
API misuse and raises TypeError. current_tags() returns what would be
stamped on a span started now.
Guard (Gates)
A Gate is a named, versioned set of guardrails defined in AIO. Pass it to
aio.init() and the SDK evaluates it on every supported model call: before the
request leaves the process (llm.request) and after the response comes back
(llm.response). A blocked call raises GuardBlockedError. Your call sites do
not change.
The policy engine ships as an optional extra, so the base install stays pure Python and takes no binary dependency:
pip install "acceldata-aio-tracer[guardrails]"
One call configures it:
import acceldata_aio_tracer as aio
aio.init(service="support-bot", tenant_id=..., project_id=..., endpoint=..., access_key=..., secret_key=...,
guardrails=aio.Gate("customer-chat")) # loads the Gate and guards every supported provider call below
aio.Gate(id, version="$LATEST", integrations=None, source=None)
names the Gate. A guardrail changes by publishing a new version in AIO, never per
process. integrations=["openai", "litellm"] restricts guarding to the named
integrations, each of which must be installed. source="file:/path/bundle.json"
loads the Gate from a file, for tests and air-gapped runs; the file is a bundle
the AIO server served, saved as is, because the SDK applies no parameter
defaults of its own. The bundle is the response of
GET <endpoint>/api/aio/gates/<gate id>/versions/<version or $LATEST> with the
accessKey and secretKey headers:
curl -H "accessKey: <access key>" -H "secretKey: <secret key>" \
"<endpoint>/api/aio/gates/<gate id>/versions/\$LATEST" -o bundle.json
The SDK fetches the Gate from the AIO server once, at init(); an unreachable
server or an error answer fails init(). A running process keeps the Gate it
loaded. To start without the server, ship the bundle file and pass source=.
init() loads the Gate before it installs anything. Guarding is
fail-closed: a Gate that cannot be loaded, a missing extra, a bad binding, or
any other failure to start raises acceldata_aio_tracer.gates.GateLoadError
instead of returning False, so an application that asked to be guarded never
runs unguarded. Pass guardrails to the first init() call; a later call
cannot add it. init() logs which integrations it hooked, each method the
installed client lacks, and what it cannot guard. A method that exists but cannot
be wrapped would run unguarded, so it makes init() raise GateLoadError and
removes the hooks already placed; so does an integration named in
integrations whose client is not installed.
What is guarded
The SDK guards the provider client, not the framework above it, because that is
where the content and the model are known. Every integration whose library is
importable in the process is hooked; one you install later is guarded at the
next start. A function bound before aio.init(), such as
from litellm import completion at import time, still refers to the unhooked
function and is not guarded: call through the module (litellm.completion) or
import it after init().
| Integration | Wrapped methods | Also covers |
|---|---|---|
openai |
chat.completions.create / .parse, responses.create, sync and async |
Azure OpenAI, every OpenAI-compatible server reached with the openai client, openai-agents, LangChain ChatOpenAI, LlamaIndex, CrewAI, AG2/AutoGen, smolagents and pydantic-ai when they use this client |
anthropic |
messages.create / .parse, messages.stream (request only), sync and async |
LangChain ChatAnthropic, LlamaIndex |
litellm |
completion, acompletion |
LiteLLM gateways, CrewAI, smolagents, any app on litellm |
bedrock |
converse, converse_stream (request only) on each bedrock-runtime client created after init(); not invoke_model (per-model request bodies; init() reports it as not guardable) |
LangChain ChatBedrockConverse, strands |
google-ai-studio |
models.generate_content, generate_content_stream (request only), sync and async |
google-adk, LangChain ChatGoogleGenerativeAI |
mistral |
chat.complete, chat.stream (request only), sync and async |
LangChain ChatMistralAI |
groq |
chat.completions.create, sync and async |
LangChain ChatGroq |
together |
chat.completions.create, sync and async |
Together AI models reached with the together client |
Streaming is guarded on the request only: a call with stream=True on any
integration, and the stream methods marked "request only" above, evaluate
llm.request and then return the stream to your application unguarded on
llm.response. The report records streamed: true. One async stream method
returns its stream without an await: messages.stream on anthropic's async
client. Its request is evaluated when you enter the async with, and a block
raises GuardBlockedError there, before anything is sent.
A guardrail sees one name for each tool a call declares. A function tool is its
name. A tool the provider runs itself has no function name, so it is named by
what it is: an OpenAI Responses hosted tool by its type (web_search,
file_search, code_interpreter, and mcp:<server_label> for an MCP server), a
Google built-in tool by its field (google_search, code_execution, in either
spelling), and a Bedrock systemTool by its name. A Google tool object that
names nothing, such as an MCP client session, is named by its class. A tool
allowlist blocks such a tool unless it names it.
Not guardable, and reported as such by init() so silence never means
"guarded": claude-agent-sdk (the model call happens inside the Claude Code
subprocess), in-process inference (transformers, vllm, gpt4all), the
Vertex AI SDK (vertexai; use google-genai with vertexai=True, guarded as
google-ai-studio), cohere, ollama and azure-ai-inference (call them
through litellm; Ollama also through its OpenAI-compatible endpoint with the
openai client), and every non-chat call (embeddings, images, audio).
litellm picks the wire protocol from the model prefix, never from api_base. An
OpenAI-compatible server such as a LiteLLM gateway needs openai/<name>; a bare
bedrock/... name makes litellm speak Bedrock's protocol against that host.
Classifier checks
Four check types run a model in this process instead of calling a judge or a
service: pii_classifier (Presidio over a spaCy package), topic_classifier
(a zero-shot NLI model), injection_classifier (a text-classification model)
and toxicity_classifier (detoxify, a multi-label model: one probability per
label, the check's labels picking which of the model's count). The transformer
models run their ONNX exports on onnxruntime (CPU), tokenized by the repo's
tokenizer.json; there is no torch. You choose each model through
AIO_GUARD_PII_SPACY_MODEL, AIO_GUARD_TOPIC_MODEL, AIO_GUARD_INJECTION_MODEL
and AIO_GUARD_TOXICITY_MODEL, and the export inside the repo through the
matching AIO_GUARD_*_ONNX_FILE (default onnx/model.onnx, the hub's fp32
export). The AIO LLM proxy image ships spaCy en_core_web_lg,
MoritzLaurer/ModernBERT-large-zeroshot-v2.0 (its int8 export),
ProtectAI/deberta-v3-base-prompt-injection and gravitee-io/detoxify-onnx
(its int8 export), the models below. They need the classifiers extra and the
model files on disk:
pip install "acceldata-aio-tracer[guardrails,classifiers]"
export AIO_GUARD_INJECTION_MODEL=ProtectAI/deberta-v3-base-prompt-injection@373b6af0f8d16739cff5de28be326652246bfaa3
export AIO_GUARD_TOPIC_MODEL=MoritzLaurer/ModernBERT-large-zeroshot-v2.0@a51e07b524299e309dd2b88d48b0cfa2bd9ec598
export AIO_GUARD_TOPIC_ONNX_FILE=onnx/model_int8.onnx # the published int8 export; onnx/model.onnx is the 1.5 GB fp32 one
export AIO_GUARD_TOXICITY_MODEL=gravitee-io/detoxify-onnx@2649a90c0c4774c34a2df0913703f4abf141d1bb
export AIO_GUARD_TOXICITY_ONNX_FILE=model.quant.onnx # the published int8 export, one file for every CPU
export AIO_GUARD_PII_SPACY_MODEL=en_core_web_lg # or en_core_web_lg@3.8.0 to pin the release wheel
python -m acceldata_aio_tracer.gates.classifiers download # the configured models into HF_HOME (about 1.4 GB)
A toxicity_classifier or injection_classifier check names labels the model
answers with (detoxify's are toxicity, severe_toxicity, obscene,
identity_attack, insult, threat, sexual_explicit, plus nine identity
mentions such as male or muslim that say what a text is about, not whether
it is toxic); a label the loaded model does not have fails the Gate at load.
A topic model must be an NLI model (labels entailment and contradiction, or
a two-label one); each candidate label is judged on its own pair with the
hypothesis "This text is about {label}", the one the zeroshot-v2.0 model cards
recommend. MoritzLaurer/deberta-v3-base-zeroshot-v2.0 with the default export
answers faster than ModernBERT at twice the memory. A repo without the named
export fails at download and at load, naming the variable; an export of your
own (optimum-cli export onnx, in a separate environment) works once it is in
the repo you name. OMP_NUM_THREADS, when set, bounds the threads one inference
uses: set it to the CPU limit of the deployment.
The download command fetches the Hugging Face models into the cache and the
spaCy package's release wheel into HF_HOME/aio-spacy, from where Presidio
loads it by path, so nothing is pip-installed; a spaCy package that is
installed (pip install https://github.com/explosion/spacy-models/releases/download/en_core_web_lg-3.8.0/en_core_web_lg-3.8.0-py3-none-any.whl)
is used first. Without a version, the wheel follows the installed spaCy's
release line (spaCy 3.8.x takes en_core_web_lg-3.8.0).
Which model stands behind each check is yours to set: the three variables
above are runner bindings with no default, so a Gate that references a check
whose variable is unset fails to load, naming it. The SDK does not download a
model at run time: a Gate that references one it cannot find fails to load,
naming the download command. For development, AIO_GUARD_FETCH_MODELS=1
makes that Gate load fetch what is missing instead, exactly as the command
does; leave it unset in production and in the proxy image, which runs with
the hub offline. A Gate loads the models its
templates use when it loads, once per process, and keeps them; each model
answers one check at a time on its own thread, and a check that outlasts its
timeoutMs is an ERROR like any other. pii_classifier runs against a Presidio
analyzer service instead when AIO_GUARD_PII_ENDPOINT is set (its /analyze
API, same output), which needs no model and no extra.
The system templates on them: pii-classifier, topic-classifier-denylist,
topic-classifier-allowlist, prompt-injection-classifier; pii-regex is the
pattern-only counterpart. The AIO LLM proxy image carries the models. An SDK
from before this change refuses a Gate that uses these types at load (unknown
check type), so bind them to a gate only once every process on it runs an SDK
that has them.
Runner bindings
Some configuration belongs to the process that runs the Gate, not to a template or a request. The SDK reads it from the environment:
| Variable | Meaning | Default |
|---|---|---|
AIO_GUARD_JUDGE_MODEL |
The model an llm_classifier check calls, by its name on the judge endpoint (no provider prefix). The judge is never called through your own client. Required by a Gate with an llm_classifier check: without it init() raises GateLoadError naming this variable. |
none |
AIO_GUARD_JUDGE_BASE_URL |
The judge's OpenAI-compatible base URL, such as https://<gateway>/v1; the SDK posts to <base>/chat/completions. Required by a Gate with an llm_classifier check. A server that rejects a request field fails the check: OpenAI's reasoning models want max_completion_tokens and some models reject temperature: 0, so put such a judge behind a gateway that maps them, such as LiteLLM. |
none |
AIO_GUARD_JUDGE_API_KEY |
Sent as Authorization: Bearer <key> when set. |
none |
AIO_GUARD_JUDGE_MAX_OUTPUT_TOKENS |
Output token budget for the judge. Reasoning counts against it, so a thinking model needs room. A Gate with an llm_classifier check fails to load when it is not positive. |
2048 |
AIO_GUARD_JUDGE_REASONING_EFFORT |
Sent as reasoning_effort on every judge request. Set it to an empty value to omit it, which models that reject the field (e.g. OpenAI non-reasoning models) need. |
low |
AIO_GUARD_CHECK_TIMEOUT_MAX_MS |
Ceiling applied to every check's timeout, in milliseconds. A Gate with a check fails to load when it is not positive. | 30000 |
AIO_GUARD_PII_ENDPOINT |
A Presidio analyzer service's base URL (e.g. http://presidio:3000). Set, a pii_classifier check POSTs its /analyze API; unset, Presidio runs in this process (the classifiers extra). |
none |
AIO_GUARD_PII_LANGUAGE |
The language Presidio analyses, in both modes. | en |
AIO_GUARD_INJECTION_MODEL |
The Hugging Face model behind injection_classifier, as <repo>@<revision> (main when the revision is omitted); its labels must be SAFE and INJECTION. Required by a Gate with that check. |
none |
AIO_GUARD_INJECTION_ONNX_FILE |
The ONNX export of that model inside its repo, run on onnxruntime. | onnx/model.onnx |
AIO_GUARD_TOPIC_ONNX_FILE |
The ONNX export of the topic model inside its repo (e.g. onnx/model_int8.onnx for ModernBERT-large-zeroshot-v2.0). |
onnx/model.onnx |
AIO_GUARD_TOXICITY_MODEL |
The Hugging Face model behind toxicity_classifier, as <repo>@<revision>: a multi-label text classifier whose labels the check's labels select (detoxify). Required by a Gate with that check. |
none |
AIO_GUARD_TOXICITY_ONNX_FILE |
The ONNX export of that model inside its repo (e.g. model.quant.onnx for gravitee-io/detoxify-onnx). |
onnx/model.onnx |
AIO_GUARD_TOPIC_MODEL |
The zero-shot NLI model behind topic_classifier, same shape. Required by a Gate with that check. |
none |
AIO_GUARD_PII_SPACY_MODEL |
The spaCy package Presidio runs on for an in-process pii_classifier (e.g. en_core_web_lg); it must match AIO_GUARD_PII_LANGUAGE. Required by a Gate with that check unless AIO_GUARD_PII_ENDPOINT is set. |
none |
AIO_GUARD_MODEL_FAMILIES |
JSON object mapping a model family to a list of model-id substrings, such as {"gemini-flash": ["gemini-"]}. It is merged over the built-in families (claude-sonnet, claude-haiku, gpt-4o, gpt-4.1) that a model allowlist can name. |
built-in families |
${NAME} endpoints, such as AIO_INJECTION_CLASSIFIER_URL |
A template names an http_classifier endpoint only as ${NAME}; the SDK reads the environment variable of that name. init() raises GateLoadError naming every variable the Gate needs and does not find. |
none |
Telemetry
Export telemetry to the gateway ingest route
(OTEL_EXPORTER_OTLP_ENDPOINT=https://<gateway>/aio), never to the collector
port: the collector drops spans that lack the identity the gateway injects.
Each evaluation records an aio.gate.evaluate span, with an
aio.guardrail.evaluate child per guardrail. A guardrail whose check called the
judge carries aio.check.model, aio.check.input_tokens and
aio.check.output_tokens. The judge's call is an HTTP request: with the requests
instrumentation on, it is an HTTP client span without content, never a chat
span. AIO shows these spans as kind guardrail.
The gate span sits beside the model call it checks, under the same parent: the request evaluation before it, the response evaluation after it. When a framework such as LangChain opens its own model span before calling the provider client, the gate spans open under that span's parent rather than inside it. That model span still spans the evaluations in time, because the framework starts it first.
A guardrail's block is an error on the gate span and on the blocking guardrail's
span. A gate-level evaluation error that blocks (the request payload could not be
built and a guardrail has onError BLOCK) opens no gate or guardrail span; it is
logged as a warning. On a
direct provider call the guard runs outside the model call: a blocked request is
never sent, so it has no model span, and a blocked response is raised after the
model span ended, so that span keeps its status, its token usage and its cost.
A framework that opens its own model span before it calls the provider client, such as LangChain, runs the guard inside that span. A block raised from the client passes through it, so the framework marks its model span as an error as well. On a blocked response the framework never reaches its normal end, so its model span carries no token usage and no cost. It also records no input or output: the framework emits them only when its model call ends normally, the provider instrumentor is suppressed under a framework, and the guard records content only for a blocked request.
Each guardrail span carries the OpenTelemetry GenAI evaluation fields:
gen_ai.evaluation.name is the guardrail id, gen_ai.evaluation.score.label its
decision, and gen_ai.evaluation.score.value its score when the score is a number.
disable_events turns off the blocked-content record below.
A blocked request also records what it blocked: a
gen_ai.client.inference.operation.details record with gen_ai.input.messages,
on the blocking guardrail's span, when message content capture is on. Redaction
applies to it like any model input, and AIO shows it as that span's Input. An
allowed call records no guard content: the model span already carries it.
The gate span's aio.guard.input_preview names the event, the gate and its
version, for example llm.request · gate customer-chat v3 ($LATEST) · 2 guardrails. Its aio.guard.output_preview counts the outcome, for example
BLOCK · 1 of 2 passed · blocked by restricted-terms (KEYWORD_MATCH) · 0 not evaluated. Each guardrail span's output preview is its decision and reason
code. Neither carries content or a judge's explanation.
Handling a block
from acceldata_aio_tracer import gates
try:
response = client.chat.completions.create(model="gpt-4o", messages=messages)
except gates.GuardBlockedError as blocked:
print(blocked.report.event) # "llm.request" or "llm.response"
from acceldata_aio_tracer import gates; gates.last_reports() returns the
reports of the most recent guarded call in the current thread or asyncio task, so
read it where the call was made; a block raises gates.GuardBlockedError
with the report attached. On llm.request the provider is never called; on
llm.response it was, and your application never receives the content.
gates.current_gate() returns the loaded Gate, or None.
See examples/demo_gates.py for a runnable walk through the block and allow paths, offline.
Troubleshooting
- Initialization failed:
init()returnsFalseand logs the reason for ordinary setup failures. Check the tenant ID, project selector, endpoint, and credentials. A redaction policy that cannot be enforced raisesaio.RedactionUnavailable. - Missing instrumentation: call
init()before constructing clients. Install the appropriate optional instrumentation for your HTTP libraries or database drivers. - Configuration changes have no effect: after successful initialization,
subsequent
init()calls returnTruewithout reconfiguring the SDK. - Missing tags: set tags before the span starts.
init()does not apply a process-wide default; tags belong to the unit of work.
More examples
See the repository examples for LangChain chat, streaming, and a LangGraph workflow. They use the shared telemetry setup, environment template, and a separate dependency configuration.
License
Apache-2.0. Includes instrumentation from OpenLIT; see UPSTREAM.md for attribution and changes.
Metadata
Release files for acceldata-aio-tracer 1.2.0.dev1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| acceldata_aio_tracer-1.2.0.dev1.tar.gz | 582.3 kB | Without provenance | Details for acceldata_aio_tracer-1.2.0.dev1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| acceldata_aio_tracer-1.2.0.dev1-py3-none-any.whl | Python 3 | none | any | Details for acceldata_aio_tracer-1.2.0.dev1-py3-none-any.whl |
Total release size: 1.3 MB
Release files / acceldata_aio_tracer-1.2.0.dev1.tar.gz
| Download URL | acceldata_aio_tracer-1.2.0.dev1.tar.gz |
|---|---|
| Size | 582.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8e62ad121e8a12487d9399dd7dc92142996ff1109ea7ca9948c1dce04ff8824f
|
|
BLAKE2b-256 checksum How to use checksums |
f17c485e3b4c41305897411168c1a0bb1a7beaf7fb6eed53d6b6ee1ac66a38f9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.4.1 CPython/3.14.5 Darwin/25.5.0
|
Release files / acceldata_aio_tracer-1.2.0.dev1-py3-none-any.whl
| Download URL | acceldata_aio_tracer-1.2.0.dev1-py3-none-any.whl |
|---|---|
| Size | 765.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
45eabca181e66965c85a0aa1886899456448a2d99e391cf00e637fa626e45b30
|
|
BLAKE2b-256 checksum How to use checksums |
10ce74c1ae22501e943093afda0c4f09489f6e332008a851a727d66eb45ca2d3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.4.1 CPython/3.14.5 Darwin/25.5.0
|
Security for acceldata-aio-tracer 1.2.0.dev1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.