Metadata-Version: 2.4
Name: openai-agents-neomundi
Version: 0.1.1
Summary: Measure every model call an OpenAI Agents SDK run makes with the NeoMundi measurement API
Author-email: Sebastien FAVRE <sebastien@neomundi.org>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/neomundi-io/neomundi-integrations/tree/main/integrations/openai-agents
Project-URL: Repository, https://github.com/neomundi-io/neomundi-integrations
Project-URL: Documentation, https://github.com/neomundi-io/neomundi-integrations/tree/main/integrations/openai-agents#readme
Project-URL: Changelog, https://github.com/neomundi-io/neomundi-integrations/blob/main/integrations/openai-agents/CHANGELOG.md
Project-URL: Issues, https://github.com/neomundi-io/neomundi-integrations/issues
Keywords: openai-agents,agents,neomundi,ai-governance,llm-measurement,tracing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: openai-agents<0.27,>=0.26.0
Requires-Dist: neomundi<3.0,>=2.1.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Provides-Extra: examples
Provides-Extra: notebook
Requires-Dist: nbformat>=5.9; extra == "notebook"
Requires-Dist: nbclient>=0.9; extra == "notebook"
Requires-Dist: ipykernel>=6.29; extra == "notebook"

<div align="center">

[![English](https://img.shields.io/badge/EN-English-2563eb?style=flat-square)](README.md) · [![Français](https://img.shields.io/badge/FR-Fran%C3%A7ais-6b7280?style=flat-square)](README_FR.md)

# OpenAI Agents SDK × NeoMundi

> 🟢 **New here? Start with [Getting Started — From Integration to Verifiable Evidence](https://github.com/neomundi-io/neomundi-integrations/blob/main/GETTING_STARTED.md).** It is the **single source of truth** for the whole path: exact versions, executable commands, measured outputs, the common errors — and 🔴 **which steps are still blocked, and why**.

**Measure every model call your agent loop makes, including the call that decides on a tool and the call that reads its result. One trace processor next to the ones you already run, the latency the SDK recorded, and only token counts the provider published.**

**[Quickstart](#quickstart)** · **[What it refuses to do](#refusals)** · **[Notebook](notebooks/quickstart.ipynb)** · **[Limitations](LIMITATIONS.md)** · **[Cost](#what-it-costs)**

</div>

---

> **Evidence level: E2.** Four model calls of a real `Agent` run, through
> the real `Runner` on `OpenAIResponsesModel` against a local Ollama's
> `/v1/responses`, were measured on the service verification account on
> 2026-11-26 and re-read from the API as persisted: 4/4, served
> `measurement_version` 3.5.0, 0.12 CHF. A tool run produced two model
> calls and both were measured. Proof: [`evidence/e2_qualification_20261126T140137Z.json`](evidence/e2_qualification_20261126T140137Z.json). See
> [LIMITATIONS.md §9](LIMITATIONS.md#9-evidence-level-e2-on-the-responses-route).

## What this is

`NeoMundiTraceProcessor` is an Agents SDK `TracingProcessor`. You install
it once, and it **appends** itself to the processors already registered.
For each model call on the Responses API (the SDK's default model class)
it takes three things. The token count comes from the provider's own
`Response` object. The latency is the span's `ended_at - started_at`, as
the SDK recorded it. The agent and the tools come from the agent loop. It
then submits to NeoMundi's `POST /v1/govern` through the `neomundi` SDK, on
a worker thread, so the agent never waits for it.

A tool-using run makes one model call per step, and each one is measured
separately. Tool executions, agent steps, turns and the run total are
reported by name and **not** measured: they are not model calls, or they
are sums of calls already measured.

## What it is not

- **Not a way to measure Chat Completions or LiteLLM agents.** Their spans carry a usage dict the SDK rebuilt. It is zero-filled when the provider is silent, and on the LiteLLM route we measured it carrying a local estimate (21/7/28) where the provider published nothing. These spans are refused ([LIMITATIONS §1](LIMITATIONS.md#1-chat-completions-and-litellm-spans-are-refused--by-design)).
- **Not a reader of exported traces.** `export()` drops the provider's `Response`. The measurement is only possible in-process, from a processor.
- **Not a measurement of tools.** A tool execution has no model and no token count, so it is named on the outcome, never billed.
- **Not a tracer, evaluator or truth checker.** Every submission is a billed measurement. NeoMundi verifies integrity and authenticity, not whether an answer was true.

## Install

```bash
pip install openai-agents-neomundi
```

Python ≥ 3.11. Depends on `openai-agents>=0.26.0,<0.27` (pinned to the
minor whose tracing surface was verified) and `neomundi>=2.1.0,<3.0`.


🔴 **`pip install` does not ship `examples/`, `notebooks/` or `evidence/`.** Measured on 2026-12-01 against the eight published wheels: each ships its package and its metadata, and **none** carries those directories. They live in the repository — [`integrations/openai-agents/`](https://github.com/neomundi-io/neomundi-integrations/tree/main/integrations/openai-agents) — so every path this page states relative to them is a repository path, not a file your install contains.
## Quickstart

⚠ **A wiring sketch, not a runnable program.** Its `await` is at module level, so pasted into a `.py` file it raises `SyntaxError: 'await' outside function` before anything else — put it in an `async def` and call it with `asyncio.run(...)`. It also assumes your own `agent` and `Runner`. **The block that runs as published is just below**, and the fuller example is [`examples/01_offline_agent.py`](https://github.com/neomundi-io/neomundi-integrations/blob/main/integrations/openai-agents/examples/01_offline_agent.py) — 🔴 **in the repository, not in the wheel.**

```python
from openai_agents_neomundi import NeoMundiTraceProcessor

processor = NeoMundiTraceProcessor(
    api_key=..., base_url="https://api.neomundi.io"
).install()  # add_trace_processor -- NEVER set_trace_processors

result = await Runner.run(agent, "What is the weather in Paris?")

processor.flush()  # submissions run off the agent's thread
for outcome in processor.outcomes:
    print(outcome.span_type, outcome.status, outcome.token_count, outcome.request_id)
```

### Runnable as published — no key, no provider, no network

🟢 **Needs nothing but `pip install openai-agents-neomundi`.** The model is the host's real `OpenAIResponsesModel`; only its HTTP transport is a stub, so the spans the processor reads are the ones the Agents SDK really writes.

🔴 **The three refusals are the point.** A turn span and a task span are sums of model calls already measured one by one, and an agent span is not a model call at all — each is refused **by name** rather than counted twice.

⚠ **On the Chat Completions route the count is refused**, as `not_submitted_unverified_token_count`: that route's span cannot be traced back to the provider's own payload. That is why this block uses the Responses route, which is the SDK's default.

```python
import asyncio

import httpx
from agents import Agent, OpenAIResponsesModel, Runner
from openai import AsyncOpenAI

from openai_agents_neomundi import NeoMundiTraceProcessor


def stub_provider() -> AsyncOpenAI:
    """No provider is called: the transport answers with a canned Responses reply."""

    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(
            200,
            json={
                "id": "resp_quickstart",
                "object": "response",
                "created_at": 1764300000,
                "model": "stub-model",
                "status": "completed",
                "output": [
                    {
                        "type": "message",
                        "id": "msg_1",
                        "role": "assistant",
                        "status": "completed",
                        "content": [{"type": "output_text", "text": "Paris.", "annotations": []}],
                    }
                ],
                "parallel_tool_calls": True,
                "tool_choice": "auto",
                "tools": [],
                # The counts a PROVIDER would have declared.
                "usage": {
                    "input_tokens": 11,
                    "input_tokens_details": {"cached_tokens": 0},
                    "output_tokens": 3,
                    "output_tokens_details": {"reasoning_tokens": 0},
                    "total_tokens": 14,
                },
            },
        )

    return AsyncOpenAI(
        api_key="not-a-real-key",
        base_url="https://provider.example.invalid/v1",
        max_retries=0,
        http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
    )


processor = NeoMundiTraceProcessor(submit=False).install()  # no key: nothing is sent

agent = Agent(
    name="quickstart-agent",
    instructions="Answer in one word.",
    model=OpenAIResponsesModel(model="stub-model", openai_client=stub_provider()),
)
result = asyncio.run(Runner.run(agent, "Capital of France?"))
processor.flush()  # submissions run off the agent's thread

print("final_output :", result.final_output)
for outcome in processor.outcomes:
    line = f"{outcome.span_type:<18} {outcome.status}"
    if outcome.token_count is not None:
        line += f" tokens={outcome.token_count} ({outcome.token_source})"
    print(line)
```

It prints exactly this:

```
final_output : Paris.
ResponseSpanData   not_submitted_local_only tokens=14 (provider_response_usage_total)
TurnSpanData       not_submitted_aggregate_span
AgentSpanData      not_submitted_not_a_model_call
TaskSpanData       not_submitted_aggregate_span
```

### Where a real key comes from

**Ask for one at <https://neomundi.io/contact-us/>** — verified reachable, and
the only route this page states. ⚠ It is **not** a claim that no other route
exists; it is the one we can point you to today.

🟢 **You do not need one to evaluate this package.** The offline test suite
needs no credential, and the evidence committed in `evidence/` can be checked
without an account.


🔴 **Do not use `set_trace_processors([processor])`.** It *replaces* the
list. That silently removes the SDK's own exporter to the OpenAI dashboard,
and any processor your application registered.

Free first: `NeoMundiTraceProcessor(submit=False)` needs no key, opens no
socket, and tells you which of your calls would be measured. Runnable,
offline: [`examples/01_offline_agent.py`](examples/01_offline_agent.py)
and the [notebook](notebooks/quickstart.ipynb).

Two lines, no key, and you see it happen: [`examples/03_the_count_you_see.py`](examples/03_the_count_you_see.py)
runs an agent whose provider publishes no usage — the run reports **0 tokens**,
and the processor refuses it, because a zero-filled dict is not a count.

## Refusals

Every span ends with an `Outcome` and an explicit status. Nothing is
submitted, and nothing is billed, when:

| Status | Why |
|---|---|
| `not_submitted_unverified_token_count` | a Chat Completions / LiteLLM generation span; the provider published no usage or a partial one; or `AnyLLMModel` is loaded, which rebuilds `Response` objects |
| `not_submitted_no_provider_response` | the run does not record sensitive data (`trace_include_sensitive_data=False`), so the span carries no provider object |
| `not_submitted_aggregate_span` | a turn or task span: a sum of calls already measured |
| `not_submitted_not_a_model_call` | a tool execution, an agent step, a handoff or a guardrail, named on the outcome |
| `not_submitted_unsupported_span` | speech, transcription, or an unknown span type |
| `not_submitted_application_error` | the model call failed, or the response did not complete |
| `not_submitted_no_latency` | the span has no usable start and end |
| `skipped_sampling` / `not_submitted_local_only` | `sample_rate` excluded it / `submit=False` |
| `not_submitted_queue_full` / `not_submitted_processor_closed` | dropped rather than blocking the agent / after `shutdown()` |
| `not_submitted_transport_error` | the API was unreachable, and your run was not affected |

No exception from this package reaches your agent. Outcomes carry no
prompt, response, tool input or output, or key. They carry only lengths,
names and identifiers. [`examples/02_refusals.py`](examples/02_refusals.py)
shows each refusal on a real run.

## What it costs

🔴 **Every submitted observation is a billed measurement** (0.030 CHF on
TIER_03). **An agent run is billed once per model call**: a run that calls
one tool makes two calls and costs two observations. `sample_rate`
(default `1.0`) is deterministic in the span id. **Kill switch:**
`processor.sample_rate = 0.0`, immediate. Installing a second processor
retires the first, so re-running a notebook cell does not bill twice.

## Honest status

| | |
|---|---|
| Offline test suite | 45 tests, green on Python 3.12 / Linux locally; CI runs 3.11–3.13 on Linux, macOS, Windows |
| Real execution | **E2**: 4 observations submitted to `https://api.neomundi.io`, 4/4 re-read as persisted (2026-11-26, Python 3.12, `neomundi` 2.1.0). See [`evidence/`](evidence/) |
| Maturity | beta |

Read [LIMITATIONS.md](LIMITATIONS.md) before drawing a conclusion from any score.

## License

Apache-2.0. See [LICENSE](../../LICENSE).
