Metadata-Version: 2.5
Name: metrxbot
Version: 0.4.0
Summary: Metrx Python SDK: track LLM calls per agent and tie them to outcomes
Project-URL: Homepage, https://metrxbot.com
Project-URL: Repository, https://github.com/ckpark123/Metrx
Author-email: Metrx <eng@metrxbot.com>
License: MIT
Requires-Python: >=3.9
Requires-Dist: httpx>=0.24.0
Provides-Extra: all
Requires-Dist: anthropic>=0.20; extra == 'all'
Requires-Dist: openai>=1.0; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.20; extra == 'anthropic'
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: respx>=0.20; extra == 'dev'
Provides-Extra: openai
Requires-Dist: openai>=1.0; extra == 'openai'
Description-Content-Type: text/markdown

# metrxbot

Python SDK for [Metrx](https://metrxbot.com). It records every OpenAI and Anthropic call your agent makes, ties the calls to a task, and posts the task's outcome, so Metrx can grade the agent against its job.

## Quick Start

```bash
pip install "metrxbot[openai]>=0.4.0"
export METRX_API_KEY=sk_live_...   # Settings -> Security -> API Keys
```

```python
import os
from metrx import Metrx
from openai import OpenAI

m = Metrx(api_key=os.environ["METRX_API_KEY"], agent_key="refund-triage")
m.instrument()   # patches OpenAI/Anthropic CLASSES: clients you create before or after are tracked

client = OpenAI()
with m.task(task_id="ticket-4821") as t:   # any string id; non-UUID ids map to a deterministic UUIDv5 client-side
    reply = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Summarise ticket 4821"}],
    )
    t.set_outcome(success=True)
# short scripts flush at exit automatically; on serverless call m.flush()
```

After the block, `t.result.status` says what happened to the outcome:

| `status`                | Meaning                                                                                                           |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `"accepted"`            | Recorded against the task's LLM events.                                                                           |
| `"pending_correlation"` | Metrx answered 202 and parked the outcome until an event with this `task_id` arrives. It is **not** recorded yet. |
| `"failed"`              | The post failed; `t.result.error` says why. The block itself never raises because of Metrx.                       |

## Installation

The PyPI package is `metrxbot`; the import name is `metrx`:

```bash
pip install "metrxbot>=0.4.0"            # core
pip install "metrxbot[openai]>=0.4.0"    # + OpenAI
pip install "metrxbot[anthropic]>=0.4.0" # + Anthropic
pip install "metrxbot[all]>=0.4.0"       # both
```

## What `instrument()` covers

`m.instrument()` patches the provider classes once, for the whole process:

- OpenAI: `chat.completions.create` and `responses.create`, sync (`OpenAI`) and async (`AsyncOpenAI`), streamed or not.
- Anthropic: `messages.create`, sync and async, streamed or not.

It returns the providers it actually patched, e.g. `["openai", "anthropic"]`. Calling it twice, or together with `m.instrument_openai(client)`, never records a call twice.

**Streaming.** OpenAI only reports usage on a stream when the request sets `stream_options={"include_usage": True}`. When the client talks to `api.openai.com` and you did not set it, Metrx sets it and hides the extra usage-only chunk, so your loop sees the same chunks it would without Metrx. Other OpenAI-compatible servers are left alone and counted from whatever usage they send.

**Not covered yet:** Anthropic's `messages.stream()` helper and OpenAI's `with_streaming_response` (both bypass `create`'s normal return path).

**Opting out.** `m.instrument(anthropic=False)` skips a provider; `METRX_DISABLE_INSTRUMENTATION=1` makes `instrument()` patch nothing.

**Already using OpenTelemetry / OpenLLMetry?** If another instrumentor already wraps a method, Metrx leaves that method alone and logs a warning, because recording the same call twice would double the cost on your P&L. Send that instrumentor's spans to Metrx's OTLP endpoint instead, or turn it off. Calls made through the Metrx gateway (`*.metrxbot.com` base URL) are recorded by the gateway, so the SDK skips them too.

## Tasks and outcomes

`m.task(task_id=...)` accepts any string: a ticket number, a queue message id, a job id. Metrx stores task ids as UUIDs, so a string that is not already a UUID is mapped on the client to `uuid5(TASK_ID_NAMESPACE, task_id)`, with the fixed namespace `522984cb-f1f3-5643-933b-8ba17bed1467`. The same string always gives the same UUID; `metrx.task_uuid("ticket-4821")` returns it (`dd2360a2-2857-5a77-a33f-bc4b210bd589`), so another service that posts reviews or outcomes for the same ticket can compute the same id. Inside the block, `t.task_id` is the UUID and `t.external_id` is the string you passed. With no `task_id`, a random UUID is used.

On exit, the events queued inside the block are sent first, then the outcome is posted, so Metrx can match the two. If the block raises, a `success=False` outcome is posted with the error message in `metadata` (turn off with `auto_outcome_on_error=False`) and your exception is re-raised unchanged.

```python
with m.task(task_id=message.id) as t:
    answer = run_agent(message)
    t.set_outcome(success=answer.resolved, value_microcents=250_000, metadata={"queue": "refunds"})
if t.result and t.result.status != "accepted":
    log.info("outcome %s: %s", t.result.status, t.result.error)
```

## Serverless (Lambda, Cloud Run, Cloud Functions)

Events are sent in batches by a background thread, and whatever is still queued is flushed when the interpreter exits. Serverless runtimes freeze or kill the process without running exit hooks, so call `m.flush()` before each invocation returns:

```python
m = Metrx(agent_key="refund-triage")   # module scope, reused across invocations
m.instrument()

def handler(event, context):
    with m.task(task_id=event["ticket_id"]) as t:
        ...
        t.set_outcome(success=True)
    m.flush()
    return {"ok": True}
```

`m.flush(timeout=None)` returns `True` when nothing is left queued.

**Forking servers (Celery prefork, gunicorn `--preload`).** A `Metrx()` created before the fork works in each child: the sender thread restarts after `fork()`. A child that exits through `os._exit` skips the exit flush, so call `m.flush()` at the end of work done outside a `task()` block (a `task()` block already sends its events on exit). On macOS, a forked child that makes any HTTPS call through httpx can abort in the system proxy lookup; set `no_proxy` (for example `no_proxy=*`) for local prefork runs.

## Configuration

| Parameter        | Default                                       | Description                                                                                 |
| ---------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `api_key`        | `METRX_API_KEY`, then `METRXBOT_API_KEY`      | Your Metrx API key. `MetrxConfigError` if none is found.                                    |
| `agent_key`      | `METRX_AGENT_KEY`, then `"default"`           | The agent every event is attributed to. The agent is created on first use.                  |
| `base_url`       | `METRX_BASE_URL`, then `https://metrxbot.com` | API origin. Must be `https://` (plain `http://` only for localhost).                        |
| `flush_interval` | `5.0`                                         | Seconds between background sends.                                                           |
| `max_batch_size` | `50`                                          | Events per request (capped at the server's 100). A full batch wakes the sender immediately. |
| `flush_at_exit`  | `True`                                        | Flush queued events at interpreter exit (up to 2 seconds in total).                         |
| `debug`          | `False`                                       | Enable debug logging.                                                                       |

The SDK logs to the `metrx` logger. It warns when Metrx rejects events (the ingest response lists them) and when an outcome cannot be recorded; it never raises into your LLM calls.

Errors raised on purpose are typed: `MetrxConfigError` (a `ValueError`) for configuration, `MetrxAPIError` (a `RuntimeError`, with `.status_code` and `.body`) from the direct API helpers such as `submit_outcome`, `submit_review` and `set_job_contract`.

## Sessions

Group related LLM calls under a session:

```python
with m.session(session_id="user-123-conv-1"):
    response = client.chat.completions.create(...)
```

`session_id` is the run identity (v0): mark a long-running run by stamping the same `session_id` on all of its events.

`config_version` is a free-text event field attributing events to a configuration revision (prompt, model, pipeline). Metrx applies **no validation, parsing, or ordering** to it; any string is stored verbatim (an empty string is stored as null) and grouping is by exact string equality only. This SDK does not stamp it automatically yet; include it on directly-ingested events.

## Upgrading from 0.3.x

- `m.instrument()` now actually tracks your clients. In 0.3.x it patched a client the SDK created itself, so nothing you called was recorded unless you also used `instrument_openai(client)`. Both still work and never double-count.
- `task_id` strings that are not UUIDs are now mapped to a UUIDv5 instead of being dropped by the server.
- `agent_key` defaults to `"default"` instead of no agent.
- Events are flushed at exit; `shutdown()` is no longer required in short scripts.

See [CHANGELOG.md](CHANGELOG.md).

## License

MIT
