Skip to main content

trAIce Python SDK

The traice-sdk distribution records LLM model usage, tokens, cost, latency, status, and product attribution, then sends events to trAIce on a background thread. Provider responses and exceptions pass through unchanged. Its Python import name is traice.

Install

pip install traice-sdk

Python 3.9 or newer is supported. The core package has no runtime dependencies. OpenAI, Anthropic, and LangChain remain optional application dependencies. PyPI does not support scoped package names, and the unrelated traice distribution is already registered, so installation uses traice-sdk while imports use traice.

Five-minute quickstart

Configure the client once when your process starts:

import os

from traice import configure

configure(
    api_key=os.environ["TRAICE_API_KEY"],
    endpoint="https://runtraice.com/api/v1/events",
)

Decorate a sync or async function that returns an OpenAI or Anthropic response:

from openai import OpenAI
from traice import track

openai = OpenAI()

@track(
    feature="support-summary",
    tenant_id="customer_42",
    user_id="user_123",
    workflow_id="support",
)
def summarize_ticket():
    return openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Summarize this ticket"}],
    )

completion = summarize_ticket()

The decorator reads usage from current OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages response shapes. It captures provider-reported cache tokens when present.

Context manager

Use a context manager when a decorator does not fit. Attach the response with span.record() so token usage can be extracted:

from traice import track

with track(feature="answer", tenant_id="customer_42") as span:
    response = span.record(openai.responses.create(model="gpt-4o-mini", input="Hello"))

Async context managers are supported too:

async with track(feature="answer", tenant_id="customer_42") as span:
    response = span.record(await async_openai.responses.create(model="gpt-4o-mini", input="Hello"))

Attribution dimensions

track() accepts the same collection dimensions as @traice/sdk:

Python argument Event field Use
feature feature Product feature or request path
user_id userId End user
tenant_id tenantId Paying customer or account
agent_id agentId Agent identity
workflow_id workflowId Workflow identity
run_id runId One workflow or agent execution
step_id stepId Step within a run
tool_name toolName Tool used by an agent
retry_count retryCount Retry attempt number
outcome outcome Product or workflow outcome
metadata metadata JSON-serializable structured context

metadata.sdk is always python and metadata.sdkVersion contains the package version.

Batching and shutdown

Events are appended to a bounded in-memory queue. A daemon thread sends batches every five seconds or when 50 events accumulate. A failed batch is retried once, then dropped. Collection failures do not enter the application request path.

Tune this behavior at startup:

configure(
    api_key=os.environ["TRAICE_API_KEY"],
    batch_size=100,
    flush_interval=2.0,
    timeout=5.0,
    max_queue_size=5_000,
)

The SDK registers an atexit flush. Explicitly flush short-lived scripts and serverless handlers:

from traice import flush

flush(timeout=2.0)

configure() returns a TraiceClient. Call client.stats() to inspect enqueued, sent, dropped, failed-batch, and queued counts.

Errors

Provider exceptions are re-raised unchanged. The SDK queues an error event with zero tokens, measured latency, and a truncated error message in metadata.

Calling track() before configure() leaves the provider call unchanged and records nothing. configure() rejects a missing API key immediately. It uses TRAICE_API_KEY when api_key is omitted.

Custom endpoint and pricing

endpoint accepts either the site base URL or the full /api/v1/events URL. Unknown models are sent with costUsd: 0 while their token counts remain intact. Add local pricing in USD per million tokens:

from traice import configure_pricing

configure_pricing(
    "openai",
    "my-fine-tuned-model",
    input_per_million=1.25,
    output_per_million=5.0,
)

LangChain and LangGraph

The callback handler has no hard LangChain dependency:

from traice.integrations import TraiceCallbackHandler

handler = TraiceCallbackHandler(feature="research", tenant_id="customer_42")
result = chain.invoke({"topic": "unit economics"}, config={"callbacks": [handler]})

The handler captures the token usage and model information that LangChain exposes through llm_output. LangGraph accepts the same callback configuration.

Privacy

The SDK sends usage metadata, attribution dimensions, and error text. It does not send prompts or model outputs. Do not place secrets or sensitive content in attribution fields or metadata.

Development

Run the dependency-free test suite:

PYTHONPATH=src python -m unittest discover -s tests -v

Build the package with python -m build. Release artifacts are source distributions and universal Python wheels.

Download files

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

Source Distribution

traice_sdk-0.1.0.tar.gz (23.5 kB view details)

Uploaded Source

Built Distribution

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

traice_sdk-0.1.0-py3-none-any.whl (12.7 kB view details)

Uploaded Python 3

File details

Details for the file traice_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: traice_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 23.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for traice_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ae27c7789d3ef5754bb24fa955087c57ecd4a6a39cdd9d4138c7cca66347bf3e
MD5 01d0956ded5ed6ac4e86fc801ea8a56b
BLAKE2b-256 8506041e72085d6b6d04bdd6491e9da4cf084010ac860c7487db3ef3eda58fea

See more details on using hashes here.

Provenance

The following attestation bundles were made for traice_sdk-0.1.0.tar.gz:

Publisher: release.yml on runtraice/traice-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file traice_sdk-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: traice_sdk-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for traice_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6d21f1b4dede077b85738945ed28e30a2c4863ce14ca89fbecd55375c3fbcbc2
MD5 edabfff78acdb1f9327814b5c681bbdd
BLAKE2b-256 827c817fb566663ad756d8dbb9e50b12ca9c26250a94eacdf6e075b684b6b97e

See more details on using hashes here.

Provenance

The following attestation bundles were made for traice_sdk-0.1.0-py3-none-any.whl:

Publisher: release.yml on runtraice/traice-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.1.1

2 files

This release

0.1.0 This release

2 files

Supported by

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