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,44 @@
|
|
|
1
|
+
"""CloudByte tracing. Core has no runtime dependencies."""
|
|
2
|
+
from ._version import SDK_VERSION as __version__
|
|
3
|
+
from .core import Tracer, Span
|
|
4
|
+
from .context import bind_context
|
|
5
|
+
_default = None
|
|
6
|
+
|
|
7
|
+
def init(api_key=None, base_url=None, **options):
|
|
8
|
+
global _default
|
|
9
|
+
if _default is not None:
|
|
10
|
+
_default.shutdown()
|
|
11
|
+
_default = Tracer(api_key, base_url, **options)
|
|
12
|
+
return _default
|
|
13
|
+
|
|
14
|
+
def get_tracer():
|
|
15
|
+
global _default
|
|
16
|
+
if _default is None:
|
|
17
|
+
_default = Tracer()
|
|
18
|
+
return _default
|
|
19
|
+
|
|
20
|
+
def trace(fn=None, *, name=None, kind="custom"):
|
|
21
|
+
def decorate(func):
|
|
22
|
+
# Resolve the process default at call time so decorators work before init().
|
|
23
|
+
import functools, inspect
|
|
24
|
+
if inspect.iscoroutinefunction(func):
|
|
25
|
+
@functools.wraps(func)
|
|
26
|
+
async def wrapped(*args, **kwargs):
|
|
27
|
+
with get_tracer().span(name or func.__name__, kind=kind):
|
|
28
|
+
return await func(*args, **kwargs)
|
|
29
|
+
else:
|
|
30
|
+
@functools.wraps(func)
|
|
31
|
+
def wrapped(*args, **kwargs):
|
|
32
|
+
with get_tracer().span(name or func.__name__, kind=kind):
|
|
33
|
+
return func(*args, **kwargs)
|
|
34
|
+
return wrapped
|
|
35
|
+
return decorate(fn) if fn is not None else decorate
|
|
36
|
+
|
|
37
|
+
def flush(timeout=5.0):
|
|
38
|
+
return get_tracer().flush(timeout)
|
|
39
|
+
|
|
40
|
+
def shutdown():
|
|
41
|
+
if _default is not None:
|
|
42
|
+
_default.shutdown()
|
|
43
|
+
|
|
44
|
+
__all__ = ["Tracer", "Span", "init", "get_tracer", "trace", "flush", "shutdown", "bind_context"]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""The installed SDK version, read once from package metadata.
|
|
2
|
+
|
|
3
|
+
Kept in its own module so the transport can read it without importing the package's __init__ (which imports the transport).
|
|
4
|
+
"""
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
SDK_VERSION = version("cloudbyte-tracer")
|
|
9
|
+
except PackageNotFoundError: # imported from a source checkout that was never installed
|
|
10
|
+
SDK_VERSION = "0+unknown"
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Threads do not inherit Python context. Copy it explicitly when submitting work."""
|
|
2
|
+
from contextvars import copy_context
|
|
3
|
+
|
|
4
|
+
def bind_context(fn):
|
|
5
|
+
context = copy_context()
|
|
6
|
+
def run(*args, **kwargs):
|
|
7
|
+
return context.copy().run(fn, *args, **kwargs)
|
|
8
|
+
return run
|
cloudbyte_tracer/core.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import os, functools, inspect
|
|
3
|
+
from typing import Optional
|
|
4
|
+
from .transport import Transport, _log, _never_raises, _text, _clamp, _clean_attributes, _attribute_value, _now, _KINDS, _STATUSES
|
|
5
|
+
import uuid, numbers
|
|
6
|
+
from .limits import encode
|
|
7
|
+
class Span:
|
|
8
|
+
"""One timed step of an agent run. Created by ``Tracer.span()``; use it as a context manager.
|
|
9
|
+
|
|
10
|
+
Leaving the ``with`` block normally gives the span status ``ok`` unless ``set_status()`` chose another;
|
|
11
|
+
an exception gives it status ``error`` (with the exception's type and message) and is re-raised unchanged.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
trace_id: str
|
|
15
|
+
span_id: str
|
|
16
|
+
parent_span_id: Optional[str]
|
|
17
|
+
|
|
18
|
+
def __init__(self, tracer: "Tracer", name, kind, parent: Optional["Span"], input, model, attributes) -> None:
|
|
19
|
+
self._tracer = tracer
|
|
20
|
+
self._parent = parent
|
|
21
|
+
self.trace_id = parent.trace_id if parent is not None else uuid.uuid4().hex
|
|
22
|
+
self.span_id = uuid.uuid4().hex[:16]
|
|
23
|
+
self.parent_span_id = parent.span_id if parent is not None else None
|
|
24
|
+
self._name = _clamp(_text(name)) or "span"
|
|
25
|
+
if kind not in _KINDS:
|
|
26
|
+
_log("unknown span kind %r for span %r; using 'custom'" % (kind, self._name))
|
|
27
|
+
kind = "custom"
|
|
28
|
+
self._kind = kind
|
|
29
|
+
self._input = input if tracer._capture_content else None
|
|
30
|
+
self._output = None
|
|
31
|
+
self._model = None if model is None else _clamp(_text(model))
|
|
32
|
+
self._attributes = _clean_attributes(attributes)
|
|
33
|
+
self._usage: dict = {}
|
|
34
|
+
self._status: Optional[str] = None
|
|
35
|
+
self._error: Optional[dict] = None
|
|
36
|
+
self._started_at: Optional[str] = None
|
|
37
|
+
self._token = None
|
|
38
|
+
|
|
39
|
+
def __enter__(self) -> "Span":
|
|
40
|
+
try:
|
|
41
|
+
self._started_at = _now()
|
|
42
|
+
self._token = self._tracer._current.set(self)
|
|
43
|
+
if self._tracer._bridge is not None:
|
|
44
|
+
self._otel_span, self._otel_context = self._tracer._bridge.start(self)
|
|
45
|
+
ctx = self._otel_span.get_span_context()
|
|
46
|
+
self.trace_id, self.span_id = format(ctx.trace_id, "032x"), format(ctx.span_id, "016x")
|
|
47
|
+
parent = self._otel_span.parent
|
|
48
|
+
self.parent_span_id = format(parent.span_id, "016x") if parent else None
|
|
49
|
+
elif self.parent_span_id is None:
|
|
50
|
+
self._tracer._enqueue(self._start_copy())
|
|
51
|
+
except Exception as exc:
|
|
52
|
+
_log("could not start span %r: %s" % (self._name, exc))
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def __exit__(self, exc_type, exc, traceback) -> bool:
|
|
56
|
+
try:
|
|
57
|
+
if exc_type is not None:
|
|
58
|
+
self._status = "error"
|
|
59
|
+
self._error = {"type": exc_type.__name__, "message": _text(exc)}
|
|
60
|
+
self._restore_current()
|
|
61
|
+
if getattr(self, "_otel_span", None) is not None:
|
|
62
|
+
self._tracer._bridge.end(self, exc)
|
|
63
|
+
else:
|
|
64
|
+
self._tracer._enqueue(self._end_copy())
|
|
65
|
+
except Exception as err:
|
|
66
|
+
_log("could not finish span %r: %s" % (self._name, err))
|
|
67
|
+
return False # never swallow the traced code's exception
|
|
68
|
+
|
|
69
|
+
@_never_raises
|
|
70
|
+
def set_output(self, value) -> None:
|
|
71
|
+
if self._tracer._capture_content:
|
|
72
|
+
self._output = value
|
|
73
|
+
|
|
74
|
+
@_never_raises
|
|
75
|
+
def set_usage(self, *, input_tokens=None, output_tokens=None, cache_read_tokens=None, cache_write_tokens=None) -> None:
|
|
76
|
+
given = {"input_tokens": input_tokens, "output_tokens": output_tokens,
|
|
77
|
+
"cache_read_tokens": cache_read_tokens, "cache_write_tokens": cache_write_tokens}
|
|
78
|
+
for key, value in given.items():
|
|
79
|
+
if value is None:
|
|
80
|
+
continue
|
|
81
|
+
if isinstance(value, numbers.Integral) and not isinstance(value, bool) and value >= 0:
|
|
82
|
+
self._usage[key] = min(int(value), 2147483647)
|
|
83
|
+
else:
|
|
84
|
+
_log("ignoring %s=%r on span %r: it must be a non-negative integer" % (key, value, self._name))
|
|
85
|
+
|
|
86
|
+
@_never_raises
|
|
87
|
+
def set_attribute(self, key: str, value) -> None:
|
|
88
|
+
self._attributes[_text(key)] = _attribute_value(value)
|
|
89
|
+
|
|
90
|
+
@_never_raises
|
|
91
|
+
def set_status(self, status: str, *, error_type=None, error_message=None) -> None:
|
|
92
|
+
if status not in _STATUSES:
|
|
93
|
+
_log("ignoring status %r on span %r; use 'ok', 'error' or 'unset'" % (status, self._name))
|
|
94
|
+
return
|
|
95
|
+
self._status = status
|
|
96
|
+
if status != "error":
|
|
97
|
+
self._error = None
|
|
98
|
+
elif error_type is not None or error_message is not None:
|
|
99
|
+
self._error = {"type": "Error" if error_type is None else _text(error_type),
|
|
100
|
+
"message": "" if error_message is None else _text(error_message)}
|
|
101
|
+
|
|
102
|
+
@_never_raises
|
|
103
|
+
def record_error(self, exc) -> None:
|
|
104
|
+
self._status = "error"
|
|
105
|
+
self._error = {"type": type(exc).__name__, "message": _text(exc)}
|
|
106
|
+
|
|
107
|
+
def _restore_current(self) -> None:
|
|
108
|
+
token, self._token = self._token, None
|
|
109
|
+
if token is None:
|
|
110
|
+
return
|
|
111
|
+
try:
|
|
112
|
+
self._tracer._current.reset(token)
|
|
113
|
+
except (ValueError, RuntimeError): # the block exits in a different context than it entered
|
|
114
|
+
self._tracer._current.set(self._parent)
|
|
115
|
+
|
|
116
|
+
def _identity(self) -> dict:
|
|
117
|
+
return {"trace_id": self.trace_id, "span_id": self.span_id, "parent_span_id": self.parent_span_id,
|
|
118
|
+
"kind": self._kind, "name": self._name, "started_at": self._started_at}
|
|
119
|
+
|
|
120
|
+
def _start_copy(self) -> dict:
|
|
121
|
+
# The server merges re-sent copies field by field and keeps a stored value when a field is absent, so
|
|
122
|
+
# this copy must not carry status, output, usage or error: if it arrived late it would overwrite them.
|
|
123
|
+
copy = self._identity()
|
|
124
|
+
copy["ended_at"] = None
|
|
125
|
+
if self._input is not None:
|
|
126
|
+
copy["input"] = self._input
|
|
127
|
+
if self._model is not None:
|
|
128
|
+
copy["model"] = self._model
|
|
129
|
+
if self._attributes:
|
|
130
|
+
copy["attributes"] = self._attributes
|
|
131
|
+
return copy
|
|
132
|
+
|
|
133
|
+
def _end_copy(self) -> dict:
|
|
134
|
+
copy = self._identity()
|
|
135
|
+
copy["ended_at"] = _now()
|
|
136
|
+
copy["status"] = self._status or "ok"
|
|
137
|
+
if self._error is not None:
|
|
138
|
+
copy["error"] = self._error
|
|
139
|
+
if self._model is not None:
|
|
140
|
+
copy["model"] = self._model
|
|
141
|
+
if self._usage:
|
|
142
|
+
copy["usage"] = self._usage
|
|
143
|
+
if self._input is not None:
|
|
144
|
+
copy["input"] = self._input
|
|
145
|
+
if self._output is not None:
|
|
146
|
+
copy["output"] = self._output
|
|
147
|
+
if self._attributes:
|
|
148
|
+
copy["attributes"] = self._attributes
|
|
149
|
+
return copy
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class Tracer(Transport):
|
|
154
|
+
"""Manual tracer; optional OpenInference integrations use the same bounded sender."""
|
|
155
|
+
def __init__(self, api_key=None, base_url=None, *, capture_content=None, redact=None,
|
|
156
|
+
service_name=None, auto_capture=None, debug=False, tracer_provider=None, **options):
|
|
157
|
+
self._debug = debug
|
|
158
|
+
self._redact = redact
|
|
159
|
+
self._bridge = None
|
|
160
|
+
self._service_name = service_name
|
|
161
|
+
key = api_key if api_key is not None else os.getenv("CLOUDBYTE_AGENT_KEY")
|
|
162
|
+
disabled = os.getenv("CLOUDBYTE_DISABLED", "").lower() in ("1", "true", "yes", "on")
|
|
163
|
+
missing = not isinstance(key, str) or not key.strip()
|
|
164
|
+
if capture_content is None:
|
|
165
|
+
capture_content = os.getenv("CLOUDBYTE_CAPTURE_CONTENT", "true").lower() not in ("0", "false", "no", "off")
|
|
166
|
+
try:
|
|
167
|
+
super().__init__(key if not missing else "disabled", base_url or os.getenv("CLOUDBYTE_BASE_URL", "https://api.cloudbyte.ai"), capture_content=capture_content, **options)
|
|
168
|
+
except Exception:
|
|
169
|
+
super().__init__("disabled", "https://api.cloudbyte.ai", capture_content=False)
|
|
170
|
+
disabled = True
|
|
171
|
+
if missing or disabled:
|
|
172
|
+
self._disabled = True
|
|
173
|
+
_log("tracing disabled (missing key or disabled configuration)")
|
|
174
|
+
elif auto_capture or tracer_provider is not None:
|
|
175
|
+
try:
|
|
176
|
+
from .otel.instrument import Bridge
|
|
177
|
+
self._bridge = Bridge(self, auto_capture, tracer_provider)
|
|
178
|
+
except Exception:
|
|
179
|
+
_log("auto-capture unavailable; check optional dependencies")
|
|
180
|
+
|
|
181
|
+
def _encode(self, span):
|
|
182
|
+
return encode(span, self._capture_content, self._redact, self._service_name)
|
|
183
|
+
|
|
184
|
+
def span(self, name, kind="custom", *, input=None, model=None, attributes=None, parent=None):
|
|
185
|
+
explicit_parent = parent if isinstance(parent, Span) else None
|
|
186
|
+
parent = explicit_parent or self._current.get()
|
|
187
|
+
span = Span(self, name, kind, parent, input, model, attributes)
|
|
188
|
+
span._explicit_parent = explicit_parent
|
|
189
|
+
return span
|
|
190
|
+
|
|
191
|
+
def trace(self, fn=None, *, name=None, kind="custom"):
|
|
192
|
+
def decorate(func):
|
|
193
|
+
if inspect.iscoroutinefunction(func):
|
|
194
|
+
@functools.wraps(func)
|
|
195
|
+
async def wrapped(*args, **kwargs):
|
|
196
|
+
with self.span(name or func.__name__, kind=kind):
|
|
197
|
+
return await func(*args, **kwargs)
|
|
198
|
+
else:
|
|
199
|
+
@functools.wraps(func)
|
|
200
|
+
def wrapped(*args, **kwargs):
|
|
201
|
+
with self.span(name or func.__name__, kind=kind):
|
|
202
|
+
return func(*args, **kwargs)
|
|
203
|
+
return wrapped
|
|
204
|
+
return decorate(fn) if fn is not None else decorate
|
|
205
|
+
|
|
206
|
+
def shutdown(self):
|
|
207
|
+
if self._bridge is not None:
|
|
208
|
+
try:
|
|
209
|
+
self._bridge.shutdown()
|
|
210
|
+
except Exception:
|
|
211
|
+
_log("auto-capture shutdown failed")
|
|
212
|
+
self._bridge = None
|
|
213
|
+
super().shutdown()
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Wire sanitation. Keep the existing server's truncation detection working."""
|
|
2
|
+
import json, math
|
|
3
|
+
from .redact import apply
|
|
4
|
+
|
|
5
|
+
MAX_FIELD_BYTES = 65536
|
|
6
|
+
MAX_ATTRIBUTES_BYTES = 32768
|
|
7
|
+
|
|
8
|
+
def dumps(value):
|
|
9
|
+
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"), default=str)
|
|
10
|
+
|
|
11
|
+
def fit(value):
|
|
12
|
+
try:
|
|
13
|
+
text = dumps(value)
|
|
14
|
+
if len(text.encode("utf-8", "replace")) <= MAX_FIELD_BYTES:
|
|
15
|
+
return json.loads(text), False
|
|
16
|
+
except Exception:
|
|
17
|
+
try:
|
|
18
|
+
text = repr(value)
|
|
19
|
+
except Exception:
|
|
20
|
+
text = "<unserializable>"
|
|
21
|
+
# The server ignores incoming *_truncated. A bounded 70 KB prefix triggers its
|
|
22
|
+
# own flag, just like the Preview helper. See docs/configuration.md.
|
|
23
|
+
return text[:70000].encode("utf-8", "replace")[:70000].decode("utf-8", "ignore"), True
|
|
24
|
+
|
|
25
|
+
def encode(span, capture_content=True, redact=None, service_name=None):
|
|
26
|
+
try:
|
|
27
|
+
copy = dict(span)
|
|
28
|
+
for field in ("input", "output"):
|
|
29
|
+
if field not in copy:
|
|
30
|
+
continue
|
|
31
|
+
raw = copy.pop(field)
|
|
32
|
+
value = apply(raw, field, span, redact) if capture_content else None
|
|
33
|
+
if value is not None:
|
|
34
|
+
copy[field], truncated = fit(value)
|
|
35
|
+
if truncated:
|
|
36
|
+
copy[field + "_truncated"] = True
|
|
37
|
+
attrs = dict(copy.get("attributes") or {})
|
|
38
|
+
if service_name:
|
|
39
|
+
attrs["service.name"] = service_name
|
|
40
|
+
cleaned = {}
|
|
41
|
+
for k, v in attrs.items():
|
|
42
|
+
if isinstance(v, str):
|
|
43
|
+
v = apply(v, "attributes." + str(k), span, redact)
|
|
44
|
+
if isinstance(v, (str, bool)) or isinstance(v, (int, float)) and math.isfinite(v):
|
|
45
|
+
cleaned[str(k)] = v
|
|
46
|
+
for key in sorted(cleaned, key=lambda k: len(dumps({k: cleaned[k]}).encode("utf-8", "replace")), reverse=True):
|
|
47
|
+
if len(dumps(cleaned).encode("utf-8", "replace")) <= MAX_ATTRIBUTES_BYTES:
|
|
48
|
+
break
|
|
49
|
+
del cleaned[key]
|
|
50
|
+
if cleaned:
|
|
51
|
+
copy["attributes"] = cleaned
|
|
52
|
+
else:
|
|
53
|
+
copy.pop("attributes", None)
|
|
54
|
+
if copy.get("error"):
|
|
55
|
+
copy["error"] = {"type": str(copy["error"].get("type", "Error")), "message": str(copy["error"].get("message", ""))[:4096]}
|
|
56
|
+
usage = {}
|
|
57
|
+
for k, v in (copy.get("usage") or {}).items():
|
|
58
|
+
if k in ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") and isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v >= 0 and int(v) == v:
|
|
59
|
+
usage[k] = min(int(v), 2147483647)
|
|
60
|
+
if usage:
|
|
61
|
+
copy["usage"] = usage
|
|
62
|
+
else:
|
|
63
|
+
copy.pop("usage", None)
|
|
64
|
+
copy["name"] = str(copy.get("name", "span"))[:200] or "span"
|
|
65
|
+
if copy.get("model") is not None:
|
|
66
|
+
copy["model"] = str(copy["model"])[:200]
|
|
67
|
+
return json.dumps(copy, allow_nan=False, default=str)
|
|
68
|
+
except Exception:
|
|
69
|
+
return None
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional OpenTelemetry/OpenInference bridge (lazy loaded)."""
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Bridge callback-based LangChain spans into ordinary OTel parent context."""
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
from opentelemetry import trace
|
|
4
|
+
|
|
5
|
+
class ContextTracer:
|
|
6
|
+
def __init__(self, tracer, parents):
|
|
7
|
+
self._tracer, self._parents = tracer, parents
|
|
8
|
+
|
|
9
|
+
def _context(self, context):
|
|
10
|
+
try:
|
|
11
|
+
from openinference.instrumentation.langchain import get_current_span
|
|
12
|
+
candidate = get_current_span()
|
|
13
|
+
if candidate is None:
|
|
14
|
+
return context
|
|
15
|
+
current = trace.get_current_span(context).get_span_context()
|
|
16
|
+
cursor = candidate.get_span_context().span_id
|
|
17
|
+
seen = set()
|
|
18
|
+
while cursor and cursor not in seen:
|
|
19
|
+
if cursor == current.span_id:
|
|
20
|
+
return trace.set_span_in_context(candidate, context)
|
|
21
|
+
seen.add(cursor)
|
|
22
|
+
cursor = self._parents.get(cursor)
|
|
23
|
+
except Exception:
|
|
24
|
+
pass
|
|
25
|
+
return context
|
|
26
|
+
|
|
27
|
+
def start_span(self, name, context=None, **kwargs):
|
|
28
|
+
return self._tracer.start_span(name, context=self._context(context), **kwargs)
|
|
29
|
+
|
|
30
|
+
@contextmanager
|
|
31
|
+
def start_as_current_span(self, name, context=None, **kwargs):
|
|
32
|
+
with self._tracer.start_as_current_span(name, context=self._context(context), **kwargs) as span:
|
|
33
|
+
yield span
|
|
34
|
+
|
|
35
|
+
class ContextProvider:
|
|
36
|
+
def __init__(self, provider, parents):
|
|
37
|
+
self.provider, self.parents = provider, parents
|
|
38
|
+
def get_tracer(self, *args, **kwargs):
|
|
39
|
+
return ContextTracer(self.provider.get_tracer(*args, **kwargs), self.parents)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
|
|
2
|
+
from .mapping import map_span
|
|
3
|
+
|
|
4
|
+
class CloudByteSpanExporter(SpanExporter):
|
|
5
|
+
def __init__(self, tracer):
|
|
6
|
+
self.tracer = tracer
|
|
7
|
+
|
|
8
|
+
def export(self, spans):
|
|
9
|
+
for span in spans:
|
|
10
|
+
try:
|
|
11
|
+
self.tracer._enqueue(map_span(span))
|
|
12
|
+
except Exception:
|
|
13
|
+
pass
|
|
14
|
+
return SpanExportResult.SUCCESS
|
|
15
|
+
|
|
16
|
+
def shutdown(self):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
def force_flush(self, timeout_millis=30000):
|
|
20
|
+
self.tracer.flush(timeout_millis / 1000)
|
|
21
|
+
return True
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Private provider, shared OTel context; never replaces the app's provider."""
|
|
2
|
+
import importlib, json
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
from opentelemetry import trace
|
|
5
|
+
from opentelemetry.sdk.trace import TracerProvider
|
|
6
|
+
from opentelemetry.sdk.resources import Resource
|
|
7
|
+
from opentelemetry.trace import Status, StatusCode
|
|
8
|
+
from openinference.instrumentation import TraceConfig
|
|
9
|
+
from .processor import CloudByteSpanProcessor
|
|
10
|
+
from .context import ContextProvider
|
|
11
|
+
from ..transport import _log
|
|
12
|
+
|
|
13
|
+
INTEGRATIONS = {"openai": ("openinference.instrumentation.openai", "OpenAIInstrumentor"),
|
|
14
|
+
"anthropic": ("openinference.instrumentation.anthropic", "AnthropicInstrumentor"),
|
|
15
|
+
"langchain": ("openinference.instrumentation.langchain", "LangChainInstrumentor")}
|
|
16
|
+
_active_bridge = None
|
|
17
|
+
|
|
18
|
+
class Bridge:
|
|
19
|
+
def __init__(self, owner, integrations, provider=None):
|
|
20
|
+
global _active_bridge
|
|
21
|
+
if _active_bridge is not None:
|
|
22
|
+
raise RuntimeError("one auto-capture tracer per process")
|
|
23
|
+
self.owner = owner
|
|
24
|
+
self.owns_provider = provider is None
|
|
25
|
+
self.provider = provider if provider is not None else TracerProvider(resource=Resource.create({"service.name": owner._service_name or "cloudbyte-agent"}), shutdown_on_exit=False)
|
|
26
|
+
self.processor = CloudByteSpanProcessor(owner)
|
|
27
|
+
self.provider.add_span_processor(self.processor)
|
|
28
|
+
self.context_provider = ContextProvider(self.provider, self.processor.parents)
|
|
29
|
+
self.tracer = self.context_provider.get_tracer("cloudbyte_tracer", version("cloudbyte-tracer"))
|
|
30
|
+
self.instrumentors = []
|
|
31
|
+
config = TraceConfig(hide_inputs=not owner._capture_content, hide_outputs=not owner._capture_content, hide_llm_invocation_parameters=not owner._capture_content, hide_llm_tools=not owner._capture_content, hide_retrieval_documents=not owner._capture_content)
|
|
32
|
+
names = INTEGRATIONS if integrations is True else (integrations or [])
|
|
33
|
+
for name in names:
|
|
34
|
+
try:
|
|
35
|
+
mod, cls = INTEGRATIONS[name]
|
|
36
|
+
inst = getattr(importlib.import_module(mod), cls)()
|
|
37
|
+
if inst.is_instrumented_by_opentelemetry:
|
|
38
|
+
_log("integration already instrumented; skipping " + name)
|
|
39
|
+
continue
|
|
40
|
+
inst.instrument(tracer_provider=self.context_provider, config=config)
|
|
41
|
+
if inst.is_instrumented_by_opentelemetry:
|
|
42
|
+
self.instrumentors.append(inst)
|
|
43
|
+
except Exception:
|
|
44
|
+
if integrations is not True:
|
|
45
|
+
_log("integration unavailable: " + str(name))
|
|
46
|
+
_active_bridge = self
|
|
47
|
+
|
|
48
|
+
def start(self, manual):
|
|
49
|
+
attrs = dict(manual._attributes)
|
|
50
|
+
attrs["openinference.span.kind"] = {"agent": "AGENT", "llm": "LLM", "tool": "TOOL", "retrieval": "RETRIEVER"}.get(manual._kind, "UNKNOWN")
|
|
51
|
+
if manual._input is not None and self.owner._capture_content:
|
|
52
|
+
attrs["input.value"] = json.dumps(manual._input, default=str)
|
|
53
|
+
if manual._model is not None:
|
|
54
|
+
attrs["llm.model_name"] = manual._model
|
|
55
|
+
context = None
|
|
56
|
+
if manual._explicit_parent is not None and getattr(manual._explicit_parent, "_otel_span", None) is not None:
|
|
57
|
+
context = trace.set_span_in_context(manual._explicit_parent._otel_span)
|
|
58
|
+
span = self.tracer.start_span(manual._name, context=context, attributes=attrs)
|
|
59
|
+
cm = trace.use_span(span, end_on_exit=False, record_exception=False, set_status_on_exception=False)
|
|
60
|
+
cm.__enter__()
|
|
61
|
+
return span, cm
|
|
62
|
+
|
|
63
|
+
def end(self, manual, exc):
|
|
64
|
+
span = manual._otel_span
|
|
65
|
+
try:
|
|
66
|
+
for k, v in manual._attributes.items():
|
|
67
|
+
span.set_attribute(k, v)
|
|
68
|
+
if manual._output is not None and self.owner._capture_content:
|
|
69
|
+
span.set_attribute("output.value", json.dumps(manual._output, default=str))
|
|
70
|
+
if manual._model is not None:
|
|
71
|
+
span.set_attribute("llm.model_name", manual._model)
|
|
72
|
+
usage = {"input_tokens": "prompt", "output_tokens": "completion", "cache_read_tokens": "prompt_details.cache_read", "cache_write_tokens": "prompt_details.cache_write"}
|
|
73
|
+
for k, v in manual._usage.items():
|
|
74
|
+
span.set_attribute("llm.token_count." + usage[k], v)
|
|
75
|
+
if manual._error:
|
|
76
|
+
span.add_event("exception", {"exception.type": manual._error["type"], "exception.message": manual._error["message"]})
|
|
77
|
+
code = StatusCode.ERROR if manual._status == "error" else StatusCode.UNSET if manual._status == "unset" else StatusCode.OK
|
|
78
|
+
span.set_status(Status(code))
|
|
79
|
+
finally:
|
|
80
|
+
manual._otel_context.__exit__(None, None, None)
|
|
81
|
+
span.end()
|
|
82
|
+
|
|
83
|
+
def shutdown(self):
|
|
84
|
+
global _active_bridge
|
|
85
|
+
self.processor.shutdown()
|
|
86
|
+
for inst in self.instrumentors:
|
|
87
|
+
try:
|
|
88
|
+
inst.uninstrument()
|
|
89
|
+
except Exception:
|
|
90
|
+
pass
|
|
91
|
+
if self.owns_provider:
|
|
92
|
+
self.provider.shutdown()
|
|
93
|
+
if _active_bridge is self:
|
|
94
|
+
_active_bridge = None
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""OpenInference to the existing CloudByte JSON contract."""
|
|
2
|
+
import datetime, json, re
|
|
3
|
+
|
|
4
|
+
KIND_MAP = {"LLM": "llm", "TOOL": "tool", "RETRIEVER": "retrieval", "RERANKER": "retrieval", "AGENT": "agent"}
|
|
5
|
+
USAGE_MAP = {"prompt": "input_tokens", "completion": "output_tokens", "prompt_details.cache_read": "cache_read_tokens", "prompt_details.cache_write": "cache_write_tokens"}
|
|
6
|
+
|
|
7
|
+
def timestamp(ns):
|
|
8
|
+
return datetime.datetime.fromtimestamp(ns / 1e9, datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
9
|
+
|
|
10
|
+
def content(attrs, direction):
|
|
11
|
+
raw = attrs.get(direction + ".value")
|
|
12
|
+
# Message arrays take priority over raw request/response envelopes.
|
|
13
|
+
messages = {}
|
|
14
|
+
pattern = re.compile(r"^llm\." + direction + r"_messages\.(\d+)\.message\.(role|content|contents\.(\d+)\.message_content\.text)$")
|
|
15
|
+
for key, value in attrs.items():
|
|
16
|
+
m = pattern.match(key)
|
|
17
|
+
if not m:
|
|
18
|
+
continue
|
|
19
|
+
item = messages.setdefault(int(m[1]), {})
|
|
20
|
+
if m[2] in ("role", "content"):
|
|
21
|
+
item[m[2]] = value
|
|
22
|
+
else:
|
|
23
|
+
item.setdefault("_parts", {})[int(m[3])] = value
|
|
24
|
+
if messages:
|
|
25
|
+
result = []
|
|
26
|
+
for _, item in sorted(messages.items()):
|
|
27
|
+
parts = item.pop("_parts", {})
|
|
28
|
+
if "content" not in item and parts:
|
|
29
|
+
item["content"] = "".join(str(v) for _, v in sorted(parts.items()))
|
|
30
|
+
result.append(item)
|
|
31
|
+
return result
|
|
32
|
+
if isinstance(raw, str):
|
|
33
|
+
try:
|
|
34
|
+
return json.loads(raw)
|
|
35
|
+
except Exception:
|
|
36
|
+
return raw
|
|
37
|
+
return raw
|
|
38
|
+
|
|
39
|
+
def map_span(span, start=False):
|
|
40
|
+
attrs = dict(span.attributes or {})
|
|
41
|
+
ctx = span.get_span_context()
|
|
42
|
+
parent = span.parent
|
|
43
|
+
parent_id = format(parent.span_id, "016x") if parent and parent.is_valid else None
|
|
44
|
+
oi_kind = str(attrs.get("openinference.span.kind", "")).upper()
|
|
45
|
+
kind = KIND_MAP.get(oi_kind, "agent" if oi_kind == "CHAIN" and parent_id is None else "custom")
|
|
46
|
+
result = {"trace_id": format(ctx.trace_id, "032x"), "span_id": format(ctx.span_id, "016x"), "parent_span_id": parent_id,
|
|
47
|
+
"name": span.name, "kind": kind, "started_at": timestamp(span.start_time), "ended_at": None if start else timestamp(span.end_time)}
|
|
48
|
+
if not start:
|
|
49
|
+
result["status"] = "error" if span.status.status_code.name == "ERROR" else "unset" if span.status.status_code.name == "UNSET" else "ok"
|
|
50
|
+
for event in span.events:
|
|
51
|
+
if event.name == "exception":
|
|
52
|
+
ea = event.attributes or {}
|
|
53
|
+
result["error"] = {"type": str(ea.get("exception.type", "Error")), "message": str(ea.get("exception.message", ""))}
|
|
54
|
+
result["status"] = "error"
|
|
55
|
+
if "error" not in result and result["status"] == "error":
|
|
56
|
+
result["error"] = {"type": "Error", "message": span.status.description or ""}
|
|
57
|
+
usage = {dest: attrs["llm.token_count." + src] for src, dest in USAGE_MAP.items() if "llm.token_count." + src in attrs}
|
|
58
|
+
if usage:
|
|
59
|
+
result["usage"] = usage
|
|
60
|
+
for direction in (("input",) if start else ("input", "output")):
|
|
61
|
+
value = content(attrs, direction)
|
|
62
|
+
if value is not None:
|
|
63
|
+
result[direction] = value
|
|
64
|
+
if "llm.model_name" in attrs:
|
|
65
|
+
result["model"] = attrs["llm.model_name"]
|
|
66
|
+
# Everything in these namespaces can contain prompts, tool arguments, documents,
|
|
67
|
+
# images or parameters. Do not duplicate them as string attributes.
|
|
68
|
+
excluded = ("input.", "output.", "llm.input_messages.", "llm.output_messages.", "llm.tools.", "llm.token_count.", "retrieval.documents.", "embedding.", "llm.invocation_parameters", "tool.parameters", "llm.function_call", "llm.prompt_template.", "gen_ai.input.", "gen_ai.output.", "gen_ai.prompt", "gen_ai.completion")
|
|
69
|
+
result["attributes"] = {k: v for k, v in attrs.items() if k not in ("openinference.span.kind", "llm.model_name") and not k.startswith(excluded)}
|
|
70
|
+
return result
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from opentelemetry.sdk.trace import SpanProcessor
|
|
2
|
+
from .exporter import CloudByteSpanExporter
|
|
3
|
+
from .mapping import map_span
|
|
4
|
+
|
|
5
|
+
class CloudByteSpanProcessor(SpanProcessor):
|
|
6
|
+
def __init__(self, tracer):
|
|
7
|
+
self.tracer = tracer
|
|
8
|
+
self.exporter = CloudByteSpanExporter(tracer)
|
|
9
|
+
self.enabled = True
|
|
10
|
+
self.parents = {}
|
|
11
|
+
|
|
12
|
+
def on_start(self, span, parent_context=None):
|
|
13
|
+
if self.enabled:
|
|
14
|
+
self.parents[span.get_span_context().span_id] = span.parent.span_id if span.parent else None
|
|
15
|
+
if self.enabled and (not span.parent or not span.parent.is_valid):
|
|
16
|
+
try:
|
|
17
|
+
self.tracer._enqueue(map_span(span, start=True))
|
|
18
|
+
except Exception:
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
def on_end(self, span):
|
|
22
|
+
if self.enabled:
|
|
23
|
+
self.exporter.export((span,))
|
|
24
|
+
self.parents.pop(span.get_span_context().span_id, None)
|
|
25
|
+
|
|
26
|
+
def shutdown(self):
|
|
27
|
+
self.enabled = False
|
|
28
|
+
self.parents.clear()
|
|
29
|
+
|
|
30
|
+
def force_flush(self, timeout_millis=30000):
|
|
31
|
+
return self.exporter.force_flush(timeout_millis)
|