Observability

Give your own Python services traces, metrics and logs over OpenTelemetry in a few lines.

aice-observability isn't an API client. It's the OpenTelemetry setup every AICE service uses, packaged so your own Python services report the same way: traces, metrics and logs, sent to any OTLP endpoint. Because it doesn't call an AICE service, it needs no project key and doesn't share the other packages' transport or error types.

pip install aice-observability

It is Python only, and it is not part of the umbrella: install it directly.

Set it up

from fastapi import FastAPI
from observability import Observability

app = FastAPI()

obs = (
    Observability()
    .service("orders-api", version="2.0.0")
    .start()                      # before any library instrument_*() call
    .instrument_fastapi(app)
    .instrument_sqlalchemy(engine)
)

Observability is a builder: each method returns the same object, so the calls chain. In order:

  1. .service(name, version=None) names the service. It must come before .start().
  2. .start() creates the trace, metric and log pipelines from the environment (below) and registers them globally. Calling it twice in one process raises RuntimeError, because OpenTelemetry's providers are process-wide singletons. Outgoing httpx calls are traced automatically once it runs.
  3. .instrument_*() attach to the libraries you use.
  4. .shutdown() flushes and stops exporting. Call it on exit so the last spans and metrics aren't lost.

Call .start() before the library instrument_*() calls. OpenTelemetry's instrumentation attaches to whatever provider is registered at the moment it runs. Those calls raise RuntimeError if .start() hasn't run, so a wrong order fails loudly rather than recording nothing.

What each method instruments

MethodInstrumentsNeeds .start() first?
instrument_fastapi(app)FastAPI requestsno
instrument_flask(app)Flask requestsno
instrument_django()Django requestsyes
instrument_sqlalchemy(engine)one SQLAlchemy engineyes
instrument_psycopg()Psycopg 3, pooled connections includedyes
instrument_psycopg2()Psycopg 2yes
instrument_asyncpg()asyncpg pools and connectionsyes
instrument_redis()redis-py commandsyes
instrument_botocore()boto3 / botocore: S3 and S3-compatible stores such as MinIOyes
instrument_celery()Celery producers and workersyes

Each integration skips quietly when the library it instruments isn't installed. Database integrations emit spans, not metrics; the collector derives the database dashboard's series from them.

FastAPI and Flask: when to instrument

instrument_fastapi() and instrument_flask() wrap one app object, so they don't need .start(). But they must run before the app serves its first request. Starlette builds its middleware stack on the first ASGI call, and the lifespan startup event is that call, so instrumenting FastAPI from inside a lifespan silently records nothing.

If your service starts telemetry in its lifespan, instrument the app at import and start telemetry later. The instrumentor binds to OpenTelemetry's global proxy providers, which forward to the real ones once .start() runs:

from observability.frameworks.fastapi import instrument_fastapi

app = FastAPI(lifespan=lifespan)   # the lifespan calls Observability()....start()
instrument_fastapi(app)

Celery

Call instrument_celery() in the publishing process and in each worker child process (for example from Celery's worker_process_init signal), since the worker pool forks. Celery then carries the trace in its message headers on its own.

Configure it

Settings come from the environment:

VariableDefaultMeaning
OTEL_EXPORTER_OTLP_ENDPOINTwhere to send telemetry, over OTLP HTTP. Required unless every signal is off
OTEL_EXPORTER_OTLP_HEADERSauth headers as key=value,key=value, for hosted backends. Values are percent-decoded, so write Authorization=Bearer%20<token>
OTEL_SERVICE_NAMEthe service's name in dashboards. Required unless you call .service(name)
OTEL_ENVIRONMENTdevelopmentdevelopment, staging, production…
OTEL_TRACES_ENABLEDtruesend traces
OTEL_METRICS_ENABLEDtruesend metrics
OTEL_LOGS_ENABLEDtruesend logs
OTEL_LOG_LEVELINFOthe lowest log level captured
.env
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
OTEL_SERVICE_NAME=orders-api
OTEL_ENVIRONMENT=production

OTEL_SERVICE_NAME wins over .service(name). That lets one image run as several processes, an API and its worker, each reporting under its own name without a rebuild. It is also enough on its own for .start().

Traces across your own queues

Celery carries the trace for you. A job stored in a Postgres table, a pgmq payload or any other hand-rolled queue does not, so the worker would start a new, unconnected trace. Carry it yourself:

from observability.propagation import continue_trace, inject_context

# producer, inside the request's span: a dict of W3C headers (IDs only)
enqueue({"document_id": doc_id, "trace": inject_context()})

# consumer
with continue_trace(job.get("trace"), "ingest.document"):
    process(job)
  • inject_context() returns the current trace context as a plain dict[str, str] (traceparent, and tracestate when set). It serialises into JSON or a JSONB column as is, and holds IDs only, never data. It returns {} when there is no active trace.
  • continue_trace(carrier, name, kind=SpanKind.CONSUMER, attributes=None) runs the block in a span that is a child of the carrier's trace. A missing or malformed carrier starts a new trace instead of failing the job. An exception in the block is recorded on the span and re-raised.
  • extract_context(carrier) returns the OpenTelemetry context a carrier describes, for code that wants to manage spans itself.

Tracing AI agents

For services that run LLM agents, observability.ai adds spans and metrics that follow OpenTelemetry's GenAI conventions, so an agent run shows up as one trace with its model calls, retrievals and tool calls underneath.

from observability.ai.agents import invoke_agent, execute_tool, invoke_subagent, execute_workflow

with invoke_agent(agent="support-triage", conversation_id=thread_id,
                  extra_attributes={"acme.run.id": run_id}):
    with execute_tool(tool="search_knowledge"):
        ...
    with invoke_subagent(agent="billing"):
        ...
HelperSpan for
invoke_agent(agent=, conversation_id=None, session_id=None, extra_attributes=None)one complete agent run. Wrap the outermost loop
execute_tool(tool=, extra_attributes=None)one tool call
invoke_subagent(agent=)a child agent, nested under the current one
execute_workflow(name=)an end-to-end workflow made of several steps

Pass session_id only for a genuine multi-run session. A single run isn't a session; put its ID in extra_attributes instead, so dashboards grouped by session don't mix the two.

observability.ai.metrics records the aggregate side, with deliberately low-cardinality labels (provider, model, tool, store). Never attach user IDs, prompts or document IDs to metrics; those belong in traces.

FunctionRecords
record_llm_request(provider=, model=), record_llm_failure(...)request and failure counts
record_latency(provider=, model=, duration=)call duration in seconds
record_token_usage(provider=, model=, input=, output=)input, output and total tokens
record_cost(provider=, model=, usd=)cost in USD
record_tool_call(tool), record_tool_latency(tool=, duration=)tool calls and duration
record_retrieval(vector_store=, document_count=, duration=)retrievals, their duration and how many documents
record_budget_event(kind)budget events: warning, run_exceeded or tenant_exhausted

What you get

The standard dashboards are built around questions rather than raw metrics:

DashboardAnswers
Service overviewIs it healthy? How much traffic, how fast, how many errors?
InfrastructureCPU, memory, disk, network, threads, garbage collection, restarts
HTTP / APIper-endpoint rate, latency percentiles, errors, and the slowest and largest requests
Databasequery rate and duration, slow and failed queries, pool saturation. Only when a database is instrumented
External servicescalls your service makes to others
Logs and tracescorrelated by trace ID

On this page