Skip to main content

TrailAI Python SDK (trailai)

OpenTelemetry-native observability for LLM applications and agents. One call to trail.init() traces 40+ LLM providers, frameworks and vector databases, and gives you prompt management, a secret vault and guardrails from TrailAI.

pip install trailai            # tracing, prompts, vault, guardrails
pip install "trailai[evals]"   # + LLM-as-judge evaluators (OpenAI / Anthropic)

Requires Python 3.10+.

Quickstart

export TRAIL_URL="https://your-trail-host/api/sdk/v1"
export TRAIL_PUBLIC_KEY="pk-trail-..."
export TRAIL_SECRET_KEY="sk-trail-..."
import trail

trail.init(application_name="support-bot", environment="production")

# Call init() before creating provider clients.
from openai import OpenAI
client = OpenAI()
client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hi"}])

Credentials can also be passed directly: trail.init(url=..., public_key=..., secret_key=...). TRAIL_URL may be given as https://host/api/sdk/v1 or https://host/api/sdk.

Manual tracing

@trail.trace(role="agent", goal="Answer the customer's question")
async def support_agent(question: str) -> str:   # sync and async functions both work
    docs = await search_docs(question)
    return await answer(question, docs)

@trail.trace(role="tool")
async def search_docs(query: str): ...

with trail.start_trace("plan", role="agent step") as span:
    span.set_metadata({"step": 1})

Prompts, vault and guardrails

prompt = trail.get_prompt(name="support-answer", version="3")
trail.get_secrets(key="STRIPE_KEY", should_set_env=True)

verdict = trail.guard.input(user_text, user_id=user.id)
...
trail.guard.output(model_text)   # pairs with the input() call in the same request

Guardrail calls fail closed: if TrailAI can't be reached, the text is reported as blocked (verdict == "yes").

Evaluations

detector = trail.evals.Hallucination(provider="openai")   # needs trailai[evals]
result = detector.measure(prompt=q, contexts=docs, text=answer)

Datasets and experiments

trail.dataset.create_dataset("capitals", description="Country -> capital")
trail.dataset.create_dataset_item("capitals", input={"country": "France"}, expected_output="Paris")

def ask(*, item):                       # sync or async
    return my_llm(f"Capital of {item.input['country']}?")

def exact(*, output, expected_output, **_):
    return trail.Evaluation(name="exact", value=float(output == expected_output))

result = trail.dataset.get_dataset("capitals").run_experiment(name="capitals", task=ask, evaluators=[exact])
print(result.format())

Each item runs in its own trace, with the task's LLM calls nested under it and evaluator scores recorded as trail.experiment.score.<name>. trail.run_experiment(name=..., data=[...], task=...) works on local data too.

GPU metrics

trail.init(..., collect_gpu_stats=True)   # pip install nvidia-ml-py (NVIDIA) or amdsmi (AMD)

Configuration

init() argument Env var Default
url TRAIL_URL — TrailAI SDK URL
public_key TRAIL_PUBLIC_KEY —
secret_key TRAIL_SECRET_KEY — secrect_key= is still accepted
application_name / environment — default service.name / deployment.environment
capture_message_content OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=false True Set False to never record prompts, completions or traced arguments
disabled_instrumentors — [] e.g. ["langchain"]
disable_metrics — False
disable_batch — False Export each span immediately (debugging only)
collect_gpu_stats — False Export NVIDIA/AMD GPU metrics
pricing_json TRAIL_PRICING_JSON bundled + refreshed Custom cost table (file or URL)

Other environment variables: TRAIL_DISABLE_PRICING_FETCH=true (never fetch prices online), TRAIL_GUARDRAIL_TIMEOUT (seconds, default 120), TRAIL_EXPORT_EVENTS=true (also export OTel log events, e.g. to a collector), and the standard OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT / OTEL_BSP_MAX_EXPORT_BATCH_SIZE (defaults 32768 characters / 128 spans).

Short-lived processes

Buffered spans are exported at interpreter exit. In serverless handlers or code that calls os._exit(), flush explicitly:

trail.flush()      # or trail.shutdown()

Failure behaviour

The SDK never raises into your application: missing credentials, an unreachable TrailAI server or an unexpected provider response only disable or reduce telemetry. Errors raised by your own code and provider SDKs propagate unchanged.

Documentation: https://app.trailai.dev/docs · License: Apache-2.0

Metadata

Release files for trailai 1.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for trailai 1.7.0
File Size Uploaded Provenance Actions
trailai-1.7.0.tar.gz 165.7 kB Without provenance Details for trailai-1.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for trailai 1.7.0
File Interpreter ABI Platform Actions
trailai-1.7.0-py3-none-any.whl Python 3 none any Details for trailai-1.7.0-py3-none-any.whl

Total release size: 467.5 kB

Release files / trailai-1.7.0.tar.gz

Download URL trailai-1.7.0.tar.gz
Size 165.7 kB
Tags Source
SHA-256 checksum
How to use checksums
777e9e4e7073717aa2d95dc76168b9afcafae4e85da49d98425ffdb9e0e46ab4
BLAKE2b-256 checksum
How to use checksums
10b117937595d3090e0faae26558ce182a57a95e533b774ef09e93139595e151
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Release files / trailai-1.7.0-py3-none-any.whl

Download URL trailai-1.7.0-py3-none-any.whl
Size 301.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
58ce9720d6f7cdf2b8704d38a5a03141f6805a991dd31877b4ac410a490fe9e9
BLAKE2b-256 checksum
How to use checksums
4c76c5d7c4b098c06a6a8654591d9399d3b08cd02338ded1f9c7fbb240e438d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Security for trailai 1.7.0

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page