agentbill-io 12.4.0__py3-none-any.whl

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.
agentbill/__init__.py ADDED
@@ -0,0 +1,202 @@
1
+ """
2
+ AgentBill Python SDK
3
+ OpenTelemetry-based SDK for tracking AI agent usage and billing
4
+
5
+ Features:
6
+ - Context manager (@agentbill_tracing) for Cost Guard protected AI calls
7
+ - signal() function for business event tracking and revenue attribution
8
+ - Auto-instrumentation for OpenAI, Anthropic, Cohere, Google AI
9
+ - Distributed tracing for cross-service trace propagation
10
+ - REST-based SignalsResource for standalone signal CRUD (v8.1.0)
11
+ """
12
+
13
+ from .client import AgentBill
14
+ from .tracer import AgentBillTracer
15
+ from .types import AgentBillConfig, TraceContext, GroupByKeys, Signal, CostData, BulkResult
16
+ from .validation import (
17
+ validate_api_key,
18
+ validate_base_url,
19
+ validate_customer_id,
20
+ validate_event_name,
21
+ validate_metadata,
22
+ validate_revenue,
23
+ ValidationError as InputValidationError
24
+ )
25
+
26
+ # New v6.6.0 features
27
+ from .exceptions import (
28
+ AgentBillError,
29
+ BudgetExceededError,
30
+ RateLimitExceededError,
31
+ PolicyViolationError,
32
+ ValidationError,
33
+ TracingError,
34
+ )
35
+ from .tracing import (
36
+ agentbill_tracing,
37
+ agentbill_traced,
38
+ TracingContext,
39
+ )
40
+ from .signals import (
41
+ signal,
42
+ track_conversion,
43
+ cost_attributed_signal,
44
+ set_signal_config,
45
+ get_signal_config,
46
+ )
47
+ from .bulk import record_bulk
48
+ from .autoinstrument import (
49
+ agentbill_autoinstrument,
50
+ initialize_tracing,
51
+ )
52
+ from .distributed import (
53
+ get_trace_context,
54
+ set_trace_context,
55
+ clear_trace_context,
56
+ propagate_trace_headers,
57
+ extract_trace_from_headers,
58
+ )
59
+ from .wrappers import (
60
+ AgentBillOpenAI,
61
+ AgentBillAnthropic,
62
+ AgentBillCohere,
63
+ AgentBillGoogleAI,
64
+ AgentBillBedrock,
65
+ )
66
+ from .resources.signals_resource import SignalsResource
67
+ from .otel_provider import AgentBillTracerProvider, NativeSpanWrapper
68
+ from .logger import get_logger, set_log_level
69
+ from .http_client import AgentBillHTTPClient, AgentBillResponse
70
+ from .async_http_client import AsyncAgentBillHTTPClient
71
+ from .async_client import AsyncAgentBill
72
+ from .raw_response import RawResponseProxy, WithRawResponseMixin
73
+ from .context import ( # P3-C: Rich Context Model
74
+ AgentBillContext,
75
+ get_context,
76
+ set_context,
77
+ clear_context,
78
+ context,
79
+ get_context_attributes,
80
+ get_context_baggage,
81
+ )
82
+ from .span_processor import ( # P3-D: Span Processing Pipeline
83
+ AgentBillSpanProcessor,
84
+ STRIP_PROMPTS,
85
+ MASK_EMAILS,
86
+ MASK_KEYS,
87
+ )
88
+ from .instrument import ( # P3-E: OpenInference Auto-Instrumentation
89
+ instrument,
90
+ uninstrument,
91
+ get_instrumented_providers,
92
+ )
93
+ from .resources.ingestion import (
94
+ IngestionResource,
95
+ HEADER_REQUEST_ID,
96
+ )
97
+
98
+ __version__ = "12.4.0"
99
+ __all__ = [
100
+ # Core
101
+ "AgentBill",
102
+ "AgentBillTracer",
103
+ "AgentBillConfig",
104
+ "TraceContext",
105
+ "GroupByKeys",
106
+
107
+ # Logging (v10.1.0)
108
+ "get_logger",
109
+ "set_log_level",
110
+
111
+ # HTTP Client (v10.2.0)
112
+ "AgentBillHTTPClient",
113
+ "AgentBillResponse",
114
+
115
+ # Async (v10.3.0)
116
+ "AsyncAgentBillHTTPClient",
117
+ "AsyncAgentBill",
118
+
119
+ # Raw Response (v10.3.0)
120
+ "RawResponseProxy",
121
+ "WithRawResponseMixin",
122
+
123
+ # Types (v8.1.0)
124
+ "Signal",
125
+ "CostData",
126
+ "BulkResult",
127
+
128
+ # Resources (v8.1.0)
129
+ "SignalsResource",
130
+
131
+ # Ingestion submit + status
132
+ "IngestionResource",
133
+ "HEADER_REQUEST_ID",
134
+
135
+ # Exceptions
136
+ "AgentBillError",
137
+ "BudgetExceededError",
138
+ "RateLimitExceededError",
139
+ "PolicyViolationError",
140
+ "ValidationError",
141
+ "TracingError",
142
+
143
+ # Input Validation (legacy)
144
+ "InputValidationError",
145
+ "validate_api_key",
146
+ "validate_base_url",
147
+ "validate_customer_id",
148
+ "validate_event_name",
149
+ "validate_metadata",
150
+ "validate_revenue",
151
+
152
+ # Context Manager / Decorator
153
+ "agentbill_tracing",
154
+ "agentbill_traced",
155
+ "TracingContext",
156
+
157
+ # Signals
158
+ "signal",
159
+ "track_conversion",
160
+ "cost_attributed_signal",
161
+ "set_signal_config",
162
+ "get_signal_config",
163
+ "record_bulk",
164
+
165
+ # Auto-instrumentation
166
+ "agentbill_autoinstrument",
167
+ "initialize_tracing",
168
+
169
+ # Distributed Tracing
170
+ "get_trace_context",
171
+ "set_trace_context",
172
+ "clear_trace_context",
173
+ "propagate_trace_headers",
174
+ "extract_trace_from_headers",
175
+
176
+ # Wrapper Classes (Hybrid Approach)
177
+ "AgentBillOpenAI",
178
+ "AgentBillAnthropic",
179
+ "AgentBillCohere",
180
+ "AgentBillGoogleAI",
181
+ "AgentBillBedrock",
182
+
183
+ # Rich Context Model (P3-C)
184
+ "AgentBillContext",
185
+ "get_context",
186
+ "set_context",
187
+ "clear_context",
188
+ "context",
189
+ "get_context_attributes",
190
+ "get_context_baggage",
191
+
192
+ # Span Processing Pipeline (P3-D)
193
+ "AgentBillSpanProcessor",
194
+ "STRIP_PROMPTS",
195
+ "MASK_EMAILS",
196
+ "MASK_KEYS",
197
+
198
+ # OpenInference Auto-Instrumentation (P3-E)
199
+ "instrument",
200
+ "uninstrument",
201
+ "get_instrumented_providers",
202
+ ]
@@ -0,0 +1,98 @@
1
+ """AgentBill Async Client — v10.4.1
2
+
3
+ Async counterpart of the AgentBill client for use with async frameworks.
4
+ Provides the same resource API surface but all HTTP calls are async.
5
+
6
+ Usage:
7
+ from agentbill import AsyncAgentBill
8
+
9
+ async with AsyncAgentBill.init({"api_key": "agb_...", "customer_id": "cust_123"}) as client:
10
+ customers = await client.customers.alist(limit=10)
11
+ resp = await client.request("GET", "/v1/custom-endpoint")
12
+ """
13
+
14
+ from typing import Any, Dict
15
+
16
+ from .types import AgentBillConfig
17
+ from .async_http_client import AsyncAgentBillHTTPClient
18
+
19
+
20
+ class _AsyncResourceProxy:
21
+ """Wraps sync resource methods to use the async HTTP client.
22
+
23
+ Each CRUD call delegates to the async HTTP client, returning parsed data.
24
+ """
25
+
26
+ def __init__(self, http: AsyncAgentBillHTTPClient, base_path: str):
27
+ self._http = http
28
+ self._path = base_path
29
+
30
+ async def list(self, **params) -> Dict[str, Any]:
31
+ str_params = {k: str(v) for k, v in params.items() if v is not None}
32
+ resp = await self._http.get(self._path, params=str_params)
33
+ return resp.data
34
+
35
+ async def create(self, **payload) -> Dict[str, Any]:
36
+ clean = {k: v for k, v in payload.items() if v is not None}
37
+ resp = await self._http.post(self._path, json=clean)
38
+ return resp.data
39
+
40
+ async def get(self, resource_id: str) -> Dict[str, Any]:
41
+ resp = await self._http.get(self._path, params={"id": resource_id})
42
+ return resp.data
43
+
44
+ async def update(self, resource_id: str, **payload) -> Dict[str, Any]:
45
+ clean = {k: v for k, v in payload.items() if v is not None}
46
+ clean["id"] = resource_id
47
+ resp = await self._http.patch(self._path, json=clean)
48
+ return resp.data
49
+
50
+ async def delete(self, resource_id: str) -> None:
51
+ await self._http.request("DELETE", self._path, json={"id": resource_id})
52
+
53
+
54
+ class AsyncAgentBill:
55
+ """Async AgentBill SDK client.
56
+
57
+ Mirrors the sync ``AgentBill`` class but uses ``AsyncAgentBillHTTPClient``
58
+ under the hood. Resources expose async CRUD methods.
59
+ """
60
+
61
+ def __init__(self, config: AgentBillConfig):
62
+ self.config = config
63
+ base_url = config.get("base_url", "https://api.agentbill.io")
64
+ api_key = config["api_key"]
65
+ self.http = AsyncAgentBillHTTPClient(base_url=base_url, api_key=api_key)
66
+
67
+ # Async resource proxies
68
+ self.customers = _AsyncResourceProxy(self.http, "/functions/v1/api-customers")
69
+ self.agents = _AsyncResourceProxy(self.http, "/functions/v1/api-agents")
70
+ self.contacts = _AsyncResourceProxy(self.http, "/functions/v1/api-contacts")
71
+ self.orders = _AsyncResourceProxy(self.http, "/functions/v1/api-orders")
72
+ self.signal_types = _AsyncResourceProxy(self.http, "/functions/v1/api-signal-types")
73
+ self.signals = _AsyncResourceProxy(self.http, "/functions/v1/list-signals")
74
+
75
+ @classmethod
76
+ def init(cls, config: AgentBillConfig) -> "AsyncAgentBill":
77
+ """Initialize async AgentBill client."""
78
+ return cls(config)
79
+
80
+ # ── Raw HTTP escape hatch ─────────────────────────────────
81
+
82
+ async def request(self, method: str, path: str, **kwargs) -> Any:
83
+ """Make an arbitrary async HTTP request through the unified client."""
84
+ return await self.http.request(method, path, **kwargs)
85
+
86
+ # ── lifecycle ─────────────────────────────────────────────
87
+
88
+ async def close(self) -> None:
89
+ await self.http.close()
90
+
91
+ async def __aenter__(self):
92
+ return self
93
+
94
+ async def __aexit__(self, *args):
95
+ await self.close()
96
+
97
+
98
+ __all__ = ["AsyncAgentBill"]
@@ -0,0 +1,177 @@
1
+ """AgentBill Async HTTP Client — v10.3.0
2
+
3
+ Async counterpart of AgentBillHTTPClient using httpx.AsyncClient.
4
+ For use with FastAPI, aiohttp, Django async views, and other async frameworks.
5
+
6
+ Usage:
7
+ async with AsyncAgentBillHTTPClient(base_url="https://api.agentbill.io", api_key="agb_...") as http:
8
+ response = await http.post("/functions/v1/otel-collector", json=payload)
9
+ print(response.data)
10
+ """
11
+
12
+ import asyncio
13
+ from typing import Any, Dict, Optional
14
+
15
+ import httpx
16
+
17
+ from .logger import get_logger
18
+ from .exceptions import (
19
+ AgentBillError,
20
+ BudgetExceededError,
21
+ RateLimitExceededError,
22
+ PolicyViolationError,
23
+ ValidationError,
24
+ )
25
+ from .http_client import AgentBillResponse
26
+
27
+ _log = get_logger("async_http")
28
+
29
+
30
+ class AsyncAgentBillHTTPClient:
31
+ """Async HTTP transport for the AgentBill Python SDK.
32
+
33
+ Mirrors AgentBillHTTPClient API but all methods are async.
34
+ Uses httpx.AsyncClient for non-blocking I/O.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ base_url: str,
40
+ api_key: str,
41
+ timeout: float = 30.0,
42
+ max_retries: int = 2,
43
+ retry_on: tuple = (502, 503, 504),
44
+ ):
45
+ self.base_url = base_url.rstrip("/")
46
+ self.api_key = api_key
47
+ self.timeout = timeout
48
+ self.max_retries = max_retries
49
+ self.retry_on = retry_on
50
+ self._client = httpx.AsyncClient(
51
+ timeout=timeout,
52
+ headers={
53
+ "Content-Type": "application/json",
54
+ "X-API-Key": api_key,
55
+ },
56
+ )
57
+
58
+ # ── public convenience methods ────────────────────────────────
59
+
60
+ async def get(self, path: str, *, params: Optional[Dict] = None, **kw) -> AgentBillResponse:
61
+ return await self.request("GET", path, params=params, **kw)
62
+
63
+ async def post(self, path: str, *, json: Any = None, **kw) -> AgentBillResponse:
64
+ return await self.request("POST", path, json=json, **kw)
65
+
66
+ async def put(self, path: str, *, json: Any = None, **kw) -> AgentBillResponse:
67
+ return await self.request("PUT", path, json=json, **kw)
68
+
69
+ async def patch(self, path: str, *, json: Any = None, **kw) -> AgentBillResponse:
70
+ return await self.request("PATCH", path, json=json, **kw)
71
+
72
+ async def delete(self, path: str, **kw) -> AgentBillResponse:
73
+ return await self.request("DELETE", path, **kw)
74
+
75
+ # ── core request with retry ───────────────────────────────────
76
+
77
+ async def request(
78
+ self,
79
+ method: str,
80
+ path: str,
81
+ *,
82
+ json: Any = None,
83
+ params: Optional[Dict] = None,
84
+ headers: Optional[Dict[str, str]] = None,
85
+ timeout: Optional[float] = None,
86
+ ) -> AgentBillResponse:
87
+ """Execute an async HTTP request with retry, error mapping, and logging."""
88
+ url = f"{self.base_url}{path}" if path.startswith("/") else path
89
+
90
+ merged_headers = {}
91
+ if headers:
92
+ merged_headers.update(headers)
93
+
94
+ last_exc: Optional[Exception] = None
95
+
96
+ for attempt in range(self.max_retries + 1):
97
+ try:
98
+ _log.debug(f"{method} {path} (attempt {attempt + 1})")
99
+ resp = await self._client.request(
100
+ method,
101
+ url,
102
+ json=json,
103
+ params=params,
104
+ headers=merged_headers,
105
+ timeout=timeout or self.timeout,
106
+ )
107
+ wrapped = AgentBillResponse(resp)
108
+
109
+ if resp.status_code in self.retry_on and attempt < self.max_retries:
110
+ wait = 0.5 * (2 ** attempt)
111
+ _log.warning(f"Retryable {resp.status_code} on {path}, retrying in {wait:.1f}s")
112
+ await asyncio.sleep(wait)
113
+ continue
114
+
115
+ if not wrapped.ok:
116
+ self._raise_for_status(wrapped)
117
+
118
+ _log.debug(f"{method} {path} → {resp.status_code}")
119
+ return wrapped
120
+
121
+ except (httpx.TimeoutException, httpx.ConnectError) as exc:
122
+ last_exc = exc
123
+ if attempt < self.max_retries:
124
+ wait = 0.5 * (2 ** attempt)
125
+ _log.warning(f"Network error on {path}: {exc}, retrying in {wait:.1f}s")
126
+ await asyncio.sleep(wait)
127
+ else:
128
+ _log.error(f"Request failed after {self.max_retries + 1} attempts: {exc}")
129
+ raise AgentBillError(f"Request to {path} failed: {exc}") from exc
130
+
131
+ except (BudgetExceededError, RateLimitExceededError, PolicyViolationError):
132
+ raise
133
+
134
+ except AgentBillError:
135
+ raise
136
+
137
+ raise AgentBillError(f"Request to {path} failed after retries") from last_exc
138
+
139
+ # ── error mapping (reuses same logic as sync client) ──────────
140
+
141
+ def _raise_for_status(self, resp: AgentBillResponse) -> None:
142
+ status = resp.status
143
+ body = resp.data if isinstance(resp.data, dict) else {}
144
+ message = body.get("error") or body.get("message") or resp.raw.text
145
+
146
+ if status == 429:
147
+ raise RateLimitExceededError(
148
+ str(message),
149
+ details={"retry_after": resp.headers.get("Retry-After")},
150
+ )
151
+ if status == 403:
152
+ reason = body.get("reason", str(message))
153
+ code = body.get("code", "")
154
+ if code == "BUDGET_EXCEEDED" or "budget" in reason.lower():
155
+ raise BudgetExceededError(reason, details=body)
156
+ raise PolicyViolationError(reason, details=body)
157
+ if status == 422:
158
+ raise ValidationError(str(message), field=body.get("field"))
159
+ if status >= 400:
160
+ raise AgentBillError(
161
+ f"HTTP {status}: {message}",
162
+ details={"status": status, "body": body},
163
+ )
164
+
165
+ # ── lifecycle ─────────────────────────────────────────────────
166
+
167
+ async def close(self) -> None:
168
+ await self._client.aclose()
169
+
170
+ async def __aenter__(self):
171
+ return self
172
+
173
+ async def __aexit__(self, *args):
174
+ await self.close()
175
+
176
+
177
+ __all__ = ["AsyncAgentBillHTTPClient"]
@@ -0,0 +1,90 @@
1
+ """Canonical attribute constants for OTEL span attributes.
2
+
3
+ Single source of truth for all attribute keys used across the SDK.
4
+ Prevents string drift between signals.py, client.py, bulk.py, and wrappers.py.
5
+
6
+ v8.0.0: Created as part of Signals Revamp Phase 1.
7
+ """
8
+
9
+ # Core signal attributes
10
+ ATTR_EVENT_NAME = "agentbill.event_name"
11
+ ATTR_IS_BUSINESS_EVENT = "agentbill.is_business_event"
12
+ ATTR_IDEMPOTENCY_KEY = "agentbill.idempotency_key"
13
+ ATTR_DATA_SOURCE = "agentbill.data_source"
14
+
15
+ # Identity
16
+ ATTR_CUSTOMER_ID = "agentbill.customer_id"
17
+ ATTR_AGENT_ID = "agentbill.agent_id"
18
+
19
+ # Business data
20
+ ATTR_REVENUE = "agentbill.revenue"
21
+ ATTR_CURRENCY = "agentbill.currency"
22
+ ATTR_EVENT_TYPE = "agentbill.event_type"
23
+ ATTR_EVENT_VALUE = "agentbill.event_value"
24
+
25
+ # Linking
26
+ ATTR_SESSION_ID = "agentbill.session_id"
27
+ ATTR_ORDER_ID = "agentbill.order_id"
28
+ ATTR_ORDER_EXTERNAL_ID = "agentbill.order_external_id"
29
+ ATTR_PARENT_SPAN_ID = "agentbill.parent_span_id"
30
+ ATTR_METADATA = "agentbill.metadata"
31
+
32
+ # AI telemetry (OpenTelemetry Semantic Conventions)
33
+ ATTR_MODEL = "gen_ai.request.model"
34
+ ATTR_PROVIDER = "gen_ai.system"
35
+ ATTR_PROMPT_TOKENS = "gen_ai.usage.prompt_tokens"
36
+ ATTR_COMPLETION_TOKENS = "gen_ai.usage.completion_tokens"
37
+ ATTR_TOTAL_TOKENS = "gen_ai.usage.total_tokens"
38
+ ATTR_LATENCY_MS = "agentbill.latency_ms"
39
+ ATTR_PROMPT_HASH = "agentbill.prompt_hash"
40
+
41
+ # Modality / operation name (OTEL Semantic Convention: gen_ai.operation.name)
42
+ # Official values: chat, embeddings, text_completion, create_image, audio_speech, audio_transcription
43
+ ATTR_OPERATION_NAME = "gen_ai.operation.name"
44
+
45
+ # Image generation — request params (pricing tier) vs usage (quantity billed)
46
+ ATTR_IMAGE_SIZE = "gen_ai.request.image_size" # e.g. "1024x1024" — determines price tier
47
+ ATTR_IMAGE_QUALITY = "gen_ai.request.image_quality" # e.g. "hd", "standard" — determines price tier
48
+ ATTR_IMAGE_COUNT = "gen_ai.usage.image_count" # actual images generated — quantity billed
49
+
50
+ # Audio — request params vs usage
51
+ ATTR_AUDIO_INPUT_FORMAT = "gen_ai.request.audio_input_format" # e.g. "mp3", "wav" — input config
52
+ ATTR_AUDIO_OUTPUT_FORMAT = "gen_ai.request.audio_output_format" # e.g. "mp3", "opus" — input config
53
+ ATTR_AUDIO_DURATION_SECONDS = "gen_ai.usage.audio_duration_seconds" # actual duration — quantity billed
54
+
55
+ # TTS — request params vs usage
56
+ ATTR_TTS_VOICE = "gen_ai.request.tts_voice" # e.g. "alloy", "nova" — determines price tier
57
+ ATTR_TTS_CHARACTERS = "gen_ai.usage.characters" # actual characters processed — quantity billed
58
+
59
+ # Embedding — request params vs usage
60
+ ATTR_EMBEDDING_DIMENSIONS = "gen_ai.request.embedding_dimensions" # requested dims — determines price tier
61
+ ATTR_EMBEDDING_INPUT_COUNT = "gen_ai.usage.embedding_input_count" # actual inputs — quantity billed
62
+
63
+ # Cache attributes
64
+ ATTR_CACHE_HIT = "agentbill.cache_hit"
65
+ ATTR_FROM_CACHE = "agentbill.from_cache"
66
+ ATTR_TOKENS_SAVED = "agentbill.tokens_saved"
67
+ ATTR_COST_SAVED = "agentbill.cost_saved"
68
+
69
+ # Cost tracing (Phase 1: enable_cost_tracing flag)
70
+ ATTR_COST_TRACING_ENABLED = "agentbill.cost_tracing.enabled"
71
+
72
+ # Manual cost (Phase 3 – two-variant model)
73
+ ATTR_COST_PROVIDED = "agentbill.cost.provided" # bool: server skips model_pricing
74
+ ATTR_COST_PROVIDER = "agentbill.cost.provider" # str: maps from CostData.vendor
75
+ ATTR_COST_AMOUNT = "agentbill.cost.amount" # float: pre-calculated cost
76
+ ATTR_COST_CURRENCY = "agentbill.cost.currency" # str: currency code
77
+
78
+ # Business grouping (whitelist)
79
+ GROUPING_KEYS = frozenset({"session_id", "workflow_id", "batch_id", "correlation_id"})
80
+
81
+ # Bulk
82
+ ATTR_BULK_INDEX = "agentbill.bulk_index"
83
+ ATTR_BULK_REQUEST = "agentbill.bulk_request"
84
+
85
+ # Resource / SDK constants
86
+ RESOURCE_SERVICE_NAME = "agentbill-python-sdk"
87
+ SDK_VERSION = "12.4.0"
88
+ SCOPE_NAME = "agentbill.signals"
89
+ SCOPE_NAME_BULK = "agentbill.signals.bulk"
90
+ SIGNAL_SPAN_NAME = "agentbill.trace.signal"