agenttrafficcop 2.0.0__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/CHANGELOG.md +27 -0
  2. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/FEATURES.md +7 -0
  3. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/PKG-INFO +185 -9
  4. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/QUICKSTARTS.md +82 -7
  5. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/README.md +182 -8
  6. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/RUNTIME_FEATURES.md +78 -7
  7. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/__init__.py +4 -1
  8. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/accounting.py +5 -0
  9. agenttrafficcop-2.2.0/agenttrafficcop/cli.py +251 -0
  10. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/client.py +173 -0
  11. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/frameworks.py +66 -10
  12. agenttrafficcop-2.2.0/agenttrafficcop/langgraph.py +316 -0
  13. agenttrafficcop-2.2.0/agenttrafficcop/openai_gateway.py +200 -0
  14. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/runtime.py +113 -8
  15. agenttrafficcop-2.2.0/agenttrafficcop/tracing.py +188 -0
  16. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/PKG-INFO +185 -9
  17. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/SOURCES.txt +7 -0
  18. agenttrafficcop-2.2.0/agenttrafficcop.egg-info/entry_points.txt +2 -0
  19. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/requires.txt +3 -0
  20. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/pyproject.toml +5 -1
  21. agenttrafficcop-2.0.0/agenttrafficcop/langgraph.py +0 -145
  22. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/LICENSE +0 -0
  23. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/MANIFEST.in +0 -0
  24. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/autogen.py +0 -0
  25. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/embeddings.py +0 -0
  26. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/exceptions.py +0 -0
  27. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/local.py +0 -0
  28. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/models.py +0 -0
  29. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/normalization.py +0 -0
  30. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/outage.py +0 -0
  31. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/py.typed +0 -0
  32. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/recipes.py +0 -0
  33. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/recovery.py +0 -0
  34. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/replay.py +0 -0
  35. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/security.py +0 -0
  36. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop/semantic.py +0 -0
  37. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/dependency_links.txt +0 -0
  38. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/agenttrafficcop.egg-info/top_level.txt +0 -0
  39. {agenttrafficcop-2.0.0 → agenttrafficcop-2.2.0}/setup.cfg +0 -0
@@ -1,3 +1,30 @@
1
+ ## 2.2.0
2
+
3
+ - Publish the SDK LangGraph checkpointed-review adapter with a built-in,
4
+ read-only verifier for owner-scoped ATC approval status. Resume input must
5
+ carry the exact review ID; the action is rechecked by ATC immediately before
6
+ execution and the one-action grant is consumed by the server.
7
+ - Add a LangGraph-native first-run and deployment walkthrough with a supported
8
+ versioned container image and Helm defaults.
9
+
10
+ ## Unreleased
11
+
12
+ - Add Anthropic model-aware gateway input-token preflight with a clearly labeled
13
+ buffered-estimate fallback; estimates remain admission buffers, not invoice caps.
14
+ - Add a starter Kubernetes Helm chart and `atc doctor` deployment preflight.
15
+ - Add LangGraph checkpointed review interrupts with safe reasons, exact-action
16
+ approval verification and a fresh ATC check before resumed node execution.
17
+
18
+ ## 2.1.0
19
+
20
+ - Add optional OpenAI SDK helpers that route BYOK Chat Completions through the
21
+ ATC OpenAI/Groq gateway, attach run and operation headers, and reuse each
22
+ operation ID across the OpenAI SDK's internal retries. Persisted IDs can be
23
+ supplied explicitly for application-level recovery.
24
+ - Add a tested egress-locked Docker quickstart that pairs the helper with a
25
+ private agent network; direct provider egress remains blocked for that
26
+ container. The topology is opt-in and self-hosted, not universal interception.
27
+
1
28
  ## 2.0.0
2
29
 
3
30
  - Add SecurityGuard text wrappers for OpenAI/Anthropic, common PII/credential
@@ -241,6 +241,13 @@ REST:
241
241
  - `POST /v1/runs/{session_id}/reservations`
242
242
  - Body: `{"reservation_id":"operation-123","estimated_cost_usd":"0.20"}`
243
243
  - `GET /v1/runs/{session_id}/reservations?after=&limit=100`
244
+ - `GET /v1/runs/{session_id}/reservations/{reservation_id}` (single-operation status)
245
+
246
+ Use `guard.get_reservation(session_id, reservation_id)` (or `await` it) for a
247
+ read-only lookup of one operation's status, estimate and actual cost when settled.
248
+ It returns 404 if the ID is unknown for that key/run. A held result is not proof
249
+ that the provider did or did not execute the request; status inspection does not
250
+ retry or release it. Reconcile final usage through trusted signed reporting.
244
251
 
245
252
  Use a stable unique ID per logical operation. Same ID and estimate returns the
246
253
  existing hold with `duplicate=true`; changing the estimate returns 409. A settled
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: agenttrafficcop
3
- Version: 2.0.0
3
+ Version: 2.2.0
4
4
  Summary: Python SDK for AgentTrafficCop — local and hosted deterministic checks for agent workflows.
5
5
  Author: AgentTrafficCop
6
6
  License-Expression: MIT
@@ -24,6 +24,8 @@ Requires-Python: >=3.11
24
24
  Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: httpx<0.30.0,>=0.27.0
27
+ Provides-Extra: openai
28
+ Requires-Dist: openai<3.0,>=1.109.1; extra == "openai"
27
29
  Provides-Extra: autogen
28
30
  Requires-Dist: pyautogen==0.2.35; extra == "autogen"
29
31
  Provides-Extra: crewai
@@ -80,17 +82,63 @@ change. Unknown-cost exceptions retain holds; they are never settled as zero.
80
82
  Python **3.11+**:
81
83
 
82
84
  ```bash
83
- python -m pip install --upgrade 'agenttrafficcop==2.0.0'
85
+ python -m pip install --upgrade 'agenttrafficcop==2.2.0'
84
86
  python -c "from importlib.metadata import version; print(version('agenttrafficcop'))"
85
87
  ```
86
88
 
87
89
  Base dependency: `httpx>=0.27.0,<0.30.0`. Use a virtual environment; optional
88
90
  framework extras have their own requirements.
89
91
 
90
- ## Security, recovery, and shared semantic helpers (2.0.0)
92
+ ## Route OpenAI calls through ATC with BYOK
93
+
94
+ Install the optional OpenAI integration:
95
+
96
+ ```bash
97
+ python -m pip install 'agenttrafficcop[openai]'
98
+ ```
99
+
100
+ The adapter configures the OpenAI SDK to use the ATC gateway, sends the ATC key
101
+ as bearer authorization and your provider key separately as BYOK, and attaches
102
+ a run ID plus a unique operation ID to each Chat Completions request:
103
+
104
+ ```python
105
+ import os
106
+ from agenttrafficcop import openai_gateway_client
107
+
108
+ with openai_gateway_client(
109
+ atc_api_key=os.environ["ATC_API_KEY"],
110
+ provider_api_key=os.environ["OPENAI_API_KEY"], # your provider key; never give it to us
111
+ run_id="order-742", # set a budget for this run before calling the gateway
112
+ base_url=os.getenv("ATC_BASE_URL", "https://your-atc-host/v2"),
113
+ ) as client:
114
+ response = client.chat.completions.create(
115
+ model="your-configured-model",
116
+ messages=[{"role": "user", "content": "Summarize this report."}],
117
+ max_tokens=300,
118
+ )
119
+ ```
120
+
121
+ For async applications, create the client with `async_openai_gateway_client`
122
+ and use the returned client in `async with`. Set `provider="groq"` to route compatible OpenAI SDK calls to
123
+ the fixed Groq gateway route. The gateway currently supports text-only,
124
+ non-streaming Chat Completions for configured models; configure exact model
125
+ prices and an eligible run budget on ATC first. No prompts or completions are
126
+ added to trace telemetry.
127
+
128
+ The adapter adds one operation ID to each `create` call before handing it to
129
+ the OpenAI SDK, so its internal retries reuse that ID. For deduplication across application/process
130
+ restarts, pass your own persisted ID with
131
+ `extra_headers={"X-ATC-Operation-ID": durable_operation_id}`. Do not blindly
132
+ retry an ambiguous result with a new ID: it can trigger a second provider call.
133
+ This integration covers only requests made through this configured client; it
134
+ does not monkey-patch other clients or frameworks. A provider key is still
135
+ required for a live BYOK call, but mock tests and local setup validation need
136
+ no real provider key.
137
+
138
+ ## Security, recovery, and shared semantic helpers (2.1.0)
91
139
 
92
140
  These are explicit Python SDK helpers; none patches model or framework calls
93
- globally. They are included in the published 2.0.0 package.
141
+ globally. They are included in the 2.1.0 package.
94
142
 
95
143
  ```python
96
144
  from agenttrafficcop import SecurityGuard, RecoveryHooks
@@ -147,6 +195,84 @@ cost when completion is ambiguous. Never wrap side-effecting tools. The ONNX run
147
195
  optional dependencies; **model weights are not bundled or downloaded**—operators
148
196
  must supply and review compatible local ONNX/tokenizer files.
149
197
 
198
+ ## Opt-in run spans
199
+
200
+ Use `GuardSync.span(...)` or `Guard.span(...)` around a tool/model/agent operation to add a timed event to the matching run timeline in the ATC dashboard:
201
+
202
+ ```python
203
+ with guard.span(RUN_ID, "search_documents", kind="tool"):
204
+ results = search_documents(query)
205
+
206
+ # Async equivalent:
207
+ async with guard.span(RUN_ID, "summarize", kind="model"):
208
+ result = await summarize_async(text)
209
+ ```
210
+
211
+ Allowed kinds are `agent`, `tool`, `model`, `retrieval`, and `other`. Span names must be short safe labels. The SDK reports only the name, kind, parent/span IDs, duration, success/error status, and exception class; it never sends inputs, outputs, exception messages, or tracebacks. Reporting is best-effort and will not replace an application exception. This is explicit instrumentation—not automatic patching—so wrap only the operations you want to see. Completed spans appear in the run timeline; calls or work not wrapped by the SDK remain invisible. The timed-span and registration-hook helpers are included in SDK 2.1.0.
212
+
213
+ The registration-time `guard_functions`, `guard_autogen_tools`,
214
+ `guard_crewai_tools`, and `guard_langgraph` helpers can wrap registered
215
+ functions/nodes in spans for you. Create the batch around the run, and pass it
216
+ when registering tools or graph nodes:
217
+
218
+ ```python
219
+ with guard.trace_batch(RUN_ID) as batch:
220
+ protected_tools = guard_functions(
221
+ runtime, tools, context=tool_context, trace_batch=batch,
222
+ )
223
+ agent = build_agent(protected_tools)
224
+ agent.run()
225
+ ```
226
+
227
+ Use an async batch with async functions; for mixed sync/async registrations,
228
+ pass `trace_batch={"sync": sync_batch, "async": async_batch}`. CrewAI exposes
229
+ both execution paths, so pass that mapping when tracing both. Only functions
230
+ registered through these explicit helpers are traced; nothing is monkey-patched.
231
+
232
+ To reduce requests for multi-step runs, use `trace_batch`; it sends up to 100 spans per HTTP request by default:
233
+
234
+ ```python
235
+ with guard.trace_batch(RUN_ID) as batch:
236
+ with batch.span("search_documents", kind="tool"):
237
+ results = search_documents(query)
238
+ with batch.span("summarize", kind="model"):
239
+ summary = summarize(results)
240
+ ```
241
+
242
+ Async code can use `async with guard.trace_batch(RUN_ID) as batch:` and
243
+ `async with batch.span(...)`. Batches flush at capacity and at scope exit, even
244
+ when the wrapped work raises. Flush is still awaited once per batch—not a
245
+ background queue—so reporting failure drops the batch but preserves the work's
246
+ result or exception.
247
+
248
+ ## Budgeted provider calls: fewer per-call plumbing arguments
249
+
250
+ These runtime provider-call helpers and the OpenAI gateway adapter are included
251
+ in SDK 2.1.0. The gateway adapter is the simplest BYOK path for supported
252
+ non-streaming Chat Completions; the runtime helpers provide separate local
253
+ reservation/accounting controls for explicitly wrapped provider calls.
254
+
255
+ For OpenAI Chat Completions or Anthropic Messages, bind the accountant and run
256
+ context once, then pass the provider's create callable and a durable operation
257
+ ID. Optional local estimate callback can be bound once too:
258
+
259
+ ```python
260
+ run = runtime.run(session_id=RUN_ID, sender="agent", recipient="openai",
261
+ accountant=accountant, estimate_cost=estimate_request)
262
+ response = run.openai_chat(client.chat.completions.create,
263
+ operation_id=PERSISTED_OPERATION_ID, model=MODEL,
264
+ messages=[{"role": "user", "content": "..."}], max_tokens=500)
265
+ ```
266
+
267
+ Use `await run.aopenai_chat(...)` for async calls. For Anthropic use
268
+ `run.anthropic_messages(...)` / `await run.aanthropic_messages(...)` with an
269
+ Anthropic `UsageAccountant`. Exact model prices and a trusted reporter are still
270
+ configured once by the application. The local estimator must use your own
271
+ pricing/tokenizer and return a positive estimate; it is not a provider hard cap.
272
+ Operation IDs remain explicit and durable. Calls are non-streaming; only a
273
+ hash-only action identity is sent by default. These methods do not intercept
274
+ other provider APIs or add provider SDK dependencies.
275
+
150
276
  ## New in 1.7.0: less setup, unchanged safety defaults
151
277
 
152
278
  - Bind session/routing/accounting once with `run = runtime.run(...)`, then use
@@ -526,14 +652,29 @@ Unreserved calls are not prevented. Actual costs above estimates are still
526
652
  recorded and can exceed the budget. `check()` does not reserve automatically.
527
653
 
528
654
  Budget reads include `reserved_spend_usd` and `available_to_reserve_usd`.
529
- `GET /v1/runs/{session_id}/reservations` supports `after` and `limit` pagination.
655
+ `GET /v1/runs/{session_id}/reservations` supports `after` and `limit`
656
+ pagination. To inspect one operation without loading a page, use
657
+ `guard.get_reservation(session_id, reservation_id)` or
658
+ `await guard.get_reservation(session_id, reservation_id)`. This read-only call
659
+ returns the reservation's `status`, estimate, actual cost (if settled), and
660
+ creation time; it returns 404 when the ID is not in that key/run. A `held` result
661
+ is not evidence the provider did or did not execute the request: do not retry the
662
+ provider call or release the hold based on status alone. Reconcile final cost
663
+ through the trusted signed usage-reporting path.
664
+
665
+ REST: `GET /v1/runs/{session_id}/reservations/{reservation_id}`. The SDK helper
666
+ is included in SDK 2.1.0; use this REST route with
667
+ the existing wheel, or use the pinned source-install instructions above for the
668
+ sync/async helper. No PyPI version change is required for the HTTP endpoint.
530
669
 
531
670
  ## Framework integrations
532
671
 
533
672
  ### LangGraph
534
673
 
674
+ Install the versioned SDK and the optional LangGraph extra:
675
+
535
676
  ```bash
536
- python -m pip install 'agenttrafficcop[langgraph]==2.0.0'
677
+ python -m pip install 'agenttrafficcop[langgraph]==2.2.0'
537
678
  ```
538
679
 
539
680
  ```python
@@ -549,13 +690,48 @@ graph.add_node("reviewer", guarded_node(
549
690
  ```
550
691
 
551
692
  Only wrapped nodes are protected. Keep exceptions propagating so failed checks
552
- stop execution. Adapters do not automatically enable normalization, hash-only,
553
- shadow mode or spending reservations. Use direct checks for unexposed options.
693
+ stop execution. To pause a circuit-breaker trip for a dashboard review, compile
694
+ with a **durable LangGraph checkpointer** (for example, a production
695
+ database-backed saver) and enable the built-in ATC verifier:
696
+
697
+ ```python
698
+ builder.add_node("reviewer", guarded_node(
699
+ reviewer_fn, guard=guard, sender="coder", recipient="reviewer",
700
+ session_id=lambda state: state["run_id"],
701
+ payload=lambda state: {"draft": state["draft"]},
702
+ review_on_trip=True,
703
+ ))
704
+ # durable_saver is your database-backed LangGraph checkpointer.
705
+ graph = builder.compile(checkpointer=durable_saver)
706
+ ```
707
+
708
+ When paused, show `__interrupt__[0].value` to the authorized operator and use
709
+ the dashboard's run-review flow to approve/reject the exact action. Resume with
710
+ `Command(resume={"review_id": event["review_id"]})`; the resume payload itself
711
+ is never authorization. The SDK queries ATC's owner-scoped review status, the
712
+ adapter checks that the state/action and review ID did not change, and ATC then
713
+ rechecks policy and consumes the one-action approval before the node runs. The
714
+ status API is read-only; only an authenticated dashboard owner can decide a
715
+ review. A custom `review_approval` callback is optional and must fail closed.
716
+
717
+ Run `python -I examples/langgraph_checkpointed_review.py` from the repository
718
+ after installing `./sdk[langgraph]` for an offline walkthrough; it uses fake ATC
719
+ and review services and an in-memory saver, so it is **not** a production setup.
720
+
721
+ A trip creates a checkpoint with only a generic review event, session ID,
722
+ opaque review ID and safe detector error code—never state, prompts, results or
723
+ exception text. On resume the verifier must approve that exact unchanged action;
724
+ only then does the node perform a fresh ATC check immediately before running. A
725
+ resume value by itself is never approval. Do not use an in-memory saver for
726
+ restart durability.
727
+ Approval does not bypass ATC spend/quota/policy controls. Adapters do not
728
+ automatically enable normalization, hash-only, shadow mode or spending
729
+ reservations. Use direct checks for unexposed options.
554
730
 
555
731
  ### Legacy AutoGen
556
732
 
557
733
  ```bash
558
- python -m pip install 'agenttrafficcop[autogen]==2.0.0'
734
+ python -m pip install 'agenttrafficcop[autogen]==2.2.0'
559
735
  ```
560
736
 
561
737
  This legacy adapter supports only `pyautogen==0.2.35`, not AgentChat or AG2.
@@ -1,10 +1,49 @@
1
- # Short integration recipes — SDK 2.0
1
+ # Short integration recipes — SDK 2.1
2
+
3
+ Install the SDK and the optional OpenAI adapter with
4
+ `python -m pip install 'agenttrafficcop[openai]==2.2.0'`. For editable
5
+ development, clone this repository and run
6
+ `python -m pip install -e './sdk[openai]'`
7
+ from its root.
2
8
 
3
9
  These protect only explicitly wrapped actions. Imports, credentials and existing
4
10
  framework objects are prerequisites, not invisible automatic configuration.
5
11
  Default checks fail closed. These framework recipes provide deterministic action
6
12
  checks, NOT automatic reserved execution/accounting of internal model calls.
7
13
 
14
+ ## BYOK model gateway: route OpenAI calls through ATC
15
+
16
+ Set an eligible run budget and exact model price in ATC first. Provide the ATC
17
+ API key and your own provider key as environment secrets; the helper sends the
18
+ ATC key as bearer authorization and the provider key in its gateway-specific
19
+ header. You do not need to expose either key in source code:
20
+
21
+ ```python
22
+ import os
23
+ from agenttrafficcop import openai_gateway_client
24
+
25
+ with openai_gateway_client(
26
+ atc_api_key=os.environ["ATC_API_KEY"],
27
+ provider_api_key=os.environ["OPENAI_API_KEY"],
28
+ run_id=os.environ["ATC_RUN_ID"],
29
+ base_url=os.environ["ATC_BASE_URL"], # e.g. https://your-atc-host/v2
30
+ ) as model:
31
+ answer = model.chat.completions.create(
32
+ model="your-configured-model",
33
+ messages=[{"role": "user", "content": "Hello"}],
34
+ max_tokens=200,
35
+ )
36
+ ```
37
+
38
+ The helper supplies run and per-call operation IDs, and SDK-internal retries
39
+ reuse the same operation ID. Pass a persisted `extra_headers={"X-ATC-Operation-ID": id}`
40
+ for application retries across process restarts. Pass `provider="groq"` to
41
+ route through Groq. The adapter supports only non-streaming OpenAI-compatible
42
+ Chat Completions for OpenAI or Groq; it does not support Anthropic. For direct
43
+ egress blocking, use the self-hosted Docker Compose instructions in
44
+ `../deploy/EGRESS_LOCKED.md`; enforcement is opt-in and does not apply to
45
+ arbitrary hosted agents.
46
+
8
47
  ## Three-line local evaluation: no account, Redis or network
9
48
 
10
49
  ```python
@@ -100,12 +139,48 @@ run = runtime.run(session_id=RUN_ID, sender='agent', recipient='model', accounta
100
139
  response = run.execute(call_provider, operation_id=PERSISTED_OPERATION_ID, estimated_cost_usd='0.02', payload={'task':'refund rules'})
101
140
  ```
102
141
 
103
- Use `await run.aexecute(...)` for async work. The wrapper checks, reserves, executes
104
- once, reports final known usage and settles unused estimate. It does not release
105
- unknown-cost holds on timeout, cancellation or arbitrary exceptions. Persist an
106
- operation ledger and failed cost reports; retry the report, NEVER the action.
107
- A dedicated context manager would still need explicit response capture and would
108
- not safely make unknown usage known; execute/aexecute is the single default path.
142
+ For OpenAI Chat Completions and Anthropic Messages, the run-bound convenience
143
+ methods remove the per-call accountant/context/kwargs plumbing:
144
+
145
+ ```python
146
+ # Exact model prices and trusted reporter are configured once in accountant.
147
+ run = runtime.run(
148
+ session_id=RUN_ID, sender='agent', recipient='openai', accountant=accountant,
149
+ estimate_cost=estimate_request, # Your local conservative estimator; see caveat below.
150
+ )
151
+ response = run.openai_chat(
152
+ client.chat.completions.create, operation_id=PERSISTED_OPERATION_ID,
153
+ model='your-exact-model', messages=[{'role':'user','content':'...'}],
154
+ max_tokens=500,
155
+ )
156
+ # Or: response = await run.aopenai_chat(async_create, ...)
157
+ ```
158
+
159
+ For Anthropic use `run.anthropic_messages(client.messages.create, ...)` or
160
+ `await run.aanthropic_messages(async_create, ...)`, with an Anthropic
161
+ `UsageAccountant` and the named `system`/`messages`/`model` arguments. These
162
+ helpers accept the provider's normal non-streaming create callable; no provider
163
+ SDK dependency is added. They do not wrap Responses API, tools, streams, or
164
+ arbitrary provider methods. The returned provider response is unchanged.
165
+
166
+ `estimate_cost(request, provider=..., operation_id=...)` runs locally before
167
+ hosted check/reservation and must return a positive USD estimate. Build it using
168
+ your own tokenizer/prices and a conservative output allowance; do not infer
169
+ pricing from model names or response metadata. The estimate is not a provider
170
+ hard cap and can be wrong. Alternatively pass `estimated_cost_usd` on each
171
+ shortcut call. Stable operation IDs remain application-supplied and must be
172
+ persisted; a duplicate reservation never authorizes another execution. The
173
+ shortcuts hash the full provider request by default, rather than transmitting
174
+ prompt contents, and reject streaming. Raw-payload mode is an explicit privacy
175
+ choice: construct `GuardRuntime(..., normalize_volatile_metadata=False)` and
176
+ then use `run(hash_only=False)`. Hashes are not encryption or anonymization.
177
+
178
+ The wrapper checks, reserves, executes once, reports final known usage and
179
+ settles unused estimate. It does not release unknown-cost holds on timeout,
180
+ cancellation or arbitrary exceptions. Persist an operation ledger and failed
181
+ cost reports; retry the report, NEVER the action. These conveniences still
182
+ require hosted Pro/Team budget configuration, exact model prices, trusted
183
+ reporting credentials, and provider-client setup.
109
184
 
110
185
  ## Common-wrapper accounting
111
186
 
@@ -33,17 +33,63 @@ change. Unknown-cost exceptions retain holds; they are never settled as zero.
33
33
  Python **3.11+**:
34
34
 
35
35
  ```bash
36
- python -m pip install --upgrade 'agenttrafficcop==2.0.0'
36
+ python -m pip install --upgrade 'agenttrafficcop==2.2.0'
37
37
  python -c "from importlib.metadata import version; print(version('agenttrafficcop'))"
38
38
  ```
39
39
 
40
40
  Base dependency: `httpx>=0.27.0,<0.30.0`. Use a virtual environment; optional
41
41
  framework extras have their own requirements.
42
42
 
43
- ## Security, recovery, and shared semantic helpers (2.0.0)
43
+ ## Route OpenAI calls through ATC with BYOK
44
+
45
+ Install the optional OpenAI integration:
46
+
47
+ ```bash
48
+ python -m pip install 'agenttrafficcop[openai]'
49
+ ```
50
+
51
+ The adapter configures the OpenAI SDK to use the ATC gateway, sends the ATC key
52
+ as bearer authorization and your provider key separately as BYOK, and attaches
53
+ a run ID plus a unique operation ID to each Chat Completions request:
54
+
55
+ ```python
56
+ import os
57
+ from agenttrafficcop import openai_gateway_client
58
+
59
+ with openai_gateway_client(
60
+ atc_api_key=os.environ["ATC_API_KEY"],
61
+ provider_api_key=os.environ["OPENAI_API_KEY"], # your provider key; never give it to us
62
+ run_id="order-742", # set a budget for this run before calling the gateway
63
+ base_url=os.getenv("ATC_BASE_URL", "https://your-atc-host/v2"),
64
+ ) as client:
65
+ response = client.chat.completions.create(
66
+ model="your-configured-model",
67
+ messages=[{"role": "user", "content": "Summarize this report."}],
68
+ max_tokens=300,
69
+ )
70
+ ```
71
+
72
+ For async applications, create the client with `async_openai_gateway_client`
73
+ and use the returned client in `async with`. Set `provider="groq"` to route compatible OpenAI SDK calls to
74
+ the fixed Groq gateway route. The gateway currently supports text-only,
75
+ non-streaming Chat Completions for configured models; configure exact model
76
+ prices and an eligible run budget on ATC first. No prompts or completions are
77
+ added to trace telemetry.
78
+
79
+ The adapter adds one operation ID to each `create` call before handing it to
80
+ the OpenAI SDK, so its internal retries reuse that ID. For deduplication across application/process
81
+ restarts, pass your own persisted ID with
82
+ `extra_headers={"X-ATC-Operation-ID": durable_operation_id}`. Do not blindly
83
+ retry an ambiguous result with a new ID: it can trigger a second provider call.
84
+ This integration covers only requests made through this configured client; it
85
+ does not monkey-patch other clients or frameworks. A provider key is still
86
+ required for a live BYOK call, but mock tests and local setup validation need
87
+ no real provider key.
88
+
89
+ ## Security, recovery, and shared semantic helpers (2.1.0)
44
90
 
45
91
  These are explicit Python SDK helpers; none patches model or framework calls
46
- globally. They are included in the published 2.0.0 package.
92
+ globally. They are included in the 2.1.0 package.
47
93
 
48
94
  ```python
49
95
  from agenttrafficcop import SecurityGuard, RecoveryHooks
@@ -100,6 +146,84 @@ cost when completion is ambiguous. Never wrap side-effecting tools. The ONNX run
100
146
  optional dependencies; **model weights are not bundled or downloaded**—operators
101
147
  must supply and review compatible local ONNX/tokenizer files.
102
148
 
149
+ ## Opt-in run spans
150
+
151
+ Use `GuardSync.span(...)` or `Guard.span(...)` around a tool/model/agent operation to add a timed event to the matching run timeline in the ATC dashboard:
152
+
153
+ ```python
154
+ with guard.span(RUN_ID, "search_documents", kind="tool"):
155
+ results = search_documents(query)
156
+
157
+ # Async equivalent:
158
+ async with guard.span(RUN_ID, "summarize", kind="model"):
159
+ result = await summarize_async(text)
160
+ ```
161
+
162
+ Allowed kinds are `agent`, `tool`, `model`, `retrieval`, and `other`. Span names must be short safe labels. The SDK reports only the name, kind, parent/span IDs, duration, success/error status, and exception class; it never sends inputs, outputs, exception messages, or tracebacks. Reporting is best-effort and will not replace an application exception. This is explicit instrumentation—not automatic patching—so wrap only the operations you want to see. Completed spans appear in the run timeline; calls or work not wrapped by the SDK remain invisible. The timed-span and registration-hook helpers are included in SDK 2.1.0.
163
+
164
+ The registration-time `guard_functions`, `guard_autogen_tools`,
165
+ `guard_crewai_tools`, and `guard_langgraph` helpers can wrap registered
166
+ functions/nodes in spans for you. Create the batch around the run, and pass it
167
+ when registering tools or graph nodes:
168
+
169
+ ```python
170
+ with guard.trace_batch(RUN_ID) as batch:
171
+ protected_tools = guard_functions(
172
+ runtime, tools, context=tool_context, trace_batch=batch,
173
+ )
174
+ agent = build_agent(protected_tools)
175
+ agent.run()
176
+ ```
177
+
178
+ Use an async batch with async functions; for mixed sync/async registrations,
179
+ pass `trace_batch={"sync": sync_batch, "async": async_batch}`. CrewAI exposes
180
+ both execution paths, so pass that mapping when tracing both. Only functions
181
+ registered through these explicit helpers are traced; nothing is monkey-patched.
182
+
183
+ To reduce requests for multi-step runs, use `trace_batch`; it sends up to 100 spans per HTTP request by default:
184
+
185
+ ```python
186
+ with guard.trace_batch(RUN_ID) as batch:
187
+ with batch.span("search_documents", kind="tool"):
188
+ results = search_documents(query)
189
+ with batch.span("summarize", kind="model"):
190
+ summary = summarize(results)
191
+ ```
192
+
193
+ Async code can use `async with guard.trace_batch(RUN_ID) as batch:` and
194
+ `async with batch.span(...)`. Batches flush at capacity and at scope exit, even
195
+ when the wrapped work raises. Flush is still awaited once per batch—not a
196
+ background queue—so reporting failure drops the batch but preserves the work's
197
+ result or exception.
198
+
199
+ ## Budgeted provider calls: fewer per-call plumbing arguments
200
+
201
+ These runtime provider-call helpers and the OpenAI gateway adapter are included
202
+ in SDK 2.1.0. The gateway adapter is the simplest BYOK path for supported
203
+ non-streaming Chat Completions; the runtime helpers provide separate local
204
+ reservation/accounting controls for explicitly wrapped provider calls.
205
+
206
+ For OpenAI Chat Completions or Anthropic Messages, bind the accountant and run
207
+ context once, then pass the provider's create callable and a durable operation
208
+ ID. Optional local estimate callback can be bound once too:
209
+
210
+ ```python
211
+ run = runtime.run(session_id=RUN_ID, sender="agent", recipient="openai",
212
+ accountant=accountant, estimate_cost=estimate_request)
213
+ response = run.openai_chat(client.chat.completions.create,
214
+ operation_id=PERSISTED_OPERATION_ID, model=MODEL,
215
+ messages=[{"role": "user", "content": "..."}], max_tokens=500)
216
+ ```
217
+
218
+ Use `await run.aopenai_chat(...)` for async calls. For Anthropic use
219
+ `run.anthropic_messages(...)` / `await run.aanthropic_messages(...)` with an
220
+ Anthropic `UsageAccountant`. Exact model prices and a trusted reporter are still
221
+ configured once by the application. The local estimator must use your own
222
+ pricing/tokenizer and return a positive estimate; it is not a provider hard cap.
223
+ Operation IDs remain explicit and durable. Calls are non-streaming; only a
224
+ hash-only action identity is sent by default. These methods do not intercept
225
+ other provider APIs or add provider SDK dependencies.
226
+
103
227
  ## New in 1.7.0: less setup, unchanged safety defaults
104
228
 
105
229
  - Bind session/routing/accounting once with `run = runtime.run(...)`, then use
@@ -479,14 +603,29 @@ Unreserved calls are not prevented. Actual costs above estimates are still
479
603
  recorded and can exceed the budget. `check()` does not reserve automatically.
480
604
 
481
605
  Budget reads include `reserved_spend_usd` and `available_to_reserve_usd`.
482
- `GET /v1/runs/{session_id}/reservations` supports `after` and `limit` pagination.
606
+ `GET /v1/runs/{session_id}/reservations` supports `after` and `limit`
607
+ pagination. To inspect one operation without loading a page, use
608
+ `guard.get_reservation(session_id, reservation_id)` or
609
+ `await guard.get_reservation(session_id, reservation_id)`. This read-only call
610
+ returns the reservation's `status`, estimate, actual cost (if settled), and
611
+ creation time; it returns 404 when the ID is not in that key/run. A `held` result
612
+ is not evidence the provider did or did not execute the request: do not retry the
613
+ provider call or release the hold based on status alone. Reconcile final cost
614
+ through the trusted signed usage-reporting path.
615
+
616
+ REST: `GET /v1/runs/{session_id}/reservations/{reservation_id}`. The SDK helper
617
+ is included in SDK 2.1.0; use this REST route with
618
+ the existing wheel, or use the pinned source-install instructions above for the
619
+ sync/async helper. No PyPI version change is required for the HTTP endpoint.
483
620
 
484
621
  ## Framework integrations
485
622
 
486
623
  ### LangGraph
487
624
 
625
+ Install the versioned SDK and the optional LangGraph extra:
626
+
488
627
  ```bash
489
- python -m pip install 'agenttrafficcop[langgraph]==2.0.0'
628
+ python -m pip install 'agenttrafficcop[langgraph]==2.2.0'
490
629
  ```
491
630
 
492
631
  ```python
@@ -502,13 +641,48 @@ graph.add_node("reviewer", guarded_node(
502
641
  ```
503
642
 
504
643
  Only wrapped nodes are protected. Keep exceptions propagating so failed checks
505
- stop execution. Adapters do not automatically enable normalization, hash-only,
506
- shadow mode or spending reservations. Use direct checks for unexposed options.
644
+ stop execution. To pause a circuit-breaker trip for a dashboard review, compile
645
+ with a **durable LangGraph checkpointer** (for example, a production
646
+ database-backed saver) and enable the built-in ATC verifier:
647
+
648
+ ```python
649
+ builder.add_node("reviewer", guarded_node(
650
+ reviewer_fn, guard=guard, sender="coder", recipient="reviewer",
651
+ session_id=lambda state: state["run_id"],
652
+ payload=lambda state: {"draft": state["draft"]},
653
+ review_on_trip=True,
654
+ ))
655
+ # durable_saver is your database-backed LangGraph checkpointer.
656
+ graph = builder.compile(checkpointer=durable_saver)
657
+ ```
658
+
659
+ When paused, show `__interrupt__[0].value` to the authorized operator and use
660
+ the dashboard's run-review flow to approve/reject the exact action. Resume with
661
+ `Command(resume={"review_id": event["review_id"]})`; the resume payload itself
662
+ is never authorization. The SDK queries ATC's owner-scoped review status, the
663
+ adapter checks that the state/action and review ID did not change, and ATC then
664
+ rechecks policy and consumes the one-action approval before the node runs. The
665
+ status API is read-only; only an authenticated dashboard owner can decide a
666
+ review. A custom `review_approval` callback is optional and must fail closed.
667
+
668
+ Run `python -I examples/langgraph_checkpointed_review.py` from the repository
669
+ after installing `./sdk[langgraph]` for an offline walkthrough; it uses fake ATC
670
+ and review services and an in-memory saver, so it is **not** a production setup.
671
+
672
+ A trip creates a checkpoint with only a generic review event, session ID,
673
+ opaque review ID and safe detector error code—never state, prompts, results or
674
+ exception text. On resume the verifier must approve that exact unchanged action;
675
+ only then does the node perform a fresh ATC check immediately before running. A
676
+ resume value by itself is never approval. Do not use an in-memory saver for
677
+ restart durability.
678
+ Approval does not bypass ATC spend/quota/policy controls. Adapters do not
679
+ automatically enable normalization, hash-only, shadow mode or spending
680
+ reservations. Use direct checks for unexposed options.
507
681
 
508
682
  ### Legacy AutoGen
509
683
 
510
684
  ```bash
511
- python -m pip install 'agenttrafficcop[autogen]==2.0.0'
685
+ python -m pip install 'agenttrafficcop[autogen]==2.2.0'
512
686
  ```
513
687
 
514
688
  This legacy adapter supports only `pyautogen==0.2.35`, not AgentChat or AG2.