cloudbyte-tracer 0.1.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.
- cloudbyte_tracer/__init__.py +44 -0
- cloudbyte_tracer/_version.py +10 -0
- cloudbyte_tracer/context.py +8 -0
- cloudbyte_tracer/core.py +213 -0
- cloudbyte_tracer/limits.py +69 -0
- cloudbyte_tracer/otel/__init__.py +1 -0
- cloudbyte_tracer/otel/context.py +39 -0
- cloudbyte_tracer/otel/exporter.py +21 -0
- cloudbyte_tracer/otel/instrument.py +94 -0
- cloudbyte_tracer/otel/mapping.py +70 -0
- cloudbyte_tracer/otel/processor.py +31 -0
- cloudbyte_tracer/redact.py +8 -0
- cloudbyte_tracer/transport.py +401 -0
- cloudbyte_tracer-0.1.0.dist-info/METADATA +108 -0
- cloudbyte_tracer-0.1.0.dist-info/RECORD +17 -0
- cloudbyte_tracer-0.1.0.dist-info/WHEEL +4 -0
- cloudbyte_tracer-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import atexit
|
|
4
|
+
import collections
|
|
5
|
+
import contextvars
|
|
6
|
+
import datetime
|
|
7
|
+
import functools
|
|
8
|
+
import http.client
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import numbers
|
|
12
|
+
import platform
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.parse
|
|
18
|
+
import urllib.request
|
|
19
|
+
import uuid
|
|
20
|
+
from typing import Optional
|
|
21
|
+
|
|
22
|
+
from ._version import SDK_VERSION
|
|
23
|
+
|
|
24
|
+
__all__ = ["Transport"]
|
|
25
|
+
|
|
26
|
+
_PREFIX = "cloudbyte_tracer:"
|
|
27
|
+
_PATH = "/v1/agent-spans"
|
|
28
|
+
_SENDER_THREAD_NAME = "cloudbyte-trace-sender"
|
|
29
|
+
_KINDS = ("agent", "llm", "tool", "retrieval", "custom")
|
|
30
|
+
_STATUSES = ("ok", "error", "unset")
|
|
31
|
+
_MAX_SPANS_PER_REQUEST = 500 # the server rejects a batch of more
|
|
32
|
+
_MAX_BODY_BYTES = 4_000_000 # the server refuses a request body of more than 5 MB; stay well under that
|
|
33
|
+
_MAX_FIELD_BYTES = 65536 # the server keeps at most 64 KB of an input or output and flags the rest as truncated
|
|
34
|
+
_CUT_FIELD_BYTES = 70000 # a longer one is sent cut to this: still over the server's limit, so it is still flagged
|
|
35
|
+
_MAX_NAME_CHARS = 200 # the server rejects a span name or model of more characters
|
|
36
|
+
_DEFAULT_BASE_URL = "https://api.cloudbyte.ai"
|
|
37
|
+
_DEFAULT_RETRY_AFTER = 5.0 # seconds to wait after a 429 whose Retry-After header is missing or not a whole number
|
|
38
|
+
_MAX_QUEUE_SPANS = 10_000 # bound memory while the sender is backing off
|
|
39
|
+
_MAX_QUEUE_BYTES = 8_000_000
|
|
40
|
+
_MAX_RETRY_AFTER = 60.0 # the longest a 429 makes the sender wait
|
|
41
|
+
# Tells the server which SDK and runtime sent a batch, e.g. "cloudbyte-tracer-python/0.1.0 (CPython 3.12.10)".
|
|
42
|
+
_USER_AGENT = "cloudbyte-tracer-python/%s (%s %s)" % (
|
|
43
|
+
SDK_VERSION, platform.python_implementation(), platform.python_version())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _log(message: str) -> None:
|
|
47
|
+
try:
|
|
48
|
+
stream = sys.stderr
|
|
49
|
+
if stream is not None:
|
|
50
|
+
print("%s %s" % (_PREFIX, message), file=stream)
|
|
51
|
+
except Exception:
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _never_raises(method):
|
|
56
|
+
"""Turn any unexpected error in a public method into a stderr line, so it never reaches the caller."""
|
|
57
|
+
@functools.wraps(method)
|
|
58
|
+
def wrapper(*args, **kwargs):
|
|
59
|
+
try:
|
|
60
|
+
return method(*args, **kwargs)
|
|
61
|
+
except Exception as exc:
|
|
62
|
+
_log("%s failed: %s: %s" % (method.__name__, type(exc).__name__, "internal tracing error"))
|
|
63
|
+
return wrapper
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _now() -> str:
|
|
67
|
+
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _text(value) -> str:
|
|
71
|
+
if isinstance(value, str):
|
|
72
|
+
return value
|
|
73
|
+
try:
|
|
74
|
+
return str(value)
|
|
75
|
+
except Exception:
|
|
76
|
+
return "<unprintable %s>" % type(value).__name__
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _attribute_value(value):
|
|
80
|
+
"""The server accepts only strings, booleans and finite numbers as attribute values."""
|
|
81
|
+
if isinstance(value, (str, bool, int)) or (isinstance(value, float) and math.isfinite(value)):
|
|
82
|
+
return value
|
|
83
|
+
return _text(value)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _clean_attributes(attributes) -> dict:
|
|
87
|
+
cleaned = {}
|
|
88
|
+
if attributes is None:
|
|
89
|
+
return cleaned
|
|
90
|
+
try:
|
|
91
|
+
for key, value in dict(attributes).items():
|
|
92
|
+
cleaned[_text(key)] = _attribute_value(value)
|
|
93
|
+
except Exception as exc:
|
|
94
|
+
_log("ignoring attributes that are not a mapping: %s" % exc)
|
|
95
|
+
return cleaned
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _clamp(text: str) -> str:
|
|
99
|
+
"""A span name or model cut to what the server accepts: it rejects a longer one, which would leave a run 'running'."""
|
|
100
|
+
return text[:_MAX_NAME_CHARS] # a Python string slice counts code points, as the server does
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _cut(text: str) -> str:
|
|
104
|
+
"""The first _CUT_FIELD_BYTES bytes of ``text`` in UTF-8, ending on a whole character."""
|
|
105
|
+
# Every character is at least one byte, so the first _CUT_FIELD_BYTES characters hold all the bytes wanted.
|
|
106
|
+
data = text[:_CUT_FIELD_BYTES].encode("utf-8", "replace") # a lone surrogate becomes "?"
|
|
107
|
+
return data[:_CUT_FIELD_BYTES].decode("utf-8", "ignore") # "ignore" drops a character the cut left half of
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _fit(value):
|
|
111
|
+
"""An input or output as it is sent.
|
|
112
|
+
|
|
113
|
+
The server stores at most 64 KB of one, so a value whose JSON text is longer is sent as a string of the first
|
|
114
|
+
~70,000 bytes of that text: the server cuts it to its limit and flags it truncated, and one huge value cannot
|
|
115
|
+
push the request over the server's 5 MB limit, which would refuse the whole batch. Content JSON cannot hold
|
|
116
|
+
(NaN, a circular structure, an odd key) is sent as its repr, cut the same way.
|
|
117
|
+
"""
|
|
118
|
+
try:
|
|
119
|
+
text = json.dumps(value, default=str, allow_nan=False, ensure_ascii=False, separators=(",", ":"))
|
|
120
|
+
return value if len(text.encode("utf-8", "replace")) <= _MAX_FIELD_BYTES else _cut(text)
|
|
121
|
+
except Exception:
|
|
122
|
+
return _cut(repr(value))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _encode(span: dict) -> Optional[str]:
|
|
126
|
+
"""JSON text for one span copy, with an oversized input or output cut (see ``_fit``). None if it cannot be encoded."""
|
|
127
|
+
try:
|
|
128
|
+
copy = dict(span)
|
|
129
|
+
for field in ("input", "output"):
|
|
130
|
+
if field in copy:
|
|
131
|
+
copy[field] = _fit(copy[field])
|
|
132
|
+
return json.dumps(copy, default=str, allow_nan=False)
|
|
133
|
+
except Exception as exc:
|
|
134
|
+
_log("dropping span %r: it cannot be encoded as JSON: %s" % (span.get("name"), exc))
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _server_message(payload: bytes) -> str:
|
|
139
|
+
"""The server's `error` text, or the start of the body when it is not the usual JSON."""
|
|
140
|
+
try:
|
|
141
|
+
message = json.loads(payload).get("error")
|
|
142
|
+
if isinstance(message, str):
|
|
143
|
+
return message
|
|
144
|
+
except Exception:
|
|
145
|
+
pass
|
|
146
|
+
return payload.decode("utf-8", "replace")[:200]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _retry_after(headers) -> float:
|
|
150
|
+
"""Seconds to wait after a 429: the Retry-After header (whole seconds) capped at _MAX_RETRY_AFTER, else the default."""
|
|
151
|
+
try:
|
|
152
|
+
seconds = int(headers.get("Retry-After", "").strip())
|
|
153
|
+
if seconds >= 0:
|
|
154
|
+
return float(min(seconds, _MAX_RETRY_AFTER))
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
return _DEFAULT_RETRY_AFTER
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Transport:
|
|
161
|
+
"""Creates spans and sends them to the server from a background thread.
|
|
162
|
+
|
|
163
|
+
Root spans are queued on start and end; children are queued on end only. The sender thread posts the
|
|
164
|
+
queue every ``flush_interval`` seconds, or as soon as ``max_batch`` spans (at most 500) are waiting; a batch
|
|
165
|
+
is also cut at about 4 MB, and an input or output over 64 KB is sent cut (the server flags it truncated).
|
|
166
|
+
A 5xx response or a connection error is retried after each of ``retry_delays`` seconds, then the batch
|
|
167
|
+
is dropped; a 4xx response is not retried. Both are reported on stderr.
|
|
168
|
+
A 429 (rate limit) waits for the Retry-After header (at most 60 seconds, 5 if it is missing or invalid)
|
|
169
|
+
instead of the next retry delay, and uses one retry. A 403 (the agent is disabled, or Agent Observability is
|
|
170
|
+
off for the organization) is reported once; the tracer then drops every further span.
|
|
171
|
+
While the sender is blocked, the queue holds at most 10,000 span copies or 8 MB of encoded JSON;
|
|
172
|
+
older copies are dropped first and one warning is printed. Tracing never waits for queue space.
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
def __init__(self, api_key: str, base_url: str = _DEFAULT_BASE_URL, *, capture_content: bool = True,
|
|
176
|
+
flush_interval: float = 1.0, max_batch: int = 100, timeout: float = 5.0,
|
|
177
|
+
retry_delays: tuple = (0.5, 1.0, 2.0)) -> None:
|
|
178
|
+
if not isinstance(api_key, str) or not api_key.strip():
|
|
179
|
+
raise ValueError("api_key must be a non-empty string")
|
|
180
|
+
if not isinstance(base_url, str):
|
|
181
|
+
raise ValueError("base_url must be an http:// or https:// URL")
|
|
182
|
+
parts = urllib.parse.urlsplit(base_url)
|
|
183
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
184
|
+
raise ValueError("base_url must be an http:// or https:// URL, got %r" % base_url)
|
|
185
|
+
|
|
186
|
+
if parts.username or parts.password or parts.query or parts.fragment:
|
|
187
|
+
raise ValueError("base_url cannot contain credentials, query or fragment")
|
|
188
|
+
self._api_key = api_key.strip()
|
|
189
|
+
self._base_url = base_url.rstrip("/")
|
|
190
|
+
self._endpoint = self._base_url + _PATH
|
|
191
|
+
self._capture_content = bool(capture_content)
|
|
192
|
+
self._flush_interval = max(0.0, float(flush_interval))
|
|
193
|
+
self._max_batch = max(1, min(int(max_batch), _MAX_SPANS_PER_REQUEST))
|
|
194
|
+
self._timeout = float(timeout)
|
|
195
|
+
self._retry_delays = tuple(max(0.0, float(delay)) for delay in retry_delays)
|
|
196
|
+
|
|
197
|
+
self._current = contextvars.ContextVar("cloudbyte_current_span_%x" % id(self), default=None)
|
|
198
|
+
self._queue: collections.deque = collections.deque() # (json text, span name, span id)
|
|
199
|
+
self._queue_bytes = 0
|
|
200
|
+
self._overflow_reported = False
|
|
201
|
+
self._cond = threading.Condition() # guards everything below
|
|
202
|
+
self._enqueued = 0 # span copies ever queued
|
|
203
|
+
self._processed = 0 # span copies the sender has finished with, whether sent or dropped
|
|
204
|
+
self._pending = set() # tickets still queued or in flight; bounded by queue + one batch
|
|
205
|
+
self._flush_requested = False
|
|
206
|
+
self._stop = threading.Event()
|
|
207
|
+
self._disabled = False # set by the server answering 403; read without the lock, it only ever goes False to True
|
|
208
|
+
|
|
209
|
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
210
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
211
|
+
return None
|
|
212
|
+
self._opener = urllib.request.build_opener(NoRedirect)
|
|
213
|
+
self._thread = threading.Thread(target=self._run, name=_SENDER_THREAD_NAME, daemon=True)
|
|
214
|
+
self._thread.start()
|
|
215
|
+
atexit.register(self.shutdown)
|
|
216
|
+
|
|
217
|
+
@_never_raises
|
|
218
|
+
def flush(self, timeout: float = 5.0) -> None:
|
|
219
|
+
"""Block until every span queued so far has been sent or dropped, for at most ``timeout`` seconds."""
|
|
220
|
+
deadline = time.monotonic() + float(timeout)
|
|
221
|
+
with self._cond:
|
|
222
|
+
target = self._enqueued
|
|
223
|
+
if not any(ticket <= target for ticket in self._pending) or not self._thread.is_alive():
|
|
224
|
+
return
|
|
225
|
+
self._flush_requested = True
|
|
226
|
+
self._cond.notify_all()
|
|
227
|
+
while any(ticket <= target for ticket in self._pending):
|
|
228
|
+
remaining = deadline - time.monotonic()
|
|
229
|
+
if remaining <= 0:
|
|
230
|
+
_log("flush timed out with %d span(s) still unsent" % sum(ticket <= target for ticket in self._pending))
|
|
231
|
+
return
|
|
232
|
+
self._cond.wait(remaining)
|
|
233
|
+
|
|
234
|
+
@_never_raises
|
|
235
|
+
def shutdown(self) -> None:
|
|
236
|
+
"""Flush, then stop the sender thread. Spans created afterwards are not sent. Runs at process exit."""
|
|
237
|
+
if self._stop.is_set():
|
|
238
|
+
return
|
|
239
|
+
self.flush()
|
|
240
|
+
with self._cond:
|
|
241
|
+
self._stop.set()
|
|
242
|
+
self._cond.notify_all()
|
|
243
|
+
if threading.current_thread() is not self._thread:
|
|
244
|
+
self._thread.join(timeout=2.0)
|
|
245
|
+
atexit.unregister(self.shutdown)
|
|
246
|
+
|
|
247
|
+
def _enqueue(self, span: dict) -> None:
|
|
248
|
+
if self._stop.is_set() or self._disabled:
|
|
249
|
+
return
|
|
250
|
+
encoded = self._encode(span) # now, so that later changes to a caller's input object are not sent
|
|
251
|
+
if encoded is None:
|
|
252
|
+
return
|
|
253
|
+
with self._cond:
|
|
254
|
+
if self._stop.is_set() or self._disabled:
|
|
255
|
+
return
|
|
256
|
+
if len(encoded) + 12 > _MAX_BODY_BYTES:
|
|
257
|
+
if not self._overflow_reported:
|
|
258
|
+
self._overflow_reported = True
|
|
259
|
+
_log("copy exceeds request byte limit; dropping it")
|
|
260
|
+
return
|
|
261
|
+
if len(encoded) > _MAX_QUEUE_BYTES:
|
|
262
|
+
# Larger than the whole queue could ever hold: drop it alone. Evicting queued spans for it would lose them for nothing.
|
|
263
|
+
if not self._overflow_reported:
|
|
264
|
+
self._overflow_reported = True
|
|
265
|
+
_log("span %r is larger than the queue limit; dropping it" % span["name"])
|
|
266
|
+
return
|
|
267
|
+
dropped = 0
|
|
268
|
+
while self._queue and (len(self._queue) >= _MAX_QUEUE_SPANS or self._queue_bytes + len(encoded) > _MAX_QUEUE_BYTES):
|
|
269
|
+
item = self._queue.popleft()
|
|
270
|
+
self._queue_bytes -= len(item[0])
|
|
271
|
+
self._pending.discard(item[3])
|
|
272
|
+
self._processed += 1
|
|
273
|
+
dropped += 1
|
|
274
|
+
if dropped and not self._overflow_reported:
|
|
275
|
+
self._overflow_reported = True
|
|
276
|
+
_log("queue full; dropping oldest spans to keep tracing memory bounded")
|
|
277
|
+
if dropped:
|
|
278
|
+
self._cond.notify_all()
|
|
279
|
+
self._queue.append((encoded, span["name"], span["span_id"], self._enqueued + 1))
|
|
280
|
+
self._pending.add(self._enqueued + 1)
|
|
281
|
+
self._queue_bytes += len(encoded)
|
|
282
|
+
self._enqueued += 1
|
|
283
|
+
if len(self._queue) == 1 or len(self._queue) >= self._max_batch:
|
|
284
|
+
self._cond.notify_all() # wake an idle sender, or one holding a batch open that is now full
|
|
285
|
+
|
|
286
|
+
def _run(self) -> None:
|
|
287
|
+
while True:
|
|
288
|
+
with self._cond:
|
|
289
|
+
if self._stop.is_set():
|
|
290
|
+
self._processed += len(self._queue)
|
|
291
|
+
for item in self._queue:
|
|
292
|
+
self._pending.discard(item[3])
|
|
293
|
+
self._queue.clear()
|
|
294
|
+
self._queue_bytes = 0
|
|
295
|
+
self._cond.notify_all()
|
|
296
|
+
return
|
|
297
|
+
while not self._queue:
|
|
298
|
+
if self._stop.is_set():
|
|
299
|
+
return
|
|
300
|
+
self._flush_requested = False
|
|
301
|
+
self._cond.wait()
|
|
302
|
+
# Hold the batch open for flush_interval, unless it fills up or a flush or shutdown asks for it now.
|
|
303
|
+
deadline = time.monotonic() + self._flush_interval
|
|
304
|
+
while len(self._queue) < self._max_batch and not self._flush_requested and not self._stop.is_set():
|
|
305
|
+
remaining = deadline - time.monotonic()
|
|
306
|
+
if remaining <= 0:
|
|
307
|
+
break
|
|
308
|
+
self._cond.wait(remaining)
|
|
309
|
+
batch = self._take_batch()
|
|
310
|
+
try:
|
|
311
|
+
self._send(batch)
|
|
312
|
+
except Exception as exc:
|
|
313
|
+
_log("dropped %d span(s): %s: %s" % (len(batch), type(exc).__name__, "internal tracing error"))
|
|
314
|
+
finally:
|
|
315
|
+
with self._cond:
|
|
316
|
+
self._processed += len(batch)
|
|
317
|
+
for item in batch:
|
|
318
|
+
self._pending.discard(item[3])
|
|
319
|
+
self._cond.notify_all()
|
|
320
|
+
|
|
321
|
+
def _take_batch(self) -> list:
|
|
322
|
+
"""Pops the next batch off the queue (call with the lock held): at most ``max_batch`` spans, and no more
|
|
323
|
+
than fit in a request body of _MAX_BODY_BYTES. A span that is too big for that alone is still sent, alone."""
|
|
324
|
+
batch = []
|
|
325
|
+
size = len('{"spans":[]}')
|
|
326
|
+
while self._queue and len(batch) < self._max_batch:
|
|
327
|
+
size += len(self._queue[0][0]) + 1 # the JSON text is ASCII, so its length is its bytes; 1 for the comma
|
|
328
|
+
if batch and size > _MAX_BODY_BYTES:
|
|
329
|
+
break
|
|
330
|
+
item = self._queue.popleft()
|
|
331
|
+
self._queue_bytes -= len(item[0])
|
|
332
|
+
batch.append(item)
|
|
333
|
+
return batch
|
|
334
|
+
|
|
335
|
+
def _send(self, batch: list) -> None:
|
|
336
|
+
body = ('{"spans":[' + ",".join(item[0] for item in batch) + "]}").encode("utf-8")
|
|
337
|
+
attempt = 0
|
|
338
|
+
while True:
|
|
339
|
+
finished, problem, wait = self._post_once(body, batch)
|
|
340
|
+
if finished:
|
|
341
|
+
return
|
|
342
|
+
if wait is None and attempt < len(self._retry_delays):
|
|
343
|
+
wait = self._retry_delays[attempt]
|
|
344
|
+
if attempt >= len(self._retry_delays) or self._stop.wait(wait):
|
|
345
|
+
break # out of retries, or the tracer is shutting down
|
|
346
|
+
attempt += 1
|
|
347
|
+
_log("dropped %d span(s) after %d attempt(s): %s" % (len(batch), attempt + 1, problem))
|
|
348
|
+
|
|
349
|
+
def _post_once(self, body: bytes, batch: list):
|
|
350
|
+
"""One POST. Returns (True, "", None) when the batch is settled, (False, why, wait) when it is worth retrying:
|
|
351
|
+
``wait`` is the seconds the server asked for (a 429), or None to use the next retry delay."""
|
|
352
|
+
request = urllib.request.Request(self._endpoint, data=body, method="POST", headers={
|
|
353
|
+
"Authorization": "Bearer " + self._api_key, "Content-Type": "application/json",
|
|
354
|
+
"User-Agent": _USER_AGENT})
|
|
355
|
+
try:
|
|
356
|
+
with self._opener.open(request, timeout=self._timeout) as response:
|
|
357
|
+
self._log_rejections(response.read(65536), batch)
|
|
358
|
+
return True, "", None
|
|
359
|
+
except urllib.error.HTTPError as err: # any status of 300 or more
|
|
360
|
+
try:
|
|
361
|
+
err.read(65536)
|
|
362
|
+
message = "request refused"
|
|
363
|
+
except OSError:
|
|
364
|
+
message = ""
|
|
365
|
+
finally:
|
|
366
|
+
err.close()
|
|
367
|
+
if err.code == 429:
|
|
368
|
+
return False, "HTTP 429: %s" % message, _retry_after(err.headers)
|
|
369
|
+
if err.code in (401, 403):
|
|
370
|
+
self._disable("HTTP %d: access denied" % err.code)
|
|
371
|
+
return True, "", None
|
|
372
|
+
if err.code >= 500:
|
|
373
|
+
return False, "HTTP %d: %s" % (err.code, message), None
|
|
374
|
+
_log("server refused %d span(s) (HTTP %d, not retried): %s" % (len(batch), err.code, message))
|
|
375
|
+
return True, "", None
|
|
376
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException) as err:
|
|
377
|
+
return False, "network error", None
|
|
378
|
+
|
|
379
|
+
def _disable(self, message: str) -> None:
|
|
380
|
+
"""The server said 403: report it once, drop what is queued, and drop every span from now on."""
|
|
381
|
+
with self._cond:
|
|
382
|
+
if self._disabled:
|
|
383
|
+
return
|
|
384
|
+
self._disabled = True
|
|
385
|
+
self._processed += len(self._queue) # dropped, so a flush() waiting on them is released
|
|
386
|
+
for item in self._queue:
|
|
387
|
+
self._pending.discard(item[3])
|
|
388
|
+
self._queue.clear()
|
|
389
|
+
self._queue_bytes = 0
|
|
390
|
+
self._cond.notify_all()
|
|
391
|
+
_log("%s; not sending further spans" % message)
|
|
392
|
+
|
|
393
|
+
def _log_rejections(self, payload: bytes, batch: list) -> None:
|
|
394
|
+
if not self._debug:
|
|
395
|
+
return
|
|
396
|
+
try:
|
|
397
|
+
rejected = json.loads(payload).get("rejected") or []
|
|
398
|
+
for item in rejected:
|
|
399
|
+
_log("server rejected span at batch index %s" % item.get("index"))
|
|
400
|
+
except Exception:
|
|
401
|
+
pass
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cloudbyte-tracer
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CloudByte agent observability tracing
|
|
5
|
+
Project-URL: Homepage, https://github.com/CloudByte-AI/cloudbyte_tracer
|
|
6
|
+
Project-URL: Documentation, https://github.com/CloudByte-AI/cloudbyte_tracer/tree/main/docs
|
|
7
|
+
Project-URL: Source, https://github.com/CloudByte-AI/cloudbyte_tracer
|
|
8
|
+
Project-URL: Issues, https://github.com/CloudByte-AI/cloudbyte_tracer/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/CloudByte-AI/cloudbyte_tracer/releases
|
|
10
|
+
Author: CloudByte
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: ai-agents,cloudbyte,llm,observability,openinference,opentelemetry,tracing
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: System :: Monitoring
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Provides-Extra: all
|
|
27
|
+
Requires-Dist: openinference-instrumentation-anthropic<4,>=3.3.9; extra == 'all'
|
|
28
|
+
Requires-Dist: openinference-instrumentation-langchain<0.2,>=0.1.90; extra == 'all'
|
|
29
|
+
Requires-Dist: openinference-instrumentation-openai<0.2,>=0.1.77; extra == 'all'
|
|
30
|
+
Requires-Dist: openinference-instrumentation<0.2,>=0.1.83; extra == 'all'
|
|
31
|
+
Requires-Dist: opentelemetry-sdk<2,>=1.45; extra == 'all'
|
|
32
|
+
Provides-Extra: anthropic
|
|
33
|
+
Requires-Dist: openinference-instrumentation-anthropic<4,>=3.3.9; extra == 'anthropic'
|
|
34
|
+
Requires-Dist: openinference-instrumentation<0.2,>=0.1.83; extra == 'anthropic'
|
|
35
|
+
Requires-Dist: opentelemetry-sdk<2,>=1.45; extra == 'anthropic'
|
|
36
|
+
Provides-Extra: langchain
|
|
37
|
+
Requires-Dist: openinference-instrumentation-langchain<0.2,>=0.1.90; extra == 'langchain'
|
|
38
|
+
Requires-Dist: openinference-instrumentation<0.2,>=0.1.83; extra == 'langchain'
|
|
39
|
+
Requires-Dist: opentelemetry-sdk<2,>=1.45; extra == 'langchain'
|
|
40
|
+
Provides-Extra: openai
|
|
41
|
+
Requires-Dist: openinference-instrumentation-openai<0.2,>=0.1.77; extra == 'openai'
|
|
42
|
+
Requires-Dist: openinference-instrumentation<0.2,>=0.1.83; extra == 'openai'
|
|
43
|
+
Requires-Dist: opentelemetry-sdk<2,>=1.45; extra == 'openai'
|
|
44
|
+
Provides-Extra: test
|
|
45
|
+
Requires-Dist: anthropic; extra == 'test'
|
|
46
|
+
Requires-Dist: build; extra == 'test'
|
|
47
|
+
Requires-Dist: httpx; extra == 'test'
|
|
48
|
+
Requires-Dist: langchain-openai; extra == 'test'
|
|
49
|
+
Requires-Dist: langgraph; extra == 'test'
|
|
50
|
+
Requires-Dist: openai; extra == 'test'
|
|
51
|
+
Requires-Dist: pytest-asyncio; extra == 'test'
|
|
52
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
53
|
+
Description-Content-Type: text/markdown
|
|
54
|
+
|
|
55
|
+
# cloudbyte-tracer
|
|
56
|
+
|
|
57
|
+
Python and Node.js SDKs for CloudByte Agent Observability, version 0.1.0. One trace is one run. Manual steps and optional OpenInference integrations record the step tree, models, token usage, content and errors.
|
|
58
|
+
|
|
59
|
+
Requires Python 3.10+ or Node.js 20+. Core has zero runtime dependencies. Auto-capture supports OpenAI, Anthropic and LangChain/LangGraph. Content capture is enabled by default.
|
|
60
|
+
|
|
61
|
+
## Install a local build
|
|
62
|
+
|
|
63
|
+
Distribution is undecided. These packages work from local files or an internal artifact server; no registry is required.
|
|
64
|
+
|
|
65
|
+
~~~sh
|
|
66
|
+
pip install ./cloudbyte_tracer-0.1.0-py3-none-any.whl
|
|
67
|
+
npm install ./cloudbyte-tracer-0.1.0.tgz
|
|
68
|
+
~~~
|
|
69
|
+
|
|
70
|
+
Set CLOUDBYTE_AGENT_KEY and CLOUDBYTE_BASE_URL in your application's environment. Do not paste keys into source files. The URL defaults to https://api.cloudbyte.ai.
|
|
71
|
+
|
|
72
|
+
~~~python
|
|
73
|
+
from cloudbyte_tracer import init
|
|
74
|
+
tracer = init()
|
|
75
|
+
with tracer.span("request", kind="agent", input={"question": "hello"}) as run:
|
|
76
|
+
with tracer.span("lookup", kind="tool") as step:
|
|
77
|
+
step.set_output({"answer": "hello"})
|
|
78
|
+
run.set_output("hello")
|
|
79
|
+
tracer.shutdown()
|
|
80
|
+
~~~
|
|
81
|
+
|
|
82
|
+
~~~js
|
|
83
|
+
import { init } from "cloudbyte-tracer";
|
|
84
|
+
const tracer = init();
|
|
85
|
+
await tracer.withSpan("request", { kind: "agent" }, async run => {
|
|
86
|
+
await tracer.withSpan("lookup", { kind: "tool" }, step => step.setOutput("hello"));
|
|
87
|
+
run.setOutput("hello");
|
|
88
|
+
});
|
|
89
|
+
await tracer.shutdown();
|
|
90
|
+
~~~
|
|
91
|
+
|
|
92
|
+
## Documentation
|
|
93
|
+
|
|
94
|
+
- [Getting started](../docs/getting-started.md)
|
|
95
|
+
- [Manual tracing](../docs/manual-tracing.md)
|
|
96
|
+
- [Auto-capture](../docs/auto-capture.md)
|
|
97
|
+
- [Configuration and limits](../docs/configuration.md)
|
|
98
|
+
- [Privacy and redaction](../docs/privacy-and-redaction.md)
|
|
99
|
+
- [Troubleshooting](../docs/troubleshooting.md)
|
|
100
|
+
- [Development, tests and releases](CONTRIBUTING.md)
|
|
101
|
+
|
|
102
|
+
All provider examples use mocked responses by default and require no provider keys. Set CLOUDBYTE_DISABLED=true for completely offline execution. With a CloudByte key configured, they send traces to your selected endpoint.
|
|
103
|
+
|
|
104
|
+
## Delivery guarantees
|
|
105
|
+
|
|
106
|
+
Sending is best effort, with a bounded in-memory queue and retry budget. Shutdown flushes with a deadline; delivery is not durable. Root spans send start and end copies, children send only end copies. A 401 or 403 stops that tracer permanently; restart after correcting access.
|
|
107
|
+
|
|
108
|
+
Apache-2.0. No SDK packages have been published by this work.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
cloudbyte_tracer/__init__.py,sha256=ddtshda65JKbyTF15neWHfMsSDD0Hts_k5_l3hku6Qc,1481
|
|
2
|
+
cloudbyte_tracer/_version.py,sha256=kyt2K9GwagKVWlC9jDF0uQJWeUtUzhxeRXVq6_5NPQw,424
|
|
3
|
+
cloudbyte_tracer/context.py,sha256=UA8SQdOGGedcsEiZUuYqNQTCYUs3s3ebzLyNwsLaGzM,275
|
|
4
|
+
cloudbyte_tracer/core.py,sha256=iXRg7EydYulD3NLWamMbGrX_COEkcTWyVnvqCxP_RjM,9678
|
|
5
|
+
cloudbyte_tracer/limits.py,sha256=aSZtVNCk_34V0l5mMdNRBFidv4qvIXeRFJ65MFJ3c0U,2989
|
|
6
|
+
cloudbyte_tracer/redact.py,sha256=aYBos6IQVXgpooM2_Wjz8h5QSHRQ7YOaAsOvx-cbpek,223
|
|
7
|
+
cloudbyte_tracer/transport.py,sha256=_v4bIaX9qCZYozKNM_dj62soHNBKDh4S8L2jPvtCOM8,18473
|
|
8
|
+
cloudbyte_tracer/otel/__init__.py,sha256=bSzuq4IK0-F2LKiO5n4_xfynzolSFoz256fYqvybDYY,65
|
|
9
|
+
cloudbyte_tracer/otel/context.py,sha256=cCle7mDjVD-JR2n7wkyd76T2ocBSV6d1Fb54VMVlO-E,1588
|
|
10
|
+
cloudbyte_tracer/otel/exporter.py,sha256=E9c7bq1RdC7Krs_q_fjmGYu58rjGRZTnSYxvhKL9uWI,584
|
|
11
|
+
cloudbyte_tracer/otel/instrument.py,sha256=im9Xw6uIGeEDEiOs0lpiHOxUjogrTMaU2WQ829AUktI,5120
|
|
12
|
+
cloudbyte_tracer/otel/mapping.py,sha256=LUgBSTipB4Qw9QdY0BJ-CRqJ84oDY-5vO7Vci8ICWS8,3946
|
|
13
|
+
cloudbyte_tracer/otel/processor.py,sha256=EDPWTVTDnQagFXBrufPmseePLzWdg63kVy5EkXuHWjo,1083
|
|
14
|
+
cloudbyte_tracer-0.1.0.dist-info/METADATA,sha256=GiTpJCe1j8lTUjo9e4dKOxIVo-oXv2Ffl0VwlkaImLU,5136
|
|
15
|
+
cloudbyte_tracer-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
16
|
+
cloudbyte_tracer-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
17
|
+
cloudbyte_tracer-0.1.0.dist-info/RECORD,,
|