DEVELOPER DOCS

SDK

Python SDK

On this page

Installation

Shell
pip install evigauge-trace

Optional extras

ExtraInstallPullsUse when
livepip install 'evigauge-trace[live]'richYou want the evigauge live terminal dashboard
shipcheckpip install 'evigauge-trace[shipcheck]'pyyamlYour Ship Check policy is YAML (JSON needs no extra)
litellmpip install 'evigauge-trace[litellm]'litellmYou route models through LiteLLM
openllmetrypip install 'evigauge-trace[openllmetry]'traceloop-sdkYou already use OpenLLMetry
adapters-langchainpip install 'evigauge-trace[adapters-langchain]'langchain-coreYou use LangChain
adapters-microsoftpip 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.

Python
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.

NameTypeRequiredDefaultDescription
org_idstr✅—Organization identifier
workspace_idstr✅—Workspace UUID the dashboard reads
project_idstr✅—Project slug the traces belong to. The project must already exist in the workspace — see Projects and attribution
backend_urlstr✅—Ingest base URL — https://ingest.evigauge.ai
api_keystr✅—Workspace API key (evg_live_…)
collector_endpointstr➖http://localhost:4317OTLP/gRPC collector. Used only when transport="collector"
wal_pathstr➖.evigauge-wal/spans.jsonlCrash-recovery write-ahead log
auto_instrumentbool➖TruePatch known LLM client methods automatically
fail_openbool➖FalseIf True, init failures log instead of raising
sampler_ratefloat➖1.0Fraction of traces sampled, 0.0–1.0
transportstr | None➖"collector""collector" or "direct" — see below

Choosing a transport

transport="direct"transport="collector" (default)
PathYour process → ingest.evigauge.ai over HTTP/JSONYour process → local collector (gRPC) → Evigauge
Needs a collectorNoYes
Uses collector_endpointNo — ignoredYes
Best forServerless, containers, quick startsExisting OTel infrastructure, local buffering, fan-out

Override without a code change:

Shell
export EVIGAUGE_TRANSPORT=direct

The explicit transport= argument always wins over the environment variable.

Collector users: your otlphttp exporter must set encoding: json. The protobuf default returns 415 from Evigauge ingest, and it fails silently from the collector's point of view — the single most common cause of "no spans arriving".

YAML
exporters:
  otlphttp:
    endpoint: https://ingest.evigauge.ai
    encoding: json                       # REQUIRED
    headers:
      x-evigauge-api-key: evg_live_xxxxxxxxxxxxxxxxxxxx

What init() does

  1. Stores config, reachable via get_config().
  2. Fetches the workspace capture_text flag from GET /v1/workspaces/{ws}/sdk-config. Fail-closed — if the lookup fails, capture_text is False and no text bodies are sent.
  3. Builds the exporter for the chosen transport.
  4. Replays any WAL from a previous crashed process, then installs DurableBatchSpanProcessor.
  5. 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

ValueBehaviour on init failure
False (default)Raises. Your process will not start mis-instrumented.
TrueLogs 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

Python
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",
)
Shell
# .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.

Python
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.

NameTypeRequiredDefaultDescription
reasoning_rolestr | None➖NoneWhat this step is for — see enums
node_typestr | None➖NoneWhat kind of component it is — see enums
end_userstr | None➖NoneEnd-user identifier for per-user attribution
namestr | 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.

Python
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

NameTypeRequiredDefaultDescription
namestr✅—Span name (positional)
domainstr | None➖NoneFree-form label. Not indexed — not queryable server-side.
reasoning_rolestr | None➖NoneSee enums
node_typestr | None➖NoneSee enums
end_userstr | None➖NoneEnd-user identifier

Node methods

record_decision(*, selected, scores=None, alternatives=None, rules_fired=None)

ParamTypeRequiredDescription
selectedstr✅The option chosen
scoresdict[str, float]➖Score per option
alternativeslist[dict]➖Options not taken, with rationale
rules_firedlist[str]➖Deterministic rules that applied

Feeds the decision-trace engine.

record_sources(*, consulted, used=None, dropped=None, scores=None)

ParamTypeRequiredDescription
consultedlist[str]✅Every source retrieved — string IDs or URLs, not objects
usedlist[str]➖The subset actually cited. Drives source_authority.
droppedlist[str]➖Retrieved and deliberately discarded
scoresdict[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, ...)

ParamTypeRequiredDefaultDescription
modelstr✅—Model identifier
input_tokensint✅—Prompt tokens
output_tokensint✅—Completion tokens
reasoning_tokensint➖0Extended-thinking tokens
tool_call_countint➖0Tool invocations
injected_context_tokensint➖0Tokens placed into context
used_context_tokensint➖0Tokens 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

Python
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_id is 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:

LineWhat 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:

Python
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.

Python
# Everything for one project, over the API.
traces = evigauge.get(f"{root}/traces", params={"project": "checkout-bot"})

If you got it wrong

  1. Create the project with the exact slug the spans are asking for, or
  2. Fix project_id in 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

AttributeTypeDescription
evigauge.schema_versionstringCurrently "1.0"
evigauge.org_idstringOrganization identifier
evigauge.workspace_idstringWorkspace UUID
evigauge.project_idstringProject/service name
evigauge.trace_idstringMust equal the OTel trace ID

Optional attributes

AttributeTypeDescription
evigauge.user_idstringInternal user identifier
evigauge.end_userstringEnd-user identifier for per-user attribution
evigauge.reasoning_roleenumSee above
evigauge.node_typeenumSee above
evigauge.parent_reasoning_idstringParent reasoning node
evigauge.decisionJSON string{rules_fired, scores, selected, alternatives}
evigauge.sourcesJSON string{consulted, used, dropped, scores}
evigauge.query_textplain stringThe user query / the prompt. ~64 KB cap.
evigauge.outcome_textplain stringThe final answer. ~64 KB cap.
evigauge.prompt_idstringPins prompt identity for Ship Check
evigauge.prompt_labelstringDisplay name
evigauge.prompt_versionstringClient-computed version
evigauge.cost.usdfloatFlat scalar
evigauge.cost.model_pricing_versionstringPricing table version
evigauge.vendor_idstringWho runs this agent — see Vendor & cloud attribution below
evigauge.vendor_roleenumin_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_text are 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 with EVIGAUGE_TEXT_CAP_BYTES (bytes). The SDK also pins OpenTelemetry's span-attribute length limit to the same value, so a runtime that sets OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT can'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:

Shell
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:

Python
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

  1. Compound fields are JSON strings. evigauge.decision and evigauge.sources must be json.dumps(...). A nested object becomes an OTLP kvlistValue and kills the whole span.
  2. consulted / used / dropped are string[] — URLs or stable IDs, never {id, title} objects.
  3. query_text / outcome_text are plain strings. Never json.dumps them.
  4. Only documented evigauge.* keys exist (the schema is extra="forbid"). Any other evigauge.* key kills the span. Note the keys are flat: evigauge.prompt_id, not evigauge.prompt.id.

Where to put text. Engines take the first non-empty query_text and the last non-empty outcome_text in a trace. Put the query on the earliest span and the outcome on the latest.

On an LLM span, query_text is 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

Python
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

Python
"""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.

Python
"""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:

CheckHow
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