agenttrafficcop 2.0.0__tar.gz → 2.1.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 (36) hide show
  1. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/CHANGELOG.md +10 -0
  2. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/FEATURES.md +7 -0
  3. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/PKG-INFO +146 -7
  4. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/QUICKSTARTS.md +82 -7
  5. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/README.md +143 -6
  6. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/RUNTIME_FEATURES.md +78 -7
  7. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/__init__.py +4 -1
  8. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/accounting.py +5 -0
  9. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/client.py +93 -0
  10. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/frameworks.py +66 -10
  11. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/langgraph.py +16 -2
  12. agenttrafficcop-2.1.0/agenttrafficcop/openai_gateway.py +200 -0
  13. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/runtime.py +113 -8
  14. agenttrafficcop-2.1.0/agenttrafficcop/tracing.py +188 -0
  15. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop.egg-info/PKG-INFO +146 -7
  16. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop.egg-info/SOURCES.txt +4 -0
  17. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop.egg-info/requires.txt +3 -0
  18. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/pyproject.toml +2 -1
  19. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/LICENSE +0 -0
  20. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/MANIFEST.in +0 -0
  21. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/autogen.py +0 -0
  22. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/embeddings.py +0 -0
  23. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/exceptions.py +0 -0
  24. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/local.py +0 -0
  25. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/models.py +0 -0
  26. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/normalization.py +0 -0
  27. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/outage.py +0 -0
  28. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/py.typed +0 -0
  29. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/recipes.py +0 -0
  30. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/recovery.py +0 -0
  31. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/replay.py +0 -0
  32. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/security.py +0 -0
  33. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop/semantic.py +0 -0
  34. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop.egg-info/dependency_links.txt +0 -0
  35. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/agenttrafficcop.egg-info/top_level.txt +0 -0
  36. {agenttrafficcop-2.0.0 → agenttrafficcop-2.1.0}/setup.cfg +0 -0
@@ -1,3 +1,13 @@
1
+ ## 2.1.0
2
+
3
+ - Add optional OpenAI SDK helpers that route BYOK Chat Completions through the
4
+ ATC OpenAI/Groq gateway, attach run and operation headers, and reuse each
5
+ operation ID across the OpenAI SDK's internal retries. Persisted IDs can be
6
+ supplied explicitly for application-level recovery.
7
+ - Add a tested egress-locked Docker quickstart that pairs the helper with a
8
+ private agent network; direct provider egress remains blocked for that
9
+ container. The topology is opt-in and self-hosted, not universal interception.
10
+
1
11
  ## 2.0.0
2
12
 
3
13
  - 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.1.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.1.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,27 @@ 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
 
535
674
  ```bash
536
- python -m pip install 'agenttrafficcop[langgraph]==2.0.0'
675
+ python -m pip install 'agenttrafficcop[langgraph]==2.1.0'
537
676
  ```
538
677
 
539
678
  ```python
@@ -555,7 +694,7 @@ shadow mode or spending reservations. Use direct checks for unexposed options.
555
694
  ### Legacy AutoGen
556
695
 
557
696
  ```bash
558
- python -m pip install 'agenttrafficcop[autogen]==2.0.0'
697
+ python -m pip install 'agenttrafficcop[autogen]==2.1.0'
559
698
  ```
560
699
 
561
700
  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.1.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.1.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,27 @@ 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
 
488
625
  ```bash
489
- python -m pip install 'agenttrafficcop[langgraph]==2.0.0'
626
+ python -m pip install 'agenttrafficcop[langgraph]==2.1.0'
490
627
  ```
491
628
 
492
629
  ```python
@@ -508,7 +645,7 @@ shadow mode or spending reservations. Use direct checks for unexposed options.
508
645
  ### Legacy AutoGen
509
646
 
510
647
  ```bash
511
- python -m pip install 'agenttrafficcop[autogen]==2.0.0'
648
+ python -m pip install 'agenttrafficcop[autogen]==2.1.0'
512
649
  ```
513
650
 
514
651
  This legacy adapter supports only `pyautogen==0.2.35`, not AgentChat or AG2.
@@ -1,4 +1,4 @@
1
- # SDK 2.0 behavior takes precedence over historical notes below
1
+ # SDK 2.1 behavior takes precedence over historical notes below
2
2
 
3
3
  See [QUICKSTARTS.md](QUICKSTARTS.md) for recommended calls and migration.
4
4
  GuardRuntime root timestamp/request_id/trace_id stripping is now on by default;
@@ -6,6 +6,38 @@ nested metadata stays untouched. Set normalize_volatile_metadata=False for stric
6
6
  hashing. Existing LocalGuard/low-level client defaults do not change. Use a new
7
7
  session ID on policy migration. The 1.x descriptions below are historical.
8
8
 
9
+ ## Opt-in metadata-only spans
10
+
11
+ `GuardSync.span(session_id, name, kind="tool")` and `Guard.span(...)` are
12
+ synchronous/asynchronous context managers. They report completed operation
13
+ duration, a safe label, kind, outcome, and exception class to the matching run
14
+ timeline. No input, output, exception message, or traceback is sent. Reports are
15
+ best-effort; the SDK does not automatically patch provider clients or frameworks.
16
+ Only explicitly wrapped operations appear. These features are included in SDK
17
+ 2.1.0. For multi-step runs,
18
+ `guard.trace_batch(session_id)` buffers up to 100 spans per request and flushes
19
+ at capacity or scope exit. Registration helpers `guard_functions`,
20
+ `guard_autogen_tools`, `guard_crewai_tools`, and `guard_langgraph` accept an
21
+ active trace batch to wrap registered tools/nodes automatically. Mixed sync/async
22
+ callables use separate batches; CrewAI can use a `{'sync': ..., 'async': ...}`
23
+ mapping. This reduces request count but still waits once per batch; it is not
24
+ background delivery. Failed submissions are dropped without masking the
25
+ wrapped operation's result or exception. No global monkey-patching is used.
26
+
27
+ ## BYOK OpenAI-compatible gateway adapter
28
+
29
+ SDK 2.1.0 includes `openai_gateway_client` and
30
+ `async_openai_gateway_client`. They configure the standard OpenAI Python SDK to
31
+ send ATC bearer authorization, the BYOK provider key, a run ID, and a per-call
32
+ operation ID through ATC's `/v2` gateway. OpenAI SDK internal retries reuse the
33
+ same operation ID; pass a persisted ID explicitly for application retries after
34
+ process restarts. OpenAI and Groq non-streaming Chat Completions are supported;
35
+ this helper does not intercept other clients, frameworks, or Anthropic calls.
36
+ Install `agenttrafficcop[openai]`. The gateway requires configured model prices
37
+ and an eligible run budget. For direct-egress blocking, use the opt-in
38
+ self-hosted Compose setup in `../deploy/EGRESS_LOCKED.md`; it does not apply to
39
+ hosted Render or arbitrary external workloads.
40
+
9
41
  # Simpler setup — SDK 1.7.0
10
42
 
11
43
  ## Configure a budget-protected run once
@@ -28,12 +60,51 @@ response = run.execute(
28
60
 
29
61
  This fragment assumes a configured GuardRuntime, a UsageAccountant, provider
30
62
  client/credentials, and an existing Pro/Team run budget. Configure these once
31
- on a trusted backend. It is not a three-line complete billing integration.
32
- For async providers use `await run.aexecute(async_provider_function, ...)`.
33
- Pass `args`/`kwargs` when needed; the original response is returned unchanged.
34
- A per-call `semantic_text` is required when the runtime has semantic monitoring.
35
- Each call still explicitly identifies the action, estimate and durable operation
36
- ID; none are guessed. Separate runs and tenants must have separate bindings.
63
+ on a trusted backend. For async providers use `await run.aexecute(...)`. Pass
64
+ `args`/`kwargs` when needed; the original response is returned unchanged. A
65
+ per-call `semantic_text` is required when the runtime has semantic monitoring.
66
+ Separate runs and tenants must have separate bindings.
67
+
68
+ For supported OpenAI Chat Completions and Anthropic Messages calls, use the
69
+ provider-shaped shortcut to avoid rebuilding request kwargs and check context:
70
+
71
+ ```python
72
+ run = runtime.run(
73
+ session_id="persisted-run-id", sender="agent", recipient="openai",
74
+ accountant=openai_accountant,
75
+ estimate_cost=estimate_request, # Local callback configured once.
76
+ )
77
+ response = run.openai_chat(
78
+ client.chat.completions.create,
79
+ operation_id="persisted-operation-id",
80
+ model="exact-priced-model",
81
+ messages=[{"role": "user", "content": "Find the refund rules"}],
82
+ max_tokens=500,
83
+ )
84
+ # Async variant: await run.aopenai_chat(async_create, ...)
85
+ # Anthropic variants: run.anthropic_messages(...) / await run.aanthropic_messages(...)
86
+ ```
87
+
88
+ The Anthropic methods accept `client.messages.create` and named `system`,
89
+ `model`, and `messages` arguments. Configure the matching provider-specific
90
+ UsageAccountant with exact prices. These shortcuts use the normal non-streaming
91
+ create callable, add no provider SDK dependency, and return the provider result
92
+ unchanged. They do not cover Responses API, streaming, arbitrary provider
93
+ methods or automatic interception.
94
+
95
+ The optional `estimate_cost(request, provider=..., operation_id=...)` callback
96
+ runs locally before the hosted check/reservation and must return a positive USD
97
+ estimate; alternatively pass `estimated_cost_usd` per call. Implement estimates
98
+ with your own tokenizer/prices and conservative output allowance. The SDK does
99
+ not guess token costs, fetch prices or turn estimates into hard caps. Callback
100
+ request contents stay local unless you separately select raw-payload mode, but
101
+ your callback should avoid logging prompt data. Operation IDs remain caller-
102
+ supplied, stable and durable: reuse after an uncertain outcome must not execute
103
+ again. By default only hash-only action identity is sent to the hosted service. To
104
+ send raw provider request data, construct `GuardRuntime(...,
105
+ normalize_volatile_metadata=False)` and bind `run(hash_only=False)` explicitly;
106
+ this transmits prompts/options and should be treated as a deliberate privacy
107
+ choice. Hashes themselves are not encryption or guaranteed anonymization.
37
108
 
38
109
  Execution delegates to the existing check/reserve/execute/report/settle path.
39
110
  Rejects or duplicate holds do not execute. Provider errors, cancellation or
@@ -25,6 +25,7 @@ from .frameworks import guard_functions, guard_autogen_tools, guard_crewai_tools
25
25
  from .accounting import TokenPrices, UsageAccountant, SignedUsageReporter, CostReportingError
26
26
  from .security import SecurityGuard, TextSecurityResult, ToolAuthorization
27
27
  from .recovery import RecoveryHooks, RecoveryDirective
28
+ from .openai_gateway import openai_gateway_client, async_openai_gateway_client
28
29
 
29
30
  try:
30
31
  from .langgraph import guarded_node
@@ -38,7 +39,7 @@ except ImportError:
38
39
  AgentTrafficCopCallback = None
39
40
 
40
41
  # Bumped for the new schema hashing, langgraph async fix, and AtcConnectionError rename
41
- __version__ = "2.0.0"
42
+ __version__ = "2.1.0"
42
43
 
43
44
  __all__ = [
44
45
  "__version__",
@@ -68,6 +69,8 @@ __all__ = [
68
69
  "ToolAuthorization",
69
70
  "RecoveryHooks",
70
71
  "RecoveryDirective",
72
+ "openai_gateway_client",
73
+ "async_openai_gateway_client",
71
74
  "SemanticObservation",
72
75
  "LocalGuard",
73
76
  "LocalResult",