SDK
Python SDK
On this page
Installation
pip install evigauge-trace
Optional extras
| Extra | Install | Pulls | Use when |
|---|---|---|---|
live | pip install 'evigauge-trace[live]' | rich | You want the evigauge live terminal dashboard |
shipcheck | pip install 'evigauge-trace[shipcheck]' | pyyaml | Your Ship Check policy is YAML (JSON needs no extra) |
litellm | pip install 'evigauge-trace[litellm]' | litellm | You route models through LiteLLM |
openllmetry | pip install 'evigauge-trace[openllmetry]' | traceloop-sdk | You already use OpenLLMetry |
adapters-langchain | pip install 'evigauge-trace[adapters-langchain]' | langchain-core | You use LangChain |
adapters-microsoft | pip install 'evigauge-trace[adapters-microsoft]' | (none) | You use Microsoft agent frameworks |
Core dependencies installed always: opentelemetry-api/-sdk/-exporter-otlp
(1.x), pydantic 2.x, tiktoken, httpx.
init()
Call once at process startup, before anything you want traced.
import evigauge.trace
evigauge.trace.init(
org_id="acme",
workspace_id="3f2b1c8e-9a4d-4f11-b7c2-1e5a8d3f6b90",
project_id="checkout-agent",
backend_url="https://ingest.evigauge.ai",
api_key="evg_live_xxxxxxxxxxxxxxxxxxxx",
transport="direct",
)
Parameters
All parameters are keyword-only.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
org_id | str | ✅ | — | Organization identifier |
workspace_id | str | ✅ | — | Workspace UUID the dashboard reads |
project_id | str | ✅ | — | Project slug the traces belong to. The project must already exist in the workspace — see Projects and attribution |
backend_url | str | ✅ | — | Ingest base URL — https://ingest.evigauge.ai |
api_key | str | ✅ | — | Workspace API key (evg_live_…) |
collector_endpoint | str | ➖ | http://localhost:4317 | OTLP/gRPC collector. Used only when transport="collector" |
wal_path | str | ➖ | .evigauge-wal/spans.jsonl | Crash-recovery write-ahead log |
auto_instrument | bool | ➖ | True | Patch known LLM client methods automatically |
fail_open | bool | ➖ | False | If True, init failures log instead of raising |
sampler_rate | float | ➖ | 1.0 | Fraction of traces sampled, 0.0–1.0 |
transport | str | None | ➖ | "collector" | "collector" or "direct" — see below |
Choosing a transport
transport="direct" | transport="collector" (default) | |
|---|---|---|
| Path | Your process → ingest.evigauge.ai over HTTP/JSON | Your process → local collector (gRPC) → Evigauge |
| Needs a collector | No | Yes |
Uses collector_endpoint | No — ignored | Yes |
| Best for | Serverless, containers, quick starts | Existing OTel infrastructure, local buffering, fan-out |
Override without a code change:
export EVIGAUGE_TRANSPORT=direct
The explicit transport= argument always wins over the environment variable.
Collector users: your
otlphttpexporter must setencoding: json. The protobuf default returns415from Evigauge ingest, and it fails silently from the collector's point of view — the single most common cause of "no spans arriving".YAMLexporters: otlphttp: endpoint: https://ingest.evigauge.ai encoding: json # REQUIRED headers: x-evigauge-api-key: evg_live_xxxxxxxxxxxxxxxxxxxx
What init() does
- Stores config, reachable via
get_config(). - Fetches the workspace
capture_textflag fromGET /v1/workspaces/{ws}/sdk-config. Fail-closed — if the lookup fails,capture_textisFalseand no text bodies are sent. - Builds the exporter for the chosen transport.
- Replays any WAL from a previous crashed process, then installs
DurableBatchSpanProcessor. - Registers auto-instrumentation when
auto_instrument=True.
Steps 3–5 are wrapped by fail_open. set_config() runs first and outside
that guard, so get_config() works even in a degraded state.
fail_open
| Value | Behaviour on init failure |
|---|---|
False (default) | Raises. Your process will not start mis-instrumented. |
True | Logs the exception and continues, untraced. |
Use fail_open=True in production when telemetry must never take down the
service; keep False in development so misconfiguration is loud.
Environment-driven setup
import os, evigauge.trace
evigauge.trace.init(
org_id=os.environ["EVIGAUGE_ORG_ID"],
workspace_id=os.environ["EVIGAUGE_WORKSPACE_ID"],
project_id=os.environ.get("EVIGAUGE_PROJECT_ID", "default"),
backend_url=os.environ.get("EVIGAUGE_INGEST_URL", "https://ingest.evigauge.ai"),
api_key=os.environ["EVIGAUGE_API_KEY"],
transport=os.environ.get("EVIGAUGE_TRANSPORT", "direct"),
fail_open=os.environ.get("ENV") == "production",
)
# .env
EVIGAUGE_ORG_ID=acme
EVIGAUGE_WORKSPACE_ID=3f2b1c8e-9a4d-4f11-b7c2-1e5a8d3f6b90
EVIGAUGE_PROJECT_ID=checkout-agent
EVIGAUGE_INGEST_URL=https://ingest.evigauge.ai
EVIGAUGE_API_KEY=evg_live_xxxxxxxxxxxxxxxxxxxx
EVIGAUGE_TRANSPORT=direct
@observe
Decorate a function to emit one span per call. Works on both sync and async functions — the decorator detects which and wraps accordingly.
from evigauge.trace import observe
@observe(reasoning_role="retrieval", node_type="retrieval")
def fetch_order(order_id: str) -> dict:
return db.get(order_id)
@observe(reasoning_role="synthesis", node_type="agent", name="compose_answer")
async def compose(ctx: dict) -> str:
return await llm.complete(ctx)
Parameters
Keyword-only.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
reasoning_role | str | None | ➖ | None | What this step is for — see enums |
node_type | str | None | ➖ | None | What kind of component it is — see enums |
end_user | str | None | ➖ | None | End-user identifier for per-user attribution |
name | str | None | ➖ | fn.__qualname__ | Span name override |
Error handling
An exception inside the wrapped function is recorded on the span
(record_exception), the span status is set to ERROR, and the exception is
re-raised unchanged. Instrumentation never swallows your errors.
ReasoningTrace
A context manager for a logical unit of reasoning, giving you a node object to attach structured evidence to. This is what makes reconstruction possible — plain spans record what happened; these records capture why.
from evigauge.trace import ReasoningTrace
with ReasoningTrace("answer_customer", reasoning_role="synthesis",
node_type="agent", end_user="user_8412") as node:
node.record_decision(
selected="lookup_order",
scores={"lookup_order": 0.88, "search_kb": 0.31},
alternatives=[{"name": "search_kb", "why_not": "no order id in message"}],
rules_fired=["order_id_present"],
)
node.record_sources(
consulted=["https://docs.internal/returns", "https://docs.internal/shipping"],
used=["https://docs.internal/returns"],
dropped=["https://docs.internal/shipping"],
scores={"https://docs.internal/returns": 0.93},
)
node.record_cost(
model="claude-opus-4-6",
input_tokens=2_140,
output_tokens=310,
)
Constructor
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
name | str | ✅ | — | Span name (positional) |
domain | str | None | ➖ | None | Free-form label. Not indexed — not queryable server-side. |
reasoning_role | str | None | ➖ | None | See enums |
node_type | str | None | ➖ | None | See enums |
end_user | str | None | ➖ | None | End-user identifier |
Node methods
record_decision(*, selected, scores=None, alternatives=None, rules_fired=None)
| Param | Type | Required | Description |
|---|---|---|---|
selected | str | ✅ | The option chosen |
scores | dict[str, float] | ➖ | Score per option |
alternatives | list[dict] | ➖ | Options not taken, with rationale |
rules_fired | list[str] | ➖ | Deterministic rules that applied |
Feeds the decision-trace engine.
record_sources(*, consulted, used=None, dropped=None, scores=None)
| Param | Type | Required | Description |
|---|---|---|---|
consulted | list[str] | ✅ | Every source retrieved — string IDs or URLs, not objects |
used | list[str] | ➖ | The subset actually cited. Drives source_authority. |
dropped | list[str] | ➖ | Retrieved and deliberately discarded |
scores | dict[str, float] | ➖ | Relevance per source, 0–1 |
Feeds the sources matrix. The
consulted vs used split is what surfaces "retrieved a good source and ignored
it".
record_cost(*, model, input_tokens, output_tokens, ...)
| Param | Type | Required | Default | Description |
|---|---|---|---|---|
model | str | ✅ | — | Model identifier |
input_tokens | int | ✅ | — | Prompt tokens |
output_tokens | int | ✅ | — | Completion tokens |
reasoning_tokens | int | ➖ | 0 | Extended-thinking tokens |
tool_call_count | int | ➖ | 0 | Tool invocations |
injected_context_tokens | int | ➖ | 0 | Tokens placed into context |
used_context_tokens | int | ➖ | 0 | Tokens the model actually drew on |
USD and the pricing version are computed for you. The
injected vs used context split powers context-optimization recommendations.
record_reliability_inputs(**kwargs)
Free-form signals for the reliability scorer.
record_plan(plan)
Records the agent's plan; feeds the decomposition engine.
record_end_user(end_user)
Sets evigauge.end_user after construction.
subnode(...)
Creates a nested node under the current one.
Cost estimation
from evigauge.trace import estimate_cost_usd, pricing_version
usd = estimate_cost_usd(model="claude-opus-4-6", input_tokens=2140, output_tokens=310)
print(f"${usd:.4f} (pricing {pricing_version()})")
Use this for local pre-flight estimates. Server-side cost on stored traces is computed independently, so a stored figure never shifts because your SDK version changed.
Enumerations
Both are server-validated — any other value fails validation and the span is dead-lettered.
reasoning_role — what the step is for:
decomposer · research · analysis · critique · synthesis · arbiter ·
retrieval · guardrail · post_process
node_type — what kind of component it is:
decomposer · classifier · agent · guardrail · post_process · retrieval
Projects and attribution
project_id is how a trace finds its home. Everything the dashboard shows is
scoped to a project: traces, cost, drift, evals, and the savings figures. Get
it wrong and the data still arrives, but not where anyone is looking.
The project has to exist first
Create the project in the dashboard before you send spans naming it. Settings → Projects, or ask a workspace admin.
A span naming a project that does not exist is not rejected. The backend
files it under the workspace's default project and records what you asked for
in requested_project_id. Nothing errors, nothing retries, and the trace is
perfectly readable. It is just filed somewhere you did not intend.
The dashboard surfaces this on the Observability screen, inside the default project, as a banner naming the project that does not exist. The team running the workspace will see it before you do, which is usually how this gets found:
Spans arrived for
checkout-v2, which doesn't exist — filed under Default.
Either create that project, or correct the project_id your service sends.
Historical traces keep the name they arrived with.
requested_project_idis stamped at ingest and never rewritten, so creating the project later fixes everything from that point on but does not move the traces already filed under the default. Create it first and you avoid the split entirely.
Getting a project's exact id, from the dashboard
You do not have to guess the slug or copy it out of a URL. Settings → Projects lists every project in the current workspace, and each row has a How to send data here link under its name.
Opening it reveals the lines for that specific project, with its id already filled in — nothing to substitute:
| Line | What it configures |
|---|---|
evigauge.trace.init(project_id="…") | The Python SDK |
x-evigauge-project-id: … | The OTLP header, for any OpenTelemetry exporter |
OTEL_RESOURCE_ATTRIBUTES+=",evigauge.project_id=…" | Claude Code telemetry |
Copy the one matching how your service reports. Because the snippet is generated from the project you opened it on, it cannot disagree with the slug the backend expects, which is the failure the rest of this section describes.
The same row also carries Export (download that project's spans as a CSV, streamed, with no size cap) and Clear (wipe its telemetry, keep the project).
Use the slug, not the display name
project_id matches the project's slug — lowercase, hyphenated, stable.
A project displayed as "Checkout Bot" has a slug like checkout-bot. Sending
the display name is the most common way to land in the default project.
One service, one project
The useful grain is a deployable unit, not a team or an environment:
evigauge.trace.init(
org_id="acme",
workspace_id="8f21c7a0-4d3b-11f0-9cd6-0242ac120002",
project_id="checkout-bot", # a service, not a squad
backend_url="https://ingest.evigauge.ai",
api_key=os.environ["EVIGAUGE_API_KEY"],
)
Separate environments belong in separate workspaces, not separate projects. A workspace carries its own API key, its own budgets and its own access rules, which is what keeps staging traffic out of production's numbers and out of production's bill.
Reading it back
Project scoping is automatic on the dashboard and explicit on the API: every
project-scoped read takes ?project=<slug>. A member restricted to one
project only ever sees that project's traces, so attribution is also an access
boundary, not only a grouping.
# Everything for one project, over the API.
traces = evigauge.get(f"{root}/traces", params={"project": "checkout-bot"})
If you got it wrong
- Create the project with the exact slug the spans are asking for, or
- Fix
project_idin the service and redeploy.
Either clears the banner for traces arriving afterwards. Already-filed traces stay in the default project; there is no backfill.
Span attribute reference
The wire contract. Violations are silently dead-lettered at ingest — the span disappears rather than erroring, so get these right.
Required envelope
| Attribute | Type | Description |
|---|---|---|
evigauge.schema_version | string | Currently "1.0" |
evigauge.org_id | string | Organization identifier |
evigauge.workspace_id | string | Workspace UUID |
evigauge.project_id | string | Project/service name |
evigauge.trace_id | string | Must equal the OTel trace ID |
Optional attributes
| Attribute | Type | Description |
|---|---|---|
evigauge.user_id | string | Internal user identifier |
evigauge.end_user | string | End-user identifier for per-user attribution |
evigauge.reasoning_role | enum | See above |
evigauge.node_type | enum | See above |
evigauge.parent_reasoning_id | string | Parent reasoning node |
evigauge.decision | JSON string | {rules_fired, scores, selected, alternatives} |
evigauge.sources | JSON string | {consulted, used, dropped, scores} |
evigauge.query_text | plain string | The user query / the prompt. ~64 KB cap. |
evigauge.outcome_text | plain string | The final answer. ~64 KB cap. |
evigauge.prompt_id | string | Pins prompt identity for Ship Check |
evigauge.prompt_label | string | Display name |
evigauge.prompt_version | string | Client-computed version |
evigauge.cost.usd | float | Flat scalar |
evigauge.cost.model_pricing_version | string | Pricing table version |
evigauge.vendor_id | string | Who runs this agent — see Vendor & cloud attribution below |
evigauge.vendor_role | enum | in_house · supplier · integrator · model_provider · cloud · unknown |
Standard OTel GenAI semantic conventions are also read: gen_ai.system,
gen_ai.request.model, gen_ai.operation.name, gen_ai.usage.input_tokens,
gen_ai.usage.output_tokens, gen_ai.response.finish_reason.
Captured-text cap (0.1.0a34+).
query_text/outcome_textare stored up to 64 KB each (raised from 16 KB) so a large model output — a generated HTML document, a long tool result — is retained in full instead of truncated mid-content. Tune it on the SDK withEVIGAUGE_TEXT_CAP_BYTES(bytes). The SDK also pins OpenTelemetry's span-attribute length limit to the same value, so a runtime that setsOTEL_ATTRIBUTE_VALUE_LENGTH_LIMITcan't silently clip captured text below the cap. On the direct-HTTP / native-OTLP routes you cap the text yourself — slice to the same 64 KB so what you send equals what is stored.
Vendor & cloud attribution
Fleet Monitor groups agents by who runs them — your own infrastructure, a cloud, or a supplier on their own stack — and flags failures that happen on a hand-off between two of them. That grouping is inferred from span attributes: Evigauge never holds your cloud credentials and never calls your cloud's control plane.
Most fleets need no code change. If your agents run the OpenTelemetry SDK with its standard
cloud resource detectors enabled, cloud.provider is already populated, so a fleet running in
AWS appears as the aws vendor automatically. A mixed AWS/Azure deployment appears as two
vendor buckets with the cross-cloud edges drawn between them.
Set the attributes below only when you need to say something the cloud detectors cannot — that an agent belongs to a named supplier, say, or to a specific internal team.
A vendor is a property of the deployment, not of one span, so the natural place for it is
the OpenTelemetry resource. This SDK is built on opentelemetry-sdk, so the standard env var
applies and needs no code change:
export OTEL_RESOURCE_ATTRIBUTES="evigauge.vendor_id=acme-billing,evigauge.vendor_role=supplier"
To set it in code instead, put it on the span like any other Evigauge attribute:
node._span.set_attribute("evigauge.vendor_id", "acme-billing")
node._span.set_attribute("evigauge.vendor_role", "supplier")
Both reach the same place: attribution is resolved per span at ingest, and resource attributes are merged onto every span the process exports.
If you cannot change the agent at all, a workspace admin can label it centrally with
priority-ordered regex rules against service.name / host.name / server.address and others.
See Vendor & cloud attribution in the REST API reference for the full resolution order, the
vendor-map rules, and how boundary faults are raised.
Note: this ships dark behind a per-deployment flag. Until it is enabled for your workspace the fleet routes still respond, but every agent lands in a single unattributed bucket — so attributes you set now are recorded and simply start grouping once it is on.
The four rules
- Compound fields are JSON strings.
evigauge.decisionandevigauge.sourcesmust bejson.dumps(...). A nested object becomes an OTLPkvlistValueand kills the whole span. consulted/used/droppedarestring[]— URLs or stable IDs, never{id, title}objects.query_text/outcome_textare plain strings. Neverjson.dumpsthem.- Only documented
evigauge.*keys exist (the schema isextra="forbid"). Any otherevigauge.*key kills the span. Note the keys are flat:evigauge.prompt_id, notevigauge.prompt.id.
Where to put text. Engines take the first non-empty
query_textand the last non-emptyoutcome_textin a trace. Put the query on the earliest span and the outcome on the latest.
On an LLM span,
query_textis the prompt — it is what Evigauge versions, evaluates, and measures a cacheable prefix from. When rendering messages into it, keep role boundaries:Python# ✅ Correct — role boundaries preserved query_text = "\n\n".join(f"{m['role']}:\n{m['content']}" for m in messages) # ❌ Wrong — no boundary, so every call hashes as its own "prompt" and the # Prompts page fills with thousands of one-call rows. query_text = " ".join(m["content"] for m in messages)
Durability
Write-ahead log
Spans are written to wal_path (default .evigauge-wal/spans.jsonl) before export.
If the process crashes, the next init() replays the WAL and logs how many
entries it recovered.
Replay happens before the span processor is constructed — required on
Windows, where renaming a file with an open handle raises PermissionError
(WinError 32).
Mount .evigauge-wal/ on a writable volume in containers. On a fully read-only
filesystem, point wal_path at a writable temp directory.
Sampling
evigauge.trace.init(..., sampler_rate=0.1) # 10% of traces
Sampling is per trace, not per span — a sampled trace keeps all its spans, so reconstruction still works. Sampling a fraction of spans would produce broken traces.
Complete Python example
"""Minimal end-to-end instrumented agent."""
import os
import evigauge.trace
from evigauge.trace import ReasoningTrace, observe
evigauge.trace.init(
org_id=os.environ["EVIGAUGE_ORG_ID"],
workspace_id=os.environ["EVIGAUGE_WORKSPACE_ID"],
project_id="checkout-agent",
backend_url="https://ingest.evigauge.ai",
api_key=os.environ["EVIGAUGE_API_KEY"],
transport="direct",
fail_open=os.environ.get("ENV") == "production",
)
@observe(reasoning_role="retrieval", node_type="retrieval")
def retrieve(query: str) -> list[str]:
return ["https://docs.internal/returns", "https://docs.internal/shipping"]
def handle(query: str, user_id: str) -> str:
# One ReasoningTrace per logical request = one trace.
with ReasoningTrace("handle_request", reasoning_role="synthesis",
node_type="agent", end_user=user_id) as node:
# Put the query on the EARLIEST span of the trace.
node._span.set_attribute("evigauge.query_text", query)
docs = retrieve(query)
node.record_decision(
selected="answer_from_kb",
scores={"answer_from_kb": 0.91, "escalate": 0.12},
rules_fired=["kb_hit"],
)
node.record_sources(consulted=docs, used=docs[:1], dropped=docs[1:])
answer = f"Returns are accepted within 30 days. ({len(docs)} sources)"
node.record_cost(model="claude-opus-4-6", input_tokens=2140, output_tokens=310)
# Put the outcome on the LATEST span of the trace.
node._span.set_attribute("evigauge.outcome_text", answer)
return answer
if __name__ == "__main__":
print(handle("Can I return this?", user_id="user_8412"))
Verifying a span landed
Run this after wiring up instrumentation. It emits one span and confirms it arrived — the definitive check that the whole path works.
"""verify_span.py — emit one span and confirm it landed."""
import os, time, uuid, httpx
import evigauge.trace
from evigauge.trace import ReasoningTrace
ORG = os.environ["EVIGAUGE_ORG"] # slug, for the read API
WS = os.environ["EVIGAUGE_WORKSPACE"] # slug, for the read API
WS_ID = os.environ["EVIGAUGE_WORKSPACE_ID"] # UUID, for the SDK
KEY = os.environ["EVIGAUGE_API_KEY"]
evigauge.trace.init(
org_id=ORG, workspace_id=WS_ID, project_id="verify",
backend_url="https://ingest.evigauge.ai", api_key=KEY, transport="direct",
)
marker = f"verify-{uuid.uuid4().hex[:8]}"
with ReasoningTrace("verify_span", reasoning_role="analysis", node_type="agent") as n:
n._span.set_attribute("evigauge.query_text", marker)
n.record_cost(model="claude-opus-4-6", input_tokens=10, output_tokens=5)
# Force the batch out, then let ingestion settle.
from opentelemetry import trace as ot
ot.get_tracer_provider().force_flush()
print(f"emitted {marker}; waiting for ingestion…")
time.sleep(20)
# 1. Did anything dead-letter?
health = httpx.get(
f"https://api.evigauge.ai/v1/observ/orgs/{ORG}/workspaces/{WS}/health/ingestion",
headers={"x-evigauge-api-key": KEY}, timeout=30,
).json()
print("dead-lettered last hour:", health.get("dead_letter_count_last_hour"))
# 2. Is the trace queryable?
traces = httpx.get(
f"https://api.evigauge.ai/v1/observ/orgs/{ORG}/workspaces/{WS}/traces",
headers={"x-evigauge-api-key": KEY},
params={"page_size": 20, "include_empty": True}, timeout=30,
).json()
# Payload is under "data", not "items".
print("recent traces:", len(traces["data"]))
assert traces["data"], "No traces — check key, workspace UUID, and ingest URL."
print("✅ span landed")
If nothing lands, work through this in order:
| Check | How |
|---|---|
| Key valid and pointed at the right workspace? | GET https://ingest.evigauge.ai/v1/auth/whoami |
| Spans arriving at all? | spans_last_hour on ingestion health |
| Arriving but rejected? | dead_letter_count_last_hour > 0 → an attribute breaks the four rules |
| Using a collector? | Its otlphttp exporter must set encoding: json — protobuf returns 415 |
| Process exiting immediately? | Call force_flush() before exit, or spans die in the batch queue |