Metadata-Version: 2.4
Name: sigil-telemetry
Version: 0.7.0
Summary: Plug-and-play telemetry for AI agents — records every LLM call and the agent's other outside calls, through any SDK or plain HTTP, and exports traces via OpenTelemetry.
Author: Zurain Khan
License-Expression: MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: opentelemetry-api>=1.20.0
Requires-Dist: opentelemetry-sdk>=1.20.0
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20.0
Requires-Dist: opentelemetry-semantic-conventions>=0.41b0
Provides-Extra: anthropic
Requires-Dist: opentelemetry-instrumentation-anthropic>=0.30.0; extra == "anthropic"
Provides-Extra: openai
Requires-Dist: opentelemetry-instrumentation-openai>=0.30.0; extra == "openai"
Provides-Extra: langchain
Requires-Dist: opentelemetry-instrumentation-langchain>=0.30.0; extra == "langchain"
Provides-Extra: crewai
Requires-Dist: opentelemetry-instrumentation-crewai>=0.30.0; extra == "crewai"
Provides-Extra: llamaindex
Requires-Dist: opentelemetry-instrumentation-llamaindex>=0.30.0; extra == "llamaindex"
Provides-Extra: vertexai
Requires-Dist: opentelemetry-instrumentation-vertexai>=0.30.0; extra == "vertexai"
Provides-Extra: mistral
Requires-Dist: opentelemetry-instrumentation-mistralai>=0.30.0; extra == "mistral"
Provides-Extra: bedrock
Requires-Dist: opentelemetry-instrumentation-bedrock>=0.30.0; extra == "bedrock"
Provides-Extra: litellm
Requires-Dist: openinference-instrumentation-litellm>=0.1.0; extra == "litellm"
Provides-Extra: cohere
Requires-Dist: opentelemetry-instrumentation-cohere>=0.30.0; extra == "cohere"
Provides-Extra: fastapi
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.41b0; extra == "fastapi"
Provides-Extra: flask
Requires-Dist: opentelemetry-instrumentation-flask>=0.41b0; extra == "flask"
Provides-Extra: django
Requires-Dist: opentelemetry-instrumentation-django>=0.41b0; extra == "django"
Provides-Extra: celery
Requires-Dist: opentelemetry-instrumentation-celery>=0.41b0; extra == "celery"
Provides-Extra: all
Requires-Dist: opentelemetry-instrumentation-anthropic>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-openai>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-langchain>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-crewai>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-llamaindex>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-vertexai>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-mistralai>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-bedrock>=0.30.0; extra == "all"
Requires-Dist: openinference-instrumentation-litellm>=0.1.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-cohere>=0.30.0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.41b0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-flask>=0.41b0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-django>=0.41b0; extra == "all"
Requires-Dist: opentelemetry-instrumentation-celery>=0.41b0; extra == "all"

# sigil-telemetry

Plug-and-play telemetry for AI agents. Install it, call `init()`, and every LLM call your agent makes is automatically tracked.

## Quick Start

```bash
pip install sigil-telemetry[all]
```

```python
from sigil_telemetry import init
init()
```

```bash
# Set your agent's ID and collector endpoint
SIGIL_AGENT_ID=sigil-hr-AGT-0001        # format: sigil-<code>-AGT-<4 digits>
SIGIL_COLLECTOR_URL=https://your-collector-endpoint/
```

That's it. Every LLM API call is now captured — tokens, model, latency, errors — and sent to your collector.

---

## What's New in v0.7.0

- **Every telemetry failure is visible, and none reaches the agent.** When something in the package fails, the agent carries on as before, and the failure is counted. The first time each kind happens, one warning names it, says what it means and how to fix it, for example: `Some telemetry could not be sent to Sigil. Fix: check SIGIL_COLLECTOR_URL and that the collector is reachable from this machine. (code: span_not_exported)`. The start-up banner lists any problems found so far under **Problems (fix these)**.
- **A self-check every hour.** At start-up and then hourly, one `sigil.check` span reports what the package found about itself, with no content and no personal data: `sigil.check.version`, `sigil.check.agent_id_format` (`ok`, `invalid` or `missing`), `sigil.check.instrumented`, `sigil.ai.default_model`, and every failure kind seen so far with its count and fix (`sigil.check.warnings`, `sigil.check.failures`). It carries `sigil.heartbeat = true`, so it is never counted as a run. Sigil's Agent Readiness panel reads it.
- **What started each run.** The root span of every run gets `sigil.run.trigger`: `user` (a request from a signed-in person), `system` (a request from another app or service, with no person), `schedule` (a timer or scheduler), `event` (a queue, task or event handler), or `unknown`. A run is where this process received the work: a request, a queued task (also when it carries the caller's trace), or a span with nothing above it. A run with no request around it but a known person (a Streamlit or Gradio app) is `user`; the worker-wide `SIGIL_USER_ID` does not count, since it names who a job runs for, not that a person started it. When the package can't see what started a run, it says `unknown` rather than guess, and warns with the fix (`trigger_unknown`). Set the trigger yourself with `SIGIL_RUN_TRIGGER` for a whole worker, or per job:

  ```python
  import sigil_telemetry

  with sigil_telemetry.run("nightly-report", trigger="schedule"):
      build_report()
  ```

  `run()` opens the run's root span (`gen_ai.operation.name = invoke_workflow`, `gen_ai.workflow.name`). Errors raised inside it reach your code unchanged, and if telemetry can't start the span the job still runs.
- **Websocket chats: one message, one run.** A websocket connection stays open for a whole visit, so it used to be one long run. Now each message the client sends starts its own run (a new trace, `sigil.run.source = websocket`, linked to the connection's span), and everything the handler does for that message in the same task is inside it. The run ends at the last reply sent, so its duration is the time to answer, not the time until the next message; a message that got no reply (a ping, a typing notice) is marked `sigil.run.replied = false`, so it can be left out of reply times. The connection's span is marked `sigil.run.container = true` and is not counted as a run. One limit: a handler that passes messages to a separate worker task (through a queue) does that work outside the message's run.
- **Scheduled jobs and Azure Functions are runs by themselves.** Each APScheduler 3.x job execution is one run with trigger `schedule`; a job that raises marks its run as an error. Each Azure Functions invocation is one run, its trigger read from the binding: a timer is `schedule`; a queue, Service Bus, Event Grid, Event Hub, blob or Cosmos DB trigger is `event`; an HTTP request is `user` or `system`, decided after the function has run (a `set_user()` inside it counts).
- **Conversations, with no code change.** Every span in a conversation gets `gen_ai.conversation.id`, from the first source that has one:
  - `sigil_telemetry.set_conversation(thread_id)` in your code;
  - a LangGraph thread (`config["configurable"]["thread_id"]`), for `invoke`, `ainvoke`, `stream` and `astream`;
  - a Bot Framework or Teams conversation (`activity.conversation.id`), for each turn;
  - the `X-Sigil-Conversation` request header (FastAPI/Starlette, Flask, Django);
  - a Streamlit, Gradio or Chainlit session (Chainlit's thread when it has one);
  - last, a websocket connection: one connection is one conversation, its ID made per connection. Anything above wins over it, so a reconnect does not split a chat that has its own thread.

  The value is sent as your app gives it, up to 200 characters; nothing is hashed in the package. A plain HTTP request that names no conversation is in none: nothing is guessed.
- **Failed calls say why.** Every failed outside call still sets ERROR, and now also carries `sigil.error.category`: `not_found` (404), `auth` (401, 403), `rate_limited` (429), `client_error` (other 4xx), `server_error` (5xx), `timeout` or `exception`, so a dashboard can keep 404 lookups apart from real failures.
- **Outside calls are named after your code.** Each outside call gets `sigil.call.name`, the function that made it (`search_refund_policy`), next to the full `sigil.agent.site`.
- **The calling app on service requests.** A request made with an app-only Entra token (a service principal) records the calling app's client ID as `sigil.caller.app` on its request span, so you can see which caller should pass the user. A token that names a person is never reported as a calling app.
- **One model call, one span.** When two layers record the same model call (an SDK instrumentor and the transport, or the SDK's own span), the one with more detail is kept. They are matched by the provider's call ID (`gen_ai.response.id`) within the same trace; spans from one layer are never merged, so a server that reuses IDs can't hide real calls.
- **Cleaner values.** `SIGIL_ENVIRONMENT` is trimmed and lower-cased (`Production`, `production ` and `PROD` are all `production`; `dev` is `development`). An `SIGIL_AGENT_ID` that is not `sigil-<code>-AGT-<4 digits>` (for example `sigil-hr-AGT-0001`) logs a clear error at start-up and is flagged in the self-check; its data is still sent. The model name is now only on AI calls (`gen_ai.request.model`), not on every span.
- **Mistral is recorded again** with current `opentelemetry-instrumentation-mistralai` releases, which renamed the instrumentor class.

**Behaviour changes to know before upgrading** (for anyone reading the data): `sigil.ai.model` is no longer on every span (the configured model is `sigil.ai.default_model` in the self-check); run root spans now carry `sigil.run.trigger`; a websocket connection is now one run per message, with the connection marked as a container; failed outside calls carry `sigil.error.category`; and `sigil.check` heartbeat spans arrive once an hour per process. No code change is needed to upgrade.

## What's New in v0.6.3

- **Anthropic calls are no longer counted twice.** Anthropic's Python SDK records each call itself from version 1.14, next to the Anthropic instrumentor, so every call reached Sigil as two spans with the same tokens (and only one of them named after the agent's code). When the Anthropic instrumentor is on, `init()` now turns the SDK's own tracing off (`ANTHROPIC_OPEN_TELEMETRY=false`, unless you set it yourself), and the SDK's spans from clients made before `init()` are not exported.

## What's New in v0.6.2

- **An agent's other outside calls are recorded too.** Agents do more than call models: they search the web, fetch prices, read records, send email. Every such call made during a run (while a span is current: a request, a job, a workflow step) is now one HTTP client span, `sigil.call.kind = "api"`, named `<METHOD> <host>`, in the step that made it: `http.request.method`, `server.address`, `server.port`, `url.path`, `url.query`, `http.response.status_code`, `sigil.agent.site` (the agent's function that made it), the calling user, request/response sizes and content type, and with content capture on the request and response bodies (`sigil.api.request.body`, `sigil.api.response.body`, text only, cut to 8000). Same clients as model calls: `httpx`, `httpx2`, `requests`/`urllib3`, `aiohttp`, `urllib`.
- **Secrets never leave the agent.** Headers are never recorded. Values of credential-like keys (`api_key`, `client_secret`, `access_token`, `password`, `Authorization`, `signature`, `sig`, …) are replaced with `[redacted]` in query strings and in JSON and form bodies, in requests and responses alike; token-like path segments (webhook and bot tokens, ids) too. With `SIGIL_CAPTURE_CONTENT=false` no body is kept and every query value is redacted.
- **Plumbing is left out.** Sign-in and token endpoints, key vaults and secret stores, telemetry and monitoring endpoints, cloud control planes and instance metadata are never recorded, nor are calls made outside a run (startup), a health probe's checks, a model call's own requests, or the collector. Add your own hosts with `SIGIL_API_SKIP_HOSTS`.
- **Handoffs from tools to models.** An outside call's answer is fingerprinted like a model's: a later model call whose input carries it (search results passed to a model) lists that call in `sigil.handoff.from`. Works with content capture off.
- **No double counting, bounded volume.** If the app already runs an OpenTelemetry HTTP client instrumentor, its spans are kept and no second one is made. Binary responses and multipart uploads are sized, not kept. At most 200 outside calls are recorded per trace; one `outside calls not recorded` span marks a trace that made more. Turn the feature off with `SIGIL_CAPTURE_API=false`.
- **AutoGen agents told apart.** AutoGen's model clients (OpenAI, Azure OpenAI, Anthropic, Azure AI, Ollama) make each request in a new asyncio task, whose stack holds none of the agent's functions, so every call used to get the app's entry point (`__main__.main`) as its `sigil.agent.site` and all of an app's AI tasks looked like one agent. The site is now taken when the client is called and carried into that task, so each call is named after the function that made it, also for streamed and parallel calls.
- **The address of SDK calls.** Spans from SDK instrumentors now get `server.address` / `server.port` (where the request really went) when the instrumentor left them out, so e.g. a model served from a cloud gateway can be told apart from the provider's own API. Never replaces what the instrumentor recorded.

## What's New in v0.6.1

- **List attributes now reach your backend.** The Azure Monitor exporter silently drops list-valued attributes, so `sigil.input.files`, `sigil.handoff.from` and instrumentors' lists such as `gen_ai.response.finish_reasons` never arrived. Every list attribute is now exported as a JSON array string, e.g. `sigil.input.files = ["image · png · 88 KB"]`.
- **Prompts of calls an instrumentor skips.** When an SDK instrumentor records a call but leaves out its input (the OpenAI instrumentor does for vision calls with images), the prompt the transport read is added — images and files as their type only (`{"type": "image_url"}`), never their data. What the instrumentor recorded is never replaced, and nothing is added when content capture is off (`SIGIL_CAPTURE_CONTENT`, `TRACELOOP_TRACE_CONTENT`, `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` or `OPENINFERENCE_HIDE_INPUTS`).
- **Launcher scripts aren't the agent.** An agent started from a console script (`uvicorn`, `gunicorn` in the venv's `bin/`) no longer gets `__main__.<module>` as its `sigil.agent.site` when its own code is installed as a package.

## What's New in v0.6.0

- **Every LLM call is captured, however it is made.** Before 0.6.0 only calls through an instrumented SDK were seen — an agent calling a model with plain `httpx.post(...)` sent nothing. `init()` now also watches the HTTP clients underneath (`httpx` and its fork `httpx2`, which the OpenAI SDK uses from 3.x, `requests`/`urllib3`, `boto3`, `aiohttp`, `urllib`) plus `websockets` (OpenAI Realtime) and `grpc` (older Gemini/Vertex SDKs). A call is recognised from its host, its route, or its request/response shape — Anthropic, OpenAI (Chat and Responses), Azure OpenAI and Foundry, Gemini/Vertex, Bedrock, Ollama, Cohere and any OpenAI-compatible server — streamed (SSE, NDJSON, AWS event-stream) or not, compressed or not.
- **No double counting.** When an SDK instrumentor is already recording a call, transport capture records no span of its own; SDK spans keep their richer detail (tool calls, agent names) and get the agent attributes below.
- **Prompts and answers recorded** on every LLM span (`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, tool calls and results included). What Sigil receives is kept as valid JSON under 8000 characters, below the Application Insights property limit of 8192 — the latest turn is protected, older turns are shortened or dropped first. Every other long string on every span, including the instrumentors' own prompt copies (`gen_ai.prompt.N.content`, `llm.input_messages.N…`, `input.value`), is cut to 8000 too, ending in `…[truncated]`. (If the app also exports to its own backend, that export gets the content unshortened, as the SDK instrumentors always sent it.) Turn off with `SIGIL_CAPTURE_CONTENT=false`.
- **One attribute vocabulary.** Spans from older OpenLLMetry versions (`gen_ai.system`, `gen_ai.usage.prompt_tokens`, `gen_ai.prompt.N.*`) and from OpenInference (`llm.*`, e.g. LiteLLM) are exported with the current `gen_ai.*` names too, so a different instrumentor version can't silently change Sigil's numbers.
- **Works alongside the app's own tracing.** If the Azure Monitor distro, Logfire or anything else already set a TracerProvider, Sigil's exporter is added to it instead of being silently dropped.
- **Processes too.** `ProcessPoolExecutor` and `multiprocessing.Process` work keeps the request's trace and user, and is flushed when it ends. Celery tasks are traced from the code that queued them (`[celery]` extra).
- **Agents told apart, from what they do.** Every LLM span says which of the agent's functions made it (`sigil.agent.site`, e.g. `app.services.llm._llm_extract ← …`). Calls from one site are compared, and what stays the same across them is the agent's **fixed prompt**: after 5 calls with at least 3 different inputs (and 2 different users, when calls carry a user) the span gets `sigil.prompt.status = split` and `sigil.prompt.id` — one id per AI task, so the same instructions called from two places in the code are one agent, and different instructions are different agents. The fixed prompt is sent once per process per version (`sigil.prompt.fixed.0`, `.1`, …, scrubbed of emails, phone numbers, IBANs, card and national id numbers), and from then on each run's `gen_ai.input.messages` carries only its input, with `{"type": "fixed"}` where the fixed prompt was.
- **Non-text input described** in `sigil.input.files`: `pdf · Report_2026.pdf · 2.1 MB`, `image · png · 88 KB`, `audio · wav · 388 KB · 12.4 s` (seconds exact for WAV and Realtime audio, `~` estimated for MP3). Files uploaded to start a request (FastAPI `UploadFile`, Flask `request.files`, Django `request.FILES`) are described on the request span — name, type and size only; this follows `SIGIL_CAPTURE_USER`. `sigil.input.chars` is the whole prompt's length before any cutting.
- **Handoffs between agents.** `sigil.handoff.from` lists the earlier spans (`<trace id>-<span id>`) whose answer this call's input carries (at least 30% of it) — one agent's output becoming another's input. `sigil.handoff.in` / `sigil.handoff.out` / `sigil.handoff.in_max` are hashed fingerprints of the input and answer, so your backend can find handoffs across processes and hours (a person reviewing in between). Ids, sites, file descriptions and fingerprints are sent even with `SIGIL_CAPTURE_CONTENT=false`; no text is.

## What's New in v0.3.0

- **Automatic user identity capture** — Extracts the calling user from Azure AD / SSO headers or JWT Bearer tokens on every request. No code changes needed — works out of the box with `init()`. Disable with `SIGIL_CAPTURE_USER=false`.
- **Worker agent support** — Set `SIGIL_USER_ID` env var for scheduled jobs and queue workers that don't have HTTP requests.
- **Background work stays in its run** (0.5.2) — LLM calls made on a `ThreadPoolExecutor` or `Thread` after the response has been sent keep the trace and user of the request that started them. Before 0.5.2 each became its own orphan trace with no user.

## What's New in v0.2.0

- **Web framework auto-instrumentation** — FastAPI, Flask, and Django are auto-detected and instrumented. All LLM calls within one HTTP request share a single `trace_id` (`operation_Id`), so you can count agent "runs" with `COUNT(DISTINCT trace_id)`.
- **Noise span filtering** — `http send` / `http send body` spans from web frameworks are silently dropped before they leave the process. They never reach your collector.
- **Health check exclusion** — Routes like `/health`, `/healthz`, `/ready`, `/alive`, `/ping` are excluded from tracing entirely.
- **Graceful shutdown** — `atexit` handler flushes all pending spans when the process exits, so you never lose the last batch.
- **Lighter install** — Removed unnecessary dependencies from the core install.

---

## Full Example

Here's a real agent that summarizes documents using Claude:

### 1. The Agent Code

```python
# document_summarizer.py
import anthropic
from sigil_telemetry import init

# Initialize telemetry — call this ONCE at startup
init()

# Your normal agent code — no changes needed
client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Summarize this document: ..."}
    ]
)
print(response.content[0].text)
```

### 2. What Gets Captured (Per LLM Call)

Every time `client.messages.create()` runs, a **span** is automatically created with:

| Field | Example Value | Description |
|-------|--------------|-------------|
| `operation_Id` | `a1b2c3d4e5f6...` | Trace ID — groups all LLM calls in a single agent run |
| `sigil.agent.id` | `doc-summarizer` | Which agent made the call |
| `sigil.agent.version` | `0.1.0` | Agent version |
| `sigil.agent.frameworks` | `Anthropic,FastAPI` | Which SDKs and frameworks were detected |
| `sigil.user.id` | `jane.doe@example.com` | Who triggered this run (auto-captured) |
| `gen_ai.system` | `anthropic` | LLM provider |
| `gen_ai.request.model` | `claude-sonnet-4-20250514` | Model used |
| `gen_ai.usage.input_tokens` | `1250` | Tokens sent |
| `gen_ai.usage.output_tokens` | `340` | Tokens received |
| `duration` | `2.3s` | How long the call took |
| `status` | `OK` or `ERROR` | Whether the call succeeded |
| `sigil.environment` | `production` | Environment |
| `sigil.agent.division` | `Sales` | Business division (if set) |
| `sigil.agent.risk_classification` | `low` | Risk level (if set) |

If the agent makes **multiple LLM calls** in one run (e.g., calls Claude then GPT-4), all calls share the same `operation_Id` so you can see the full trace.

### 3. How Trace Grouping Works

**API agents (FastAPI/Flask/Django):** The web framework instrumentor creates a root span per HTTP request. All LLM calls within that request automatically become child spans sharing the same `trace_id`. You don't need to do anything — `init()` handles it.

**Worker agents (scheduled jobs, listeners):** Wrap your `main()` function in a custom span. All LLM calls within one job share the same `trace_id`.

In both cases: `COUNT(DISTINCT trace_id)` = number of agent runs.

### 4. Where the Data Goes

```
Agent makes LLM call
        │
        ▼
sigil-telemetry auto-captures it as an OpenTelemetry span
(noise spans like "http send" are filtered out here)
        │
        ▼
Span is batched and sent via OTLP to:
  → Your configured collector endpoint
        │
        ▼
Collector forwards to:
  → Your observability backend (Jaeger, Zipkin, Datadog, etc.)
```

---

## User Identity Capture

v0.3.0 automatically captures who triggered each agent run. No code changes needed.

**How it works:**

| Auth Method | How Identity Is Captured |
|-------------|------------------------|
| Azure AD / SSO (Easy Auth) | Reads `X-MS-CLIENT-PRINCIPAL-NAME` header automatically |
| Azure AD / SSO (in-app JWT) | Decodes Bearer token, extracts `preferred_username` → `upn` → `email` → `name` → `oid` |
| Front end passes the user to a backend | Reads `X-Sigil-User` (recommended), common proxy headers (`X-Forwarded-Email`, `X-Auth-Request-Email`, `X-User-Email`, …), and, as a last resort, any header whose name mentions user/email and whose value is an email (e.g. `X-Portal-User-Email`) |
| Unusual header name | Set `SIGIL_USER_HEADER` to the header's name |
| Worker agents (no HTTP) | Reads `SIGIL_USER_ID` env var |

The captured user ID is attached as `sigil.user.id` on every request span. All LLM calls within that request inherit the user context through the shared trace.

**Disable user capture:**

```bash
SIGIL_CAPTURE_USER=false
```

Or in code:

```python
init(SigilConfig(capture_user=False))
```

---

## Supported SDKs

Use `[all]` to install everything. Only the SDKs your agent actually uses get activated.

| SDK | Install Extra | What It Covers |
|-----|--------------|----------------|
| Anthropic | `[anthropic]` | Anthropic API |
| OpenAI | `[openai]` | OpenAI API (including compatible endpoints) |
| LangChain | `[langchain]` | LangChain, LangGraph, any LangChain-wrapped model |
| CrewAI | `[crewai]` | CrewAI multi-agent framework |
| LlamaIndex | `[llamaindex]` | LlamaIndex agents and pipelines |
| Vertex AI | `[vertexai]` | Google Vertex AI, Gemini models |
| Mistral AI | `[mistral]` | Mistral API |
| AWS Bedrock | `[bedrock]` | Claude, Llama, Titan via AWS |
| LiteLLM | `[litellm]` | Unified proxy across 100+ LLM providers |

**Anything else** — raw HTTP, an SDK without an instrumentor, a self-hosted or gateway endpoint — is recorded by transport capture with no extra install: model, tokens, prompt, answer, latency and errors (no SDK-level detail such as tool calls). Those spans carry `sigil.capture.source = transport`.

Not covered: agents that are not written in Python, low-code platforms, models running inside the process (`transformers`, `llama-cpp`), Batch APIs (usage arrives hours later in a file), and gateways whose responses don't carry token usage (the call is recorded without tokens when the host is a known model host).

## Web Framework Auto-Instrumentation

These are included in `[all]` and auto-detected by `init()`:

| Framework | Install Extra | What It Does |
|-----------|--------------|--------------|
| FastAPI | `[fastapi]` | Creates root span per HTTP request — all LLM calls in that request share one trace_id |
| Flask | `[flask]` | Same trace grouping for Flask apps |
| Django | `[django]` | Same trace grouping for Django apps |
| Celery | `[celery]` | One trace per task, linked to the code that queued it |

Health check routes (`/health`, `/healthz`, `/ready`, `/alive`, `/ping`, `/startup`, `/liveness`, `/readiness`) are automatically excluded from tracing.

## Configuration

| Env Variable | Default | Description |
|-------------|---------|-------------|
| `SIGIL_AGENT_ID` | — | **Required.** Your agent's unique ID, `sigil-<code>-AGT-<4 digits>` |
| `SIGIL_AGENT_VERSION` | `0.1.0` | Track deployments |
| `SIGIL_COLLECTOR_URL` | — | **Required.** Your collector endpoint URL |
| `SIGIL_ENVIRONMENT` | `production` | `production`, `staging`, `development` (trimmed and lower-cased; `prod` and `dev` are accepted) |
| `SIGIL_RUN_TRIGGER` | — | What starts this process's runs when the package can't see it: `user`, `system`, `schedule` or `event` (for a worker or a cron job) |
| `SIGIL_CONSOLE_EXPORT` | `false` | Print spans to console for debugging |
| `SIGIL_DIVISION` | — | Business division (e.g., `Sales`, `Engineering`) |
| `SIGIL_RISK_CLASSIFICATION` | — | Agent risk level (`low`, `medium`, `high`) |
| `SIGIL_HOURS_SAVED` | — | Estimated hours saved per run |
| `SIGIL_CAPTURE_USER` | `true` | Set `false` to disable automatic user identity capture |
| `SIGIL_USER_ID` | — | Static user ID for worker agents with no HTTP context |
| `SIGIL_USER_HEADER` | — | Name of the request header that carries the signed-in user, when it isn't one the package already knows |
| `SIGIL_PROPAGATE_CONTEXT` | `true` | Set `false` to stop background threads and processes inheriting the request's trace and user |
| `SIGIL_CAPTURE_CONTENT` | `true` | Set `false` to stop recording prompts and answers |
| `SIGIL_CAPTURE_TRANSPORT` | `true` | Set `false` to record only calls made through an instrumented SDK |
| `SIGIL_CAPTURE_API` | `true` | Set `false` to stop recording the agent's other outside calls (APIs, web search, email) |
| `SIGIL_API_SKIP_HOSTS` | — | Comma-separated hosts never recorded as outside calls; a leading dot matches subdomains (`.internal.example`) |
| `SIGIL_MAX_CONTENT_CHARS` | `8000` | Longest string attribute sent. Can be lowered, never raised past 8000 (Application Insights cuts or drops a property over 8192) |

Or pass config in code:

```python
from sigil_telemetry import init, SigilConfig

init(SigilConfig(
    agent_id="sigil-hr-AGT-0001",
    environment="development",
    console_export=True,
    capture_user=True
))
```

## Custom Spans

Track things beyond LLM calls (document parsing, tool use, etc.):

```python
from sigil_telemetry import get_tracer, record_error

tracer = get_tracer()

with tracer.start_as_current_span("parse-contract") as span:
    span.set_attribute("document.pages", 42)
    try:
        result = parse_pdf(file)
    except Exception as e:
        record_error(span, e)
        raise
```
