Skip to main content

optio

Know what your agents cost. Then pay less.
Cost, loop and quality signals in the OpenTelemetry GenAI vocabulary —
plus an opt-in optimizer that cuts the bill on traffic you already send.

CI PyPI Python License


Your agent framework tells you what happened. optio tells you what it cost, whether it was going in circles, and whether the answer was any good — as ordinary OTel span attributes, so every backend you already run can chart and alert on them.

It ships as two packages, and the split is deliberate:

Package Where it sits What it does
👁 optio beside the request Reads spans, writes signals. Never touches a request.
✂️ optio_optimize in the request path Caches, trims, marks prefixes. Opt-in, installed separately.

You can adopt either one alone.

Quickstart

Cut cost — wrap the client you already have

One line, either vendor, sync or async (the wrapper detects which):

from anthropic import Anthropic
from optio_optimize import wrap_anthropic_client

client = wrap_anthropic_client(Anthropic())

# Everything from here on is optimized. Your call sites do not change.
client.messages.create(
    model="claude-haiku-4-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "..."}],
)
from openai import OpenAI
from optio_optimize import wrap_openai_client

client = wrap_openai_client(OpenAI())
client.chat.completions.create(model="gpt-4o-mini", messages=[...])

The client is mutated and returned, so you keep the object you built with one method replaced. Async clients (AsyncAnthropic, AsyncOpenAI) work identically. Every parameter this package does not model — seed, top_p, metadata, extra_headers, tool calls, multimodal blocks — rides through untouched.

Only lossless stages run by default. Nothing that could change an answer is on unless you turn it on:

wrap_anthropic_client(Anthropic(), trim_history=False)  # tune individual stages

Want the numbers afterwards?

from optio_optimize import Optimizer

optimizer = Optimizer()
client = wrap_anthropic_client(Anthropic(), optimizer)
...
print("\n".join(optimizer.report.summary_lines("claude-haiku-4-5")))

Measure — instrument the agent

from optio import instrument

instrument(agent)  # spans now carry cost + behavior signals

That is the whole integration. optio reads the spans your framework already emits and writes numbers back onto them — it never sees or alters a request (ADR-001).

Scope a run and give it a budget:

from optio import meter, RunContext


@meter(budget="$0.50")
def run_agent(prompt: str) -> str: ...


with RunContext(budget="$0.50") as run:  # or scope it yourself
    ...  # spans emitted inside are governed

No framework? RunContext governs any code that emits GenAI spans — a raw SDK loop included.

Works with

Framework instrument Extra Guide
LangGraph auto-detected optio[langgraph] langgraph.md
OpenAI Agents SDK auto-detected optio[openai] openai-agents.md
CrewAI auto-detected optio[crewai] crewai.md
Claude Agent SDK auto-detected optio[claude] claude-agent-sdk.md
Anything else RunContext — integrations

An adapter does not make your framework emit GenAI spans — that is the ecosystem's job (OTel instrumentation, OpenInference, or your framework's own exporter). optio reads what they produce.

Install

pip install optio                # core: signals only, never touches a request
pip install "optio[langgraph]"   # + framework adapter
pip install "optio[optimize]"    # + optio_optimize: acts on the signals

Python 3.10 – 3.14, Linux/macOS/Windows. Installing optio alone never pulls the optimizer in, and an import-linter contract keeps it that way.

The signals

These attribute names are the integration contract — mirrored as constants in optio.semconv and asserted by contract tests. docs/signals.md is authoritative.

Signal Type Lane
gen_ai.run.actual_cost double (USD) cost
gen_ai.run.projected_cost double (USD) cost
gen_ai.run.budget_remaining double (USD) cost
gen_ai.run.cost_per_successful_task double (USD) cost × quality
gen_ai.run.loop_state enum string behavior
gen_ai.run.repeat_count int behavior
gen_ai.run.quality.groundedness double [0,1] quality (opt-in)
gen_ai.run.quality.task_success double [0,1] quality (opt-in)
gen_ai.run.success bool quality

Policies match the exact names, so they stay portable across backends:

deny if input.attributes["gen_ai.run.projected_cost"] > 0.50
deny if input.attributes["gen_ai.run.loop_state"] == "looping"

What it saves

Cost reduction, measured against live APIs, not simulated:

Workload gpt-4o-mini claude-sonnet-4-5
retry_storm 93.5% 97.8%
tool_loop 80.8% 93.7%
multi_turn_chat_long — 86.2%
mcp_agent — 84.0%
fan_out 68.2% 83.7%
multi_turn_chat 8.4% 82.2%
rag_queries 16.5% 76.2%

Those two columns differ by 10× on multi_turn_chat, and that gap is the point. OpenAI populates its prefix cache automatically, so the biggest lever — placing explicit cache breakpoints — has nothing to do there. Anthropic caches only what you mark, which is where marking correctly is worth 80%+ on ordinary conversation traffic.

Three Anthropic figures come with 100% byte-identical output, and two of them reduce zero tokens — prefix caching changes the rate tokens are billed at, not the volume. A tool that reports only "tokens saved" scores those at 0.0%.

Full method, dates and per-stage detail: docs/optimize-benchmarks.md.

How it decides what to claim

Every number here is measured, dated and re-runnable — and several exist because a measurement contradicted an earlier claim and the claim lost:

  • Stages ship off when the evidence says so. 14 of 24 optimizations are disabled by default, including one that measured a cost increase of 14.8%.
  • The riskiest stages were measured, then left off. All four answer-changing stages were run live and isolated on 2026-08-03 for $0.85 total, and all four stayed off. semantic_cache served a wrong answer to 6 of 7 adversarial near-duplicates on gpt-4o-mini and 7 of 8 on claude-haiku-4-5 — two vendors, same verdict.
  • Every run is kept. Live exchanges are recorded under docs/evidence/, so re-checking a published number costs nothing instead of costing money (ADR-039).
  • Corrections stay in the record. optimize-benchmarks.md rewrites itself in place when a live run contradicts a simulated one — it has, twice.

The reasoning behind each decision is in 50 ADRs.

Overhead

Published rather than promised — generated by the CI benchmark job, not written by hand.

Measure Result Budget
Per-step, cost + behavior lanes mean ~70 µs, p99 ~130 µs < 5 ms p99
Behavior classification at 10k steps ~40 µs → ~50 µs flat in run length
Classification vs window size 37 µs at 50, 38 µs at 1000 flat in window
Ledger snapshot, 10k open reservations ~100 µs O(1)-ish
Both lanes disabled ~18 µs p99 —
import optio ~158 ms cold < 500 ms

Roughly 40× inside budget. Measured on one developer machine with an in-memory store and no exporter attached; read them as an order of magnitude, not a promise for your hardware. The window-size row is a structural guarantee rather than a measurement — classification is O(1) in the window, so raising behavior_window_size to catch longer cycles costs memory but not latency. It used to cost both, at 370 µs per step (docs/testing.md).

Detector accuracy on the synthetic corpus, both CI-gated:

Measure Result
False positives — healthy runs flagged 0 / 1200 (0.000%)
Detection — pathological runs caught 600 / 600 (100.0%)

The detection rate is gated alongside the false-positive rate, because a zero false-positive rate is trivially achievable by never detecting anything.

Status

alpha (0.3.0). All three lanes work end to end and every signal in the contract is implemented, on 99% coverage with 100% on the ledger and the fail-open guard.

  • State is in-process only. store_backend="redis" is rejected at setup rather than silently ignored (ADR-005).
  • The signal names may still move. They are pinned to OTel GenAI semconv 1.37.0, which is itself marked Development-stability upstream (ADR-002).

1.0.0 waits for that vocabulary to stabilise — the reasoning and the three conditions are in ADR-046.

Public API

The top-level package, and nothing else (ADR-012):

from optio import instrument, meter, RunContext, current_run, Config, BudgetPolicy
from optio import __version__, GENAI_SEMCONV_VERSION
instrument attach to a framework object
meter decorator: scope a run, optionally with a budget
RunContext the same thing as a context manager
current_run the run in scope, or None
Config everything configurable, validated at setup
BudgetPolicy the limits a run is governed by
__version__, GENAI_SEMCONV_VERSION this release, and the semconv release it tracks

Plus optio.semconv, which holds the attribute names as constants.

From optio_optimize, the entry points are wrap_anthropic_client, wrap_openai_client, Optimizer, BatchOptimizer and OptimizeConfig.

optio.runtime, optio.lanes and friends are internal and may change without a major bump — if you need something from them, please open an issue rather than importing it. A test asserts every name above appears in this file, so an undocumented export cannot ship.

Docs

Signals contract every attribute, authoritative
Integrations per-framework setup guides
Behavior detection what the corpus does and does not model
Optimize benchmarks per-stage, per-workload, dated
Evidence recorded live runs behind the claims
Testing how the numbers above are produced
Runbooks when a signal does not show up
ADRs why every decision went the way it did
Contributing the gate you need to pass
Security reporting a vulnerability
Changelog what changed, and why

Development

pip install -e ".[dev]"
pytest                       # 2,253 tests
ruff check . && mypy         # lint + types
lint-imports                 # architecture boundaries

Contributions are welcome — CONTRIBUTING.md describes the gate, which is the same one CI runs.

License

Apache-2.0 — see LICENSE.

Metadata

Release files for optio 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for optio 0.3.0
File Size Uploaded Provenance Actions
optio-0.3.0.tar.gz 985.9 kB With provenance Details for optio-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for optio 0.3.0
File Interpreter ABI Platform Actions
optio-0.3.0-py3-none-any.whl Python 3 none any Details for optio-0.3.0-py3-none-any.whl

Total release size: 1.4 MB

Release files / optio-0.3.0.tar.gz

Download URL optio-0.3.0.tar.gz
Size 985.9 kB
Tags Source
SHA-256 checksum
How to use checksums
2493f42b4563c688f85b31e05887ef3fc5a9abf03c52e966db98305fbd397173
BLAKE2b-256 checksum
How to use checksums
43e89c3c6a7ade2626393295df531fd96f8c24f4670600c0ab0df2899cb9d21b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 3, 2026.

Transparency log

Release files / optio-0.3.0-py3-none-any.whl

Download URL optio-0.3.0-py3-none-any.whl
Size 375.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
31c52f90b1c65c2b6c08cafcdb12bf7a0bc4d428fd8135e494b5ba3900074391
BLAKE2b-256 checksum
How to use checksums
413370d691990f7faa54acc03e88178837fca59fa26e65fe8bf7be0fcc94b449
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 3, 2026.

Transparency log

Security for optio 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for optio-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 3, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page