Metadata-Version: 2.4
Name: trailai
Version: 1.7.0
Summary: OpenTelemetry-native auto-instrumentation for LLM applications, agents and GPUs, with prompts, vault and guardrails from TrailAI
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: OpenTelemetry,otel,otlp,llm,tracing,openai,anthropic,claude,cohere,llm monitoring,observability,monitoring,gpt,Generative AI,chatGPT,gpu,agents
Author: TrailAI
Author-email: support@trailai.dev
Requires-Python: >=3.10,<4.0
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Provides-Extra: evals
Requires-Dist: anthropic (>=0.30) ; extra == "evals"
Requires-Dist: openai (>=1.40) ; extra == "evals"
Requires-Dist: opentelemetry-api (>=1.28,<2)
Requires-Dist: opentelemetry-exporter-otlp-proto-http (>=1.28,<2)
Requires-Dist: opentelemetry-instrumentation (>=0.49b0)
Requires-Dist: opentelemetry-sdk (>=1.28,<2)
Requires-Dist: pydantic (>=2.5,<3)
Requires-Dist: requests (>=2.31,<3)
Requires-Dist: wrapt (>=1.14,<3)
Project-URL: Documentation, https://app.trailai.dev/docs
Project-URL: Homepage, https://trailai.dev
Project-URL: Issues, https://github.com/tmam-dev/trail/issues
Project-URL: Repository, https://github.com/tmam-dev/trail
Description-Content-Type: text/markdown

# 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](https://trailai.dev).

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

Requires Python 3.10+.

## Quickstart

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

```python
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

```python
@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

```python
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

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

## Datasets and experiments

```python
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

```python
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:

```python
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

