Metadata-Version: 2.3
Name: etaoi
Version: 0.4.1
Summary: ETAOI Flow SDK — agent-native tracing for LangChain / LangGraph / deepagents and LiveKit voice agents
Keywords: langchain,langgraph,deepagents,tracing,observability,agents
Author: ETAOI contributors
License: MIT
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: etaoi-schema>=0.5.2,<1
Requires-Dist: langchain-core>=1.0,<2
Requires-Dist: anyio>=4
Requires-Dist: msgpack>=1.1.2
Requires-Dist: tenacity>=9
Requires-Dist: websockets>=13,<17
Requires-Dist: fastapi>=0.100 ; extra == 'fastapi'
Requires-Dist: livekit-agents>=1.2,<2 ; extra == 'livekit'
Requires-Dist: opentelemetry-sdk>=1.20 ; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.20 ; extra == 'otel-export'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20 ; extra == 'otel-export'
Requires-Dist: deepagents>=0.6.1,<0.7 ; extra == 'test'
Requires-Dist: langgraph>=1.1.0,<2 ; extra == 'test'
Requires-Dist: pytest>=8 ; extra == 'test'
Requires-Dist: pytest-asyncio>=0.24 ; extra == 'test'
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/etaoi/etaoi
Project-URL: Repository, https://github.com/etaoi/etaoi
Provides-Extra: fastapi
Provides-Extra: livekit
Provides-Extra: otel
Provides-Extra: otel-export
Provides-Extra: test
Description-Content-Type: text/markdown

# etaoi

The Python SDK for **ETAOI Flow** — an agent-native trace visualizer for the
LangChain ecosystem and LiveKit voice agents. Attach it to your agent, run a
conversation, and watch the full reasoning unfold as a navigable, drill-down
node graph.

```bash
pip install etaoi             # core SDK
pip install "etaoi[livekit]"  # + LiveKit voice agent tap
```

Every function, its arguments, return value and an example are in the
[SDK reference](../../docs/reference/sdk.md), along with every environment
variable. Runnable recipes live in [`examples/cookbook/`](../../examples/cookbook/).

## 30-second quickstart

Start the server (`docker compose up`), then turn tracing on with env vars only:

```bash
export ETAOI_TRACING=true                    # `import etaoi` turns tracing on
export ETAOI_AUTO_INSTRUMENT=openai,anthropic   # optional: trace every client
python my_app.py                             # my_app.py does `import etaoi`
```

Or call it in code:

```python
import etaoi

etaoi.init()   # process-wide; reads ETAOI_* env vars; kwargs win over env
```

`etaoi.init()` is a global-mode `attach()`. It traces every LangChain runnable,
`@etaoi.trace` and (with `instrument=["openai", "anthropic"]` or
`ETAOI_AUTO_INSTRUMENT`) every OpenAI / Anthropic client of an installed SDK.
It is idempotent: later calls return the same handle. It never raises. With
`ETAOI_DISABLED=1` it is a no-op. If the server is unreachable, events are
dropped from a bounded queue and your app keeps running. Exit does not wait on
reconnect backoff: when the server is unreachable, detach and atexit return at
once. A connected sender gets a few seconds for its final flush.

| Env var | Meaning |
|---|---|
| `ETAOI_TRACING` | `true` / `1` / `yes`: `import etaoi` calls `etaoi.init()` |
| `ETAOI_HOST`, `ETAOI_PUBLIC_KEY`, `ETAOI_SECRET_KEY` | where to send (see Cloud below) |
| `ETAOI_ENVIRONMENT`, `ETAOI_RELEASE` | labels stamped on every span |
| `ETAOI_SAMPLE_RATE` | fraction of traces kept, `0`..`1` (default `1`) |
| `ETAOI_CAPTURE_IO` | `false`: send no inputs / outputs |
| `ETAOI_CAPTURE_TRACEBACK` | `true`: add a masked, size-capped traceback to failed spans |
| `ETAOI_AUTO_INSTRUMENT` | providers `init()` patches, e.g. `openai,anthropic` (also `gemini`, `litellm`); unset: none |
| `ETAOI_LOG_LEVEL` | `debug` / `info` / `warning` (default) / `error`, for the `etaoi` logger only |
| `ETAOI_DISABLED` | `1`: everything is a no-op |

All variables, including LiveKit and transport ones, are listed in the
[reference](../../docs/reference/sdk.md#environment-variables).

## Health: flush, status and warnings

```python
etaoi.flush(timeout=5.0)   # True once queued events are sent; does not detach
etaoi.status()             # also handle.status()
# {"connected": True, "server_url": "ws://127.0.0.1:8787/ingest", "last_error": None,
#  "sent": 120, "dropped": 0, "held": 0, "queued": 0}
```

`dropped` counts events lost to queue overflow. `held` counts events buffered
for unsampled traces, and `queued` counts events waiting to be sent. `flush()`
also closes `etaoi.start_span` spans that were never ended. It returns `False`
on timeout, and returns at once when the server is unreachable or rejected
the credentials.

The SDK logs one WARNING per problem per handle, with the fix in the message.
The problems are: server unreachable (try `etaoi doctor`), credentials
rejected (`4401`, set `ETAOI_SECRET_KEY` / the server's `ETAOI_ACCESS_TOKEN`),
schema mismatch (`4400`, upgrade the SDK or the server), rate limited
(`4429`) and queue full. After that warning, queue-full drops are only counted
in `status()`. Set `ETAOI_LOG_LEVEL=debug` to log every emitted span (name,
kind, ids) and connection events.

## Labels: environment, release, tags, metadata

```python
etaoi.init(environment="prod", release="2026.11.1", tags=["checkout"],
           metadata={"region": "eu"})          # also on attach(...)

agent.invoke(inputs, config={"tags": ["exp-7"], "metadata": {"tenant": "acme"}})

@etaoi.trace(tags=["rag"], metadata={"stage": "rerank"})
def rerank(...): ...
```

Every span carries `metadata["environment"]` / `metadata["release"]` plus your
metadata. Tags, including LangChain run tags, go in the span's `tags` field.
Per-invoke and per-span values win over the `attach`/`init` defaults.

**Per request (web apps: one process, many users).** In sync or async code:

```python
with etaoi.context(user_id=user.id, session_id=conversation_id,
                   tags=["api"], metadata={"tenant": "acme"}):
    agent.invoke(inputs)
```

Every span and LangChain run started inside the block carries these labels.
`user_id` and `session_id` replace the `attach`/`init` defaults for root
traces started in the block. `environment` / `release` are accepted too.
Nested contexts merge, and the inner one wins. Concurrent requests do not
leak into each other, because the context is a contextvar.

## Sampling

```python
etaoi.init(sample_rate=0.1)   # or ETAOI_SAMPLE_RATE=0.1
```

The keep-or-drop decision is made per trace and is deterministic by trace_id,
so a trace is always kept or dropped whole. **A trace that ends in an error or
a LangGraph interrupt is always kept.** Unsampled traces are buffered until
their root span closes and dropped only if they were clean. The buffer is
bounded: on overflow, the oldest buffered traces are dropped. The
`agent_context` snapshot and feedback scores are never sampled out.

## Masking and I/O capture

```python
import json, re

def mask(payload: dict) -> dict:   # values can be nested (e.g. input_messages)
    return json.loads(re.sub(r"\d{3}-\d{2}-\d{4}", "<ssn>", json.dumps(payload, default=str)))

etaoi.init(mask=mask)        # applied to every span payload before it leaves the process

@etaoi.trace(capture_inputs=False)     # arguments never sent
def login(password: str): ...

with etaoi.span("profile", capture_outputs=False):   # output never sent
    ...
```

`mask` gets each span's whole payload dict (inputs, outputs, messages) and
returns the dict to send. If it raises or returns a non-dict, the payload is
replaced by `{"masked": "[mask failed]"}`. Nothing unmasked is sent. Set
`ETAOI_CAPTURE_IO=false` (or `capture_io=False`) to send no I/O at all;
metadata, timing, model and token usage are still sent.

**Errors.** A failed span (`@trace`, `span`, or a LangChain `on_*_error`)
carries `error` (the masked message) and `error_type` (for example
`"ValueError"`). Its payload also gets `error_chain`, up to five
`"Type: message"` entries from `__cause__` / `__context__`, each one masked.
With `ETAOI_CAPTURE_TRACEBACK=true`, the payload also gets a masked
`error_traceback`, capped at 8 KB with the newest frames kept. With I/O
capture off, only exception types are sent: no messages and no traceback.

## Feedback

```python
etaoi.feedback("thumbs_up", True)                 # current span, inferred boolean
etaoi.feedback("rating", 4, comment="fast")       # numeric
etaoi.feedback("category", "wrong_tool")          # categorical
span.score("relevance", 0.8)                      # same, on a Span you hold
```

Called inside a trace, feedback targets the current span. In a web app, return
the ids to the client and send the feedback in a later request:

```python
s = etaoi.current_span()
ids = {"span_id": str(s.span_id), "trace_id": str(s.trace_id),
       "session_id": str(s.session_id)}
# … later, in the feedback endpoint:
etaoi.feedback("thumbs_up", False, span=ids["span_id"], trace_id=ids["trace_id"],
               session_id=ids["session_id"], comment="hallucinated a price")
```

Feedback is stored in the server's scores table with `source="user_feedback"`
(the same path as LiveKit `handle.score(...)`). `handle.session_id` gives the
default session id of an `attach`/`init` handle.

## Quick start — LangChain / LangGraph / deepagents

```python
import etaoi

etaoi.attach(my_agent)  # streams telemetry to a local ETAOI Flow server
# … now `my_agent.invoke(...)` shows up as a trace.
```

One callback adapter covers LangChain, LangGraph, and deepagents.

Call `etaoi.attach()` with **no agent** to trace process-wide. The handler is
then added to every LangChain runnable, including standalone models,
`with_config(...)` copies and runnables started in other threads. It is also
the handler for the tracing API below. `handle.detach()` undoes it.

Sessions: without an explicit `session_id`, each LangGraph
`configurable.thread_id` becomes its own session. A LangGraph `interrupt()`
ends its spans with `status="interrupted"`, not as an error.

## Tracing your own code

Anything outside LangChain callbacks can be a node too. Spans nest under the
current span, whether that span comes from a decorator, a LangChain tool or a
graph node. LangChain runs started inside a decorated function nest under it.

```python
import etaoi

@etaoi.trace                                  # sync, async, generators, async generators
def rerank(query: str, docs: list[str]) -> list[str]: ...

@etaoi.trace(name="fetch-context", kind="retriever")
async def fetch(query: str) -> list[str]: ...

with etaoi.span("load-profile", inputs={"user": uid}) as s:   # a block
    s.set_attribute("cache", "hit")           # -> metadata
    s.add_event("retry", attempt=2)           # -> payload["events"] (max 100)
    s.record_exception(handled_error)         # an "exception" event, masked
    s.set_output(profile)

job = etaoi.start_span("background-job", inputs=params)   # manual lifetime
job.end(output=result)                        # or end(error=exc); idempotent

etaoi.current_span()          # the current Span
etaoi.update_current_span(output=profile, metadata={"cache": "hit"})
```

`etaoi.span` and `etaoi.start_span` always return an `etaoi.Span`. A span
has `span_id`, `trace_id` and `session_id`, plus `set_output`,
`set_attribute`, `add_event`, `record_exception`, `score` and `end`. With
nothing attached (or no current span) it is a falsy no-op: the ids are
`None` and the methods do nothing. `start_span` opens a child of the current
span but does not make it current. Close it yourself; `etaoi.flush()` or
detach closes it otherwise.

Arguments, return value and exceptions are captured. `kind` is any `NodeKind`
and defaults to `"function"`. With no handler attached, every call above is a
zero-cost passthrough. The decorator keeps the function's exact signature
for IDEs and type checkers, and the package ships `py.typed`. The decorator
also accepts processors, which run before capture:

```python
@etaoi.trace(process_inputs=lambda args: {**args, "api_key": "***"},
             process_outputs=lambda out: out[:1000],
             reduce=lambda chunks: "".join(c.text for c in chunks))
def stream(prompt: str, api_key: str): ...
```

A generator's output is `reduce(chunks)`. By default, string chunks are
joined and anything else is recorded as the list of chunks (at most 10,000).
If a processor raises, the raw value is recorded and the error is logged
once at debug level.

**Distributed tracing.** Carry a trace across a service call:

```python
headers = etaoi.inject_headers({"content-type": "application/json"})
httpx.post(url, headers=headers)             # adds an `etaoi-trace` header

# in the called service:
with etaoi.continue_trace(request.headers):
    agent.invoke(inputs)                     # child of the caller's span
```

The header value is `<trace_id>:<span_id>:<session_id>`, as 32-character hex
UUIDs. Spans and LangChain runs started in the block join the caller's trace
and session. A missing or malformed header is ignored.

**Raw provider clients.** `wrap_openai` / `wrap_anthropic` patch a client so each
call becomes an `llm` span carrying the messages, response, normalized usage
and model. Streams are reduced into one response and get TTFT.

```python
client = etaoi.wrap_openai(openai.OpenAI())        # also AsyncOpenAI
claude = etaoi.wrap_anthropic(anthropic.Anthropic())
```

This covers `chat.completions.create` / `.parse` and `responses.create`
(OpenAI), and `messages.create` (Anthropic).

**Threads.** A bare `ThreadPoolExecutor` drops the current span. Use
`etaoi.ContextThreadPoolExecutor` (LangChain's, re-exported), which copies
the context into each task. `asyncio.gather` / `asyncio.to_thread` already
copy it.

## Quick start — LiveKit voice agents

```python
from livekit.agents import AgentSession
import etaoi

session = AgentSession(...)
etaoi.attach_session(session)
```

Captures voice turns (mic → STT → LLM → TTS → speaker), tool calls, sub-agent
handoffs, scores/outcomes, errors, and — if the host enabled LiveKit recording
— synced audio for replay alongside the trace.

## ETAOI Flow Cloud (project API keys)

To stream to the hosted ingest instead of a local self-host server, pass a
`host` plus your project's API keys:

```python
import etaoi

etaoi.attach(
    my_agent,
    host="ingest.etaoi.dev",         # bare host → wss://, default path /ingest
    public_key="pk_live_…",
    secret_key="sk_live_…",
)
```

Or via environment (explicit params take precedence):

```bash
export ETAOI_HOST=ingest.etaoi.dev
export ETAOI_PUBLIC_KEY=pk_live_…
export ETAOI_SECRET_KEY=sk_live_…
```

```python
etaoi.attach(my_agent)  # picks up ETAOI_HOST / ETAOI_PUBLIC_KEY / ETAOI_SECRET_KEY
```

The keys are sent as `X-Etaoi-Public-Key` / `X-Etaoi-Secret-Key` headers on
every (re)connect — and only when **both** are set, so self-host stays
key-less. If the server rejects them (WS close code `4401`), the SDK logs one
clear warning and stops reconnecting. It never raises into or blocks your agent.

## Design constraints

- **Never blocks your agent.** Async background flush via `anyio`, bounded
  in-memory queue with drop-oldest on overflow, transparent reconnect with
  backoff. All callbacks return immediately, and a bug inside a callback is
  swallowed, so your chain still returns normally.
- **Schema-versioned wire format.** MessagePack with `permessage-deflate` over
  WebSocket; schema version is negotiated at the handshake (MAJOR mismatch =
  fast fail, close code `4400`).
- **No vendor lock-in.** Self-host the server with `docker compose up`, or
  stream to ETAOI Flow Cloud. Same SDK.

For the wire schema this package depends on, see
[`etaoi-schema`](https://pypi.org/project/etaoi-schema/).

## Links

- SDK reference: [`docs/reference/sdk.md`](../../docs/reference/sdk.md)
- Source: <https://github.com/etaoi/etaoi>
- Changelog: see the project's `CHANGELOG.md` (per-version what's-new / what's-fixed)
- License: MIT
