agentbill-io 12.4.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 (52) hide show
  1. agentbill_io-12.4.0/LICENSE +21 -0
  2. agentbill_io-12.4.0/PKG-INFO +391 -0
  3. agentbill_io-12.4.0/README.md +339 -0
  4. agentbill_io-12.4.0/agentbill/__init__.py +202 -0
  5. agentbill_io-12.4.0/agentbill/async_client.py +98 -0
  6. agentbill_io-12.4.0/agentbill/async_http_client.py +177 -0
  7. agentbill_io-12.4.0/agentbill/attributes.py +90 -0
  8. agentbill_io-12.4.0/agentbill/autoinstrument.py +567 -0
  9. agentbill_io-12.4.0/agentbill/bulk.py +197 -0
  10. agentbill_io-12.4.0/agentbill/client.py +1327 -0
  11. agentbill_io-12.4.0/agentbill/context.py +182 -0
  12. agentbill_io-12.4.0/agentbill/distributed.py +332 -0
  13. agentbill_io-12.4.0/agentbill/exceptions.py +171 -0
  14. agentbill_io-12.4.0/agentbill/http_client.py +226 -0
  15. agentbill_io-12.4.0/agentbill/instrument.py +213 -0
  16. agentbill_io-12.4.0/agentbill/integrations/__init__.py +14 -0
  17. agentbill_io-12.4.0/agentbill/integrations/crewai.py +80 -0
  18. agentbill_io-12.4.0/agentbill/integrations/langchain.py +271 -0
  19. agentbill_io-12.4.0/agentbill/logger.py +66 -0
  20. agentbill_io-12.4.0/agentbill/otel_provider.py +191 -0
  21. agentbill_io-12.4.0/agentbill/raw_response.py +70 -0
  22. agentbill_io-12.4.0/agentbill/resources/__init__.py +17 -0
  23. agentbill_io-12.4.0/agentbill/resources/_envelope.py +41 -0
  24. agentbill_io-12.4.0/agentbill/resources/agents.py +152 -0
  25. agentbill_io-12.4.0/agentbill/resources/contacts.py +104 -0
  26. agentbill_io-12.4.0/agentbill/resources/customers.py +113 -0
  27. agentbill_io-12.4.0/agentbill/resources/ingestion.py +135 -0
  28. agentbill_io-12.4.0/agentbill/resources/orders.py +195 -0
  29. agentbill_io-12.4.0/agentbill/resources/signal_types.py +99 -0
  30. agentbill_io-12.4.0/agentbill/resources/signals_resource.py +106 -0
  31. agentbill_io-12.4.0/agentbill/signal_builder.py +677 -0
  32. agentbill_io-12.4.0/agentbill/signals.py +261 -0
  33. agentbill_io-12.4.0/agentbill/span_processor.py +277 -0
  34. agentbill_io-12.4.0/agentbill/tracer.py +142 -0
  35. agentbill_io-12.4.0/agentbill/tracing.py +468 -0
  36. agentbill_io-12.4.0/agentbill/types.py +123 -0
  37. agentbill_io-12.4.0/agentbill/validation.py +143 -0
  38. agentbill_io-12.4.0/agentbill/wrappers.py +1039 -0
  39. agentbill_io-12.4.0/agentbill_io.egg-info/PKG-INFO +391 -0
  40. agentbill_io-12.4.0/agentbill_io.egg-info/SOURCES.txt +50 -0
  41. agentbill_io-12.4.0/agentbill_io.egg-info/dependency_links.txt +1 -0
  42. agentbill_io-12.4.0/agentbill_io.egg-info/requires.txt +39 -0
  43. agentbill_io-12.4.0/agentbill_io.egg-info/top_level.txt +1 -0
  44. agentbill_io-12.4.0/pyproject.toml +110 -0
  45. agentbill_io-12.4.0/setup.cfg +4 -0
  46. agentbill_io-12.4.0/tests/test_agentbill.py +115 -0
  47. agentbill_io-12.4.0/tests/test_cost_guard_errors.py +90 -0
  48. agentbill_io-12.4.0/tests/test_integrations.py +117 -0
  49. agentbill_io-12.4.0/tests/test_otel_compliance.py +166 -0
  50. agentbill_io-12.4.0/tests/test_resource_shapes.py +152 -0
  51. agentbill_io-12.4.0/tests/test_signal_trace_link.py +85 -0
  52. agentbill_io-12.4.0/tests/test_tracer.py +223 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 AgentBill
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,391 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentbill-io
3
+ Version: 12.4.0
4
+ Summary: OpenTelemetry-based SDK for tracking and billing AI agent usage with Cost Guard protection
5
+ Author-email: AgentBill <dominic@agentbill.io>
6
+ License: MIT
7
+ Project-URL: Homepage, https://agentbill.io
8
+ Project-URL: Documentation, https://docs.agentbill.io
9
+ Keywords: ai,billing,tracking,opentelemetry,llm,agents,cost-guard,tracing,distributed-tracing
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: httpx>=0.24.0
22
+ Requires-Dist: opentelemetry-api<2,>=1.27.0
23
+ Requires-Dist: opentelemetry-sdk<2,>=1.27.0
24
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.27.0
25
+ Provides-Extra: openai
26
+ Requires-Dist: openai>=1.0.0; extra == "openai"
27
+ Provides-Extra: anthropic
28
+ Requires-Dist: anthropic>=0.9.0; extra == "anthropic"
29
+ Provides-Extra: cohere
30
+ Requires-Dist: cohere>=4.0.0; extra == "cohere"
31
+ Provides-Extra: google
32
+ Requires-Dist: google-generativeai>=0.3.0; extra == "google"
33
+ Provides-Extra: otel
34
+ Provides-Extra: langchain
35
+ Requires-Dist: langchain-core>=0.2.0; extra == "langchain"
36
+ Provides-Extra: crewai
37
+ Requires-Dist: crewai>=0.30.0; extra == "crewai"
38
+ Requires-Dist: langchain-core>=0.2.0; extra == "crewai"
39
+ Provides-Extra: all
40
+ Requires-Dist: openai>=1.0.0; extra == "all"
41
+ Requires-Dist: anthropic>=0.9.0; extra == "all"
42
+ Requires-Dist: cohere>=4.0.0; extra == "all"
43
+ Requires-Dist: google-generativeai>=0.3.0; extra == "all"
44
+ Provides-Extra: dev
45
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
46
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
47
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
48
+ Requires-Dist: black>=23.0.0; extra == "dev"
49
+ Requires-Dist: pylint>=2.17.0; extra == "dev"
50
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
51
+ Dynamic: license-file
52
+
53
+ # AgentBill Python SDK
54
+
55
+ OpenTelemetry-based SDK for automatically tracking and billing AI agent usage.
56
+
57
+ ## Installation
58
+
59
+ ### From PyPI (Recommended)
60
+ ```bash
61
+ pip install agentbill-io
62
+ ```
63
+
64
+ ### From PyPI (Coming Soon)
65
+ ```bash
66
+ pip install agentbill
67
+ ```
68
+
69
+ ### From Source
70
+ ```bash
71
+ # Clone your repository and install
72
+ git clone https://github.com/yourusername/agentbill-python-sdk.git
73
+ cd agentbill-python-sdk
74
+ pip install -e .
75
+ ```
76
+
77
+ ## OpenTelemetry requirements (v12.2.0+)
78
+
79
+ The SDK is built only from official OpenTelemetry packages, installed with it:
80
+ `opentelemetry-api`, `opentelemetry-sdk` and `opentelemetry-exporter-otlp-proto-http`
81
+ (all `>=1.27,<2`). Spans go to `/otel-collector` through the official
82
+ `OTLPSpanExporter` (OTLP/HTTP protobuf) with static headers. No custom exporter,
83
+ no fallback mode. Python 3.10+.
84
+
85
+ **Already using OpenTelemetry?** If your app already set an OpenTelemetry SDK
86
+ `TracerProvider`, AgentBill adds its exporter to it instead of creating a second
87
+ one, so its spans join your traces. To send your own spans with nothing but the
88
+ standard library and environment variables:
89
+
90
+ ```bash
91
+ export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.agentbill.io/functions/v1/otel-collector
92
+ export OTEL_EXPORTER_OTLP_HEADERS="X-API-Key=agb_..."
93
+ ```
94
+
95
+ **Version conflicts:** `pip install -U opentelemetry-api opentelemetry-sdk` to align them.
96
+
97
+ ## File Structure
98
+
99
+ ```
100
+ agentbill-python/
101
+ ├── agentbill/
102
+ │ ├── __init__.py
103
+ │ ├── client.py
104
+ │ ├── tracer.py
105
+ │ └── types.py
106
+ ├── examples/
107
+ │ ├── openai_basic.py
108
+ │ ├── anthropic_basic.py
109
+ │ ├── bedrock_basic.py
110
+ │ ├── azure_openai_basic.py
111
+ │ ├── mistral_basic.py
112
+ │ └── google_ai_basic.py
113
+ ├── tests/
114
+ │ ├── test_agentbill.py
115
+ │ └── test_tracer.py
116
+ ├── README.md
117
+ ├── setup.py
118
+ ├── pyproject.toml
119
+ ├── pytest.ini
120
+ ├── Makefile
121
+ ├── CHANGELOG.md
122
+ ├── CONTRIBUTING.md
123
+ ├── SECURITY.md
124
+ └── LICENSE
125
+ ```
126
+
127
+ ## Quick Start
128
+
129
+ ```python
130
+ from agentbill import AgentBill
131
+ import openai
132
+
133
+ # Initialize AgentBill
134
+ agentbill = AgentBill.init({
135
+ "api_key": "your-api-key",
136
+ "customer_id": "customer-123",
137
+ "debug": True
138
+ })
139
+
140
+ # Wrap your OpenAI client
141
+ client = agentbill.wrap_openai(openai.OpenAI(
142
+ api_key="sk-..."
143
+ ))
144
+
145
+ # Use normally - all calls are automatically tracked!
146
+ response = client.chat.completions.create(
147
+ model="gpt-4",
148
+ messages=[{"role": "user", "content": "Hello!"}]
149
+ )
150
+ ```
151
+
152
+ ## ⚠️ Critical: Cost Guard Error Handling
153
+
154
+ Cost Guard runs on every wrapped call; decisions come only from the company’s Cost Guard policies (company, customer, and agent daily/monthly budgets in `cost_guard_policies`), configured in the AgentBill app at `/admin/system-configuration`. The SDK raises exceptions when policy limits are exceeded. **Do NOT catch and continue with direct AI calls** - the blocking is intentional to prevent overspending!
155
+
156
+ ```python
157
+ # ❌ WRONG - This bypasses budget protection!
158
+ try:
159
+ response = wrapped_client.chat.completions.create(...)
160
+ except Exception as e:
161
+ print("AgentBill failed, continuing anyway...")
162
+ response = unwrapped_client.chat.completions.create(...) # BUDGET BYPASSED!
163
+
164
+ # ✅ CORRECT - Respect the block, handle gracefully
165
+ try:
166
+ response = wrapped_client.chat.completions.create(...)
167
+ except Exception as e:
168
+ if hasattr(e, 'code') and e.code == 'BUDGET_EXCEEDED':
169
+ print("Budget limit reached - please upgrade or wait")
170
+ return None # Return early, don't bypass!
171
+ raise # Re-raise other errors
172
+ ```
173
+
174
+ ## Linking signals to an AI call
175
+
176
+ `signal()` chooses its trace in this order: explicit `trace_id` (`traceId` in
177
+ TypeScript) → active OpenTelemetry span → AgentBill’s stored context (set after
178
+ a wrapped client call) → a new trace. The active-span path covers `instrument()`,
179
+ `agentbill_tracing()` / `agentbillTracing()`, and your app’s own OpenTelemetry
180
+ spans. A signal linked to an AI call is a child span of that AI span.
181
+
182
+ With `AGENTBILL_API_KEY` and `OPENAI_API_KEY` set:
183
+
184
+ ```python
185
+ from agentbill import agentbill_tracing, signal
186
+ from openai import OpenAI
187
+
188
+ client = OpenAI()
189
+ with agentbill_tracing(customer_id="customer-123"):
190
+ response = client.chat.completions.create(
191
+ model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}]
192
+ )
193
+ signal("answer_delivered")
194
+ ```
195
+
196
+ With `instrument()` (install `openinference-instrumentation-openai` first;
197
+ `instrument()` installs instrumentation, it is not a context manager):
198
+
199
+ ```python
200
+ from agentbill import instrument, signal
201
+ from openai import OpenAI
202
+ from opentelemetry import trace
203
+
204
+ instrument(providers=["openai"], customer_id="customer-123")
205
+ client = OpenAI()
206
+ with trace.get_tracer(__name__).start_as_current_span("answer"):
207
+ response = client.chat.completions.create(
208
+ model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}]
209
+ )
210
+ signal("answer_delivered") # Joins the active application trace.
211
+ ```
212
+
213
+ TypeScript registers the official AsyncLocalStorage context manager when the
214
+ app has none, keeping concurrent requests in separate traces.
215
+
216
+ ## Features
217
+
218
+ - ✅ Zero-config instrumentation
219
+ - ✅ Accurate token & cost tracking
220
+ - ✅ Multi-provider support (OpenAI, Anthropic, Bedrock, Azure OpenAI, Mistral, Google AI)
221
+ - ✅ Rich metadata capture
222
+ - ✅ OpenTelemetry-based
223
+ - ✅ Cost Guard budget enforcement (blocks requests BEFORE spending)
224
+
225
+ ## Supported Providers
226
+
227
+ - **OpenAI** - GPT-4, GPT-5, Embeddings, DALL-E, Whisper, TTS
228
+ - **Anthropic** - Claude Sonnet, Claude Opus
229
+ - **AWS Bedrock** - Claude, Titan, and other Bedrock models
230
+ - **Azure OpenAI** - GPT models via Azure
231
+ - **Mistral AI** - Mistral models
232
+ - **Google AI** - Gemini Pro, Gemini Flash
233
+
234
+ ## Provider Examples
235
+
236
+ ### OpenAI
237
+ ```python
238
+ from agentbill import AgentBill
239
+ import openai
240
+
241
+ agentbill = AgentBill.init({"api_key": "your-api-key"})
242
+ client = agentbill.wrap_openai(openai.OpenAI(api_key="sk-..."))
243
+
244
+ response = client.chat.completions.create(
245
+ model="gpt-4",
246
+ messages=[{"role": "user", "content": "Hello!"}]
247
+ )
248
+ ```
249
+
250
+ ### Anthropic
251
+ ```python
252
+ from agentbill import AgentBill
253
+ import anthropic
254
+
255
+ agentbill = AgentBill.init({"api_key": "your-api-key"})
256
+ client = agentbill.wrap_anthropic(anthropic.Anthropic(api_key="sk-ant-..."))
257
+
258
+ response = client.messages.create(
259
+ model="claude-sonnet-4-20250514",
260
+ max_tokens=1024,
261
+ messages=[{"role": "user", "content": "Hello!"}]
262
+ )
263
+ ```
264
+
265
+ ### AWS Bedrock
266
+ ```python
267
+ from agentbill import AgentBill
268
+ import boto3
269
+
270
+ agentbill = AgentBill.init({"api_key": "your-api-key"})
271
+ bedrock = agentbill.wrap_bedrock(boto3.client('bedrock-runtime'))
272
+
273
+ response = bedrock.invoke_model(
274
+ modelId='anthropic.claude-v2',
275
+ body=json.dumps({
276
+ "prompt": "Hello!",
277
+ "max_tokens_to_sample": 300
278
+ })
279
+ )
280
+ ```
281
+
282
+ ### Azure OpenAI
283
+ ```python
284
+ from agentbill import AgentBill
285
+ from openai import AzureOpenAI
286
+
287
+ agentbill = AgentBill.init({"api_key": "your-api-key"})
288
+ client = agentbill.wrap_azure_openai(AzureOpenAI(
289
+ api_key="your-azure-key",
290
+ api_version="2024-02-01",
291
+ azure_endpoint="https://your-resource.openai.azure.com"
292
+ ))
293
+
294
+ response = client.chat.completions.create(
295
+ model="gpt-4",
296
+ messages=[{"role": "user", "content": "Hello!"}]
297
+ )
298
+ ```
299
+
300
+ ### Mistral AI
301
+ ```python
302
+ from agentbill import AgentBill
303
+ from mistralai import Mistral
304
+
305
+ agentbill = AgentBill.init({"api_key": "your-api-key"})
306
+ client = agentbill.wrap_mistral(Mistral(api_key="your-mistral-key"))
307
+
308
+ response = client.chat.complete(
309
+ model="mistral-large-latest",
310
+ messages=[{"role": "user", "content": "Hello!"}]
311
+ )
312
+ ```
313
+
314
+ ### Google AI (Gemini)
315
+ ```python
316
+ from agentbill import AgentBill
317
+ import google.generativeai as genai
318
+
319
+ agentbill = AgentBill.init({"api_key": "your-api-key"})
320
+ genai.configure(api_key="your-google-key")
321
+ model = genai.GenerativeModel('gemini-pro')
322
+ wrapped_model = agentbill.wrap_google_ai(model)
323
+
324
+ response = wrapped_model.generate_content("Hello!")
325
+ ```
326
+
327
+ ## Configuration
328
+
329
+ ```python
330
+ config = {
331
+ "api_key": "your-api-key", # Required
332
+ "base_url": "https://...", # Optional
333
+ "customer_id": "customer-123", # Optional
334
+ "debug": True # Optional
335
+ }
336
+
337
+ agentbill = AgentBill.init(config)
338
+ ```
339
+
340
+ ## Publishing to PyPI
341
+
342
+ ### Prerequisites
343
+ 1. Create a PyPI account at https://pypi.org/account/register/
344
+ 2. Generate an API token at https://pypi.org/manage/account/token/
345
+ 3. Create `~/.pypirc` file with your token:
346
+ ```ini
347
+ [pypi]
348
+ username = __token__
349
+ password = pypi-YOUR_API_TOKEN_HERE
350
+ ```
351
+
352
+ ### Publishing Steps
353
+ ```bash
354
+ # Build the package
355
+ python setup.py sdist bdist_wheel
356
+
357
+ # Upload to PyPI
358
+ pip install twine
359
+ twine upload dist/*
360
+ ```
361
+
362
+ ## GitHub Repository Setup
363
+
364
+ 1. Create your GitHub repository (e.g., `agentbill-python-sdk`)
365
+ 2. Push all files (agentbill/, examples/, LICENSE, setup.py, README.md)
366
+ 3. Tag releases: `git tag v1.0.0 && git push origin v1.0.0`
367
+ 4. Users can install with: `pip install agentbill-io`
368
+
369
+ ## Idempotent Ingestion (X-Request-Id)
370
+
371
+ Every OTLP batch this SDK exports to `/functions/v1/otel-collector` carries an
372
+ `X-Request-Id: <uuid4>` header (auto-generated per export, reused across
373
+ transport-level retries within that export). The collector deduplicates on
374
+ `(company_id, request_id)`, so a transient 5xx / network retry will not
375
+ double-write WAL rows, spans, or billing events.
376
+
377
+ - **No configuration required** — the header is emitted automatically by the
378
+ v7.x line of this SDK.
379
+ - **Server fallback:** clients that cannot set custom headers may send
380
+ `{"requestId": "..."}` at the JSON envelope root.
381
+ - **Native OTLP exporters:** the standard OTLP-HTTP exporter keeps headers
382
+ static across batches, so per-batch rotation is not yet wired on that path
383
+ (`PHASE3-R3-SDK-REQUESTID-NATIVE` — tracked); the collector still dedupes
384
+ those payloads on the natural key `(company_id, trace_id, span_id)`.
385
+
386
+ See the [OpenTelemetry Integration docs](https://www.agentbill.io/docs/otel)
387
+ for the full request-id contract.
388
+
389
+ ## License
390
+
391
+ MIT