Skip to main content

Official Python SDK for AITracer — tracing, verification, governance, cost intelligence, and integrations

Project description

AITracer Python SDK

This directory is the official Python package in the AITracer monorepo (python/aitracer-sdk/). The TypeScript SDK lives at packages/sdk (npm install @noirstack/aitracer-sdk); starters are under starters/ and examples under examples/python-sdk/.

Official Python entrypoint for AITracer — tracing, verification, governance signals, cost intelligence, and first-party integrations (OpenAI Agents, OTLP/JSON, Guardrails).

Install from PyPI (package name aitracer-sdk, import as aitracer):

pip install aitracer-sdk

Current version: 0.3.0


Configure

Use an workspace API key (akt_…) and your app base URL (same origin as the AITracer web app).

from aitracer import AITracerClient, configure

configure(api_key="akt_xxx", base_url="https://your-app.example.com")

# Or construct a client explicitly:
client = AITracerClient(api_key="akt_xxx", base_url="https://your-app.example.com")

The client uses retries, timeouts, and Authorization: Bearer on all requests.


Basic tracing

Native ingest maps to POST /api/traces.

from aitracer import trace, configure

configure(api_key="akt_xxx", base_url="https://your-app.example.com")

trace.record(
    workflow="customer-support-agent",
    model="gpt-4.1",
    input_data={"query": "Status?"},
    output_data={"answer": "Shipped."},
    metrics={"promptTokens": 50, "completionTokens": 20, "latencyMs": 400},
)

Async tracing

For FastAPI, async agents, and event loops, install httpx:

pip install 'aitracer-sdk[async]'
import asyncio
from aitracer import AsyncAITracerClient, configure_async, trace

async def main():
    configure_async(api_key="akt_xxx", base_url="https://your-app.example.com")
    await trace.arecord(
        workflow="async-job",
        model="gpt-4.1",
        input_data={"q": "hello"},
        output_data={"a": "world"},
    )

asyncio.run(main())

AsyncAITracerClient uses async retries with exponential backoff on timeouts, connection errors, and 429 / 502 / 503 / 504.


Batch ingestion

Sync (thread pool, preserves order):

from aitracer import trace, configure

configure(api_key="akt_xxx", base_url="https://your-app.example.com")

trace.batch_record(
    [
        {"workflow": "bulk-1", "model": "gpt-4o-mini", "input_data": {"i": 1}},
        {"workflow": "bulk-2", "model": "gpt-4o-mini", "input_data": {"i": 2}},
    ],
    max_workers=8,
)

Async (bounded concurrency):

await trace.batch_arecord(
    [{"workflow": "a", "model": "gpt-4o"}, {"workflow": "b", "model": "gpt-4o"}],
    concurrency=8,
)

CLI

After install, the aitracer command is available:

aitracer init                    # print starter AITRACER_* env vars
export AITRACER_API_KEY=akt_...
export AITRACER_BASE_URL=https://your-app.example.com
aitracer test-ingest             # POST a minimal trace
aitracer verify <trace_id>       # best-effort lookup (depends on auth mode)

HTTP errors & observability

AITracerHTTPError includes request_id, correlation_id, url, attempts_made, and a response_body excerpt. Use exc.diagnostics() for structured logging.


Verification

Many deployments embed verification records on the trace ingest response (there is often no standalone public verification URL).

from aitracer import verify

records = verify.records_from_response(ingest_response)
digest = verify.hash("your-trace-id")

Governance (Guardrails / policy)

Normalized guardrail and policy outcomes → POST /api/integrations/openai-guardrails.

from aitracer import governance, configure

configure(api_key="akt_xxx", base_url="https://your-app.example.com")

governance.report_policy_event(
    guardrail_name="pii",
    trigger_type="pii_detected",
    trigger_source="user_input",
    action_taken="blocked",
    trace_id="optional-public-trace-slug",
)

Cost intelligence

There is often no standalone cost HTTP API; token and spend fields are carried on trace / execution payloads. Helpers aggregate what you already ingested or listed:

from aitracer import cost

summary = cost.from_ingest_response(ingest_response)
rollup = cost.aggregate(list_of_trace_dicts)
spend_by_model = cost.get_model_spend(list_of_trace_dicts)

OpenAI Agents integration

POST /api/integrations/openai-agents

from aitracer.integrations.openai_agents import register_tracing, export_spans

cfg = register_tracing(
    base_url="https://your-app.example.com",
    api_key="akt_xxx",
)
export_spans({"traceId": "...", "spans": [...]}, config=cfg)

OTLP integration

POST /api/integrations/otlp/v1/traces (JSON encoding).

from aitracer.integrations.otlp import export_resource_spans, collector_exporter_yaml_snippet
from aitracer import AITracerClient

client = AITracerClient(api_key="akt_xxx", base_url="https://your-app.example.com")
export_resource_spans({"resourceSpans": [...]}, client=client)

print(collector_exporter_yaml_snippet(base_url="https://your-app.example.com", api_key="akt_xxx"))

Documentation


Examples

Runnable samples live in examples/ (set AITRACER_API_KEY and optional AITRACER_BASE_URL).


Local smoke install

./scripts/smoke-install-test.sh local

Roadmap (toward “production hardening”)

Shipped in 0.3.0: async client, batch ingest, richer HTTP errors, CLI stubs, trace.astream / webhooks placeholders, contrib/ for framework adapters.

Still the main leverage points for enterprise adoption:

Area Status
Async (AsyncAITracerClient, trace.arecord, batch_arecord) Implemented ([async] extra)
Batch (trace.batch_record) Implemented
Streaming (trace.astream) Not implemented — needs platform ingest contract
Framework wrappers (LangChain, LlamaIndex, CrewAI, FastAPI middleware, …) contrib/ placeholder only
CLI init, test-ingest, verify
Error observability Request/correlation IDs, URL, attempts, diagnostics()
Pydantic models Optional future extra (validation / IDE ergonomics)
Webhooks handle_verification_webhook placeholder
MCP / enterprise policy Future layers on top of stable client / trace APIs

License

MIT — see repository for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aitracer_sdk-0.4.0.tar.gz (19.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aitracer_sdk-0.4.0-py3-none-any.whl (23.1 kB view details)

Uploaded Python 3

File details

Details for the file aitracer_sdk-0.4.0.tar.gz.

File metadata

  • Download URL: aitracer_sdk-0.4.0.tar.gz
  • Upload date:
  • Size: 19.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for aitracer_sdk-0.4.0.tar.gz
Algorithm Hash digest
SHA256 0164f58a1d11307717aa48280da261300ea93a9e0100e2c0ea811681d0f5df6d
MD5 c7cfce0ee4891597e0478a02123d0f0e
BLAKE2b-256 986960dbfe80a76b9563864544629b3a3c6a78ec0885f1a3f64d0db5e2dfd0de

See more details on using hashes here.

File details

Details for the file aitracer_sdk-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: aitracer_sdk-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 23.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for aitracer_sdk-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2eb2138c2653ed803c67643e9a80289793d221bc384c984cdd458ce05fe6825c
MD5 707adaf8d1ebb4738bf29ea2250d3af2
BLAKE2b-256 65d27afc898f82071923fbc94648f989178fbd9dc1f81194693c2fe9b7781cef

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page