trodo-python 1.2.0__py3-none-any.whl → 2.2.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.
@@ -0,0 +1,281 @@
1
+ """Optional: register OpenTelemetry auto-instrumentation that feeds spans
2
+ into our TrodoSpanProcessor. Call ``enable_auto_instrument()`` once at
3
+ startup to pick up Anthropic / OpenAI / LangChain / LlamaIndex / Google
4
+ Generative AI / Vertex AI and others — without any more code.
5
+
6
+ Each underlying OTel package is an optional dependency — we import them
7
+ lazily and skip anything that isn't installed.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import datetime, timezone
13
+ from typing import Any, Callable, Dict, Iterable, List, Optional
14
+
15
+ from .context import get_active_context
16
+ from .processor import TrodoSpan, TrodoSpanProcessor
17
+
18
+
19
+ def _hr_to_iso(nanos: Optional[int]) -> Optional[str]:
20
+ if nanos is None:
21
+ return None
22
+ return datetime.fromtimestamp(nanos / 1e9, tz=timezone.utc).isoformat().replace("+00:00", "Z")
23
+
24
+
25
+ def _infer_kind(attrs: Dict[str, Any]) -> str:
26
+ if not attrs:
27
+ return "generic"
28
+ if attrs.get("gen_ai.tool.name"):
29
+ return "tool"
30
+ if attrs.get("gen_ai.operation.name") or attrs.get("gen_ai.request.model"):
31
+ return "llm"
32
+ if attrs.get("db.system") or attrs.get("retrieval.query"):
33
+ return "retrieval"
34
+ return "generic"
35
+
36
+
37
+ def otel_span_to_trodo_span(otel_span: Any) -> Optional[TrodoSpan]:
38
+ """Translate an OTel ReadableSpan to our TrodoSpan using GenAI semconv."""
39
+ ctx = get_active_context()
40
+ if ctx is None:
41
+ return None # span emitted outside of wrap_agent — drop
42
+ try:
43
+ span_ctx = (
44
+ otel_span.get_span_context()
45
+ if callable(getattr(otel_span, "get_span_context", None))
46
+ else otel_span.context
47
+ )
48
+ except Exception:
49
+ return None
50
+
51
+ span_id_int = getattr(span_ctx, "span_id", None)
52
+ if not span_id_int:
53
+ return None
54
+ span_id = f"{span_id_int:016x}" if isinstance(span_id_int, int) else str(span_id_int)
55
+
56
+ parent = getattr(otel_span, "parent", None)
57
+ parent_span_id: Optional[str] = None
58
+ if parent is not None:
59
+ pid = getattr(parent, "span_id", None)
60
+ parent_span_id = f"{pid:016x}" if isinstance(pid, int) else str(pid) if pid else None
61
+ if parent_span_id is None:
62
+ parent_span_id = ctx.span_id
63
+
64
+ attrs = dict(getattr(otel_span, "attributes", {}) or {})
65
+ kind = _infer_kind(attrs)
66
+
67
+ start_time = getattr(otel_span, "start_time", None)
68
+ end_time = getattr(otel_span, "end_time", None)
69
+ started_at = _hr_to_iso(start_time) or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
70
+ ended_at = _hr_to_iso(end_time)
71
+ duration_ms = None
72
+ if start_time and end_time:
73
+ duration_ms = max(0, int((end_time - start_time) / 1e6))
74
+
75
+ status = getattr(otel_span, "status", None)
76
+ status_code = getattr(status, "status_code", None)
77
+ ok = "ok"
78
+ try:
79
+ from opentelemetry.trace import StatusCode
80
+
81
+ ok = "error" if status_code == StatusCode.ERROR else "ok"
82
+ except Exception:
83
+ ok = "error" if (status_code and str(status_code).endswith("ERROR")) else "ok"
84
+
85
+ # Accept both stable and experimental GenAI semconv keys.
86
+ in_toks = (
87
+ attrs.get("gen_ai.usage.input_tokens")
88
+ or attrs.get("gen_ai.usage.prompt_tokens")
89
+ or attrs.get("llm.usage.prompt_tokens")
90
+ )
91
+ out_toks = (
92
+ attrs.get("gen_ai.usage.output_tokens")
93
+ or attrs.get("gen_ai.usage.completion_tokens")
94
+ or attrs.get("llm.usage.completion_tokens")
95
+ )
96
+ model = (
97
+ attrs.get("gen_ai.request.model")
98
+ or attrs.get("gen_ai.response.model")
99
+ or attrs.get("llm.request.model")
100
+ )
101
+ provider = attrs.get("gen_ai.system") or attrs.get("llm.vendor")
102
+ prompt = attrs.get("gen_ai.prompt") or attrs.get("llm.prompts")
103
+ completion = attrs.get("gen_ai.completion") or attrs.get("llm.completion")
104
+
105
+ return TrodoSpan(
106
+ span_id=span_id,
107
+ run_id=ctx.run_id,
108
+ parent_span_id=parent_span_id,
109
+ kind=kind,
110
+ name=getattr(otel_span, "name", kind),
111
+ status=ok,
112
+ started_at=started_at,
113
+ ended_at=ended_at,
114
+ duration_ms=duration_ms,
115
+ model=model,
116
+ provider=provider,
117
+ input_tokens=int(in_toks) if in_toks is not None else None,
118
+ output_tokens=int(out_toks) if out_toks is not None else None,
119
+ temperature=attrs.get("gen_ai.request.temperature"),
120
+ tool_name=attrs.get("gen_ai.tool.name"),
121
+ input=prompt,
122
+ output=completion,
123
+ attributes=attrs or None,
124
+ )
125
+
126
+
127
+ class _OtelAdapter:
128
+ """Adapter matching opentelemetry.sdk.trace.SpanProcessor interface."""
129
+
130
+ def __init__(self, processor: TrodoSpanProcessor) -> None:
131
+ self._processor = processor
132
+
133
+ def on_start(self, span: Any, parent_context: Any = None) -> None:
134
+ pass
135
+
136
+ def on_end(self, span: Any) -> None:
137
+ trodo_span = otel_span_to_trodo_span(span)
138
+ if trodo_span is not None:
139
+ self._processor.enqueue_span(trodo_span)
140
+
141
+ def shutdown(self) -> None:
142
+ self._processor.shutdown()
143
+
144
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
145
+ self._processor.force_flush()
146
+ return True
147
+
148
+
149
+ _INSTRUMENTORS: List[tuple[str, Callable[[], Any]]] = []
150
+
151
+
152
+ def _register_instrumentors() -> None:
153
+ """Build the list of known instrumentor factories.
154
+
155
+ Each entry is ``(framework_id, factory)`` where ``factory`` performs a
156
+ lazy import and returns an ``instrument()`` call. Failures are swallowed
157
+ so missing optional deps never break user code.
158
+ """
159
+ global _INSTRUMENTORS
160
+ if _INSTRUMENTORS:
161
+ return
162
+
163
+ def _anthropic() -> Any:
164
+ from opentelemetry.instrumentation.anthropic import AnthropicInstrumentor # type: ignore
165
+
166
+ AnthropicInstrumentor().instrument()
167
+
168
+ def _openai() -> Any:
169
+ from opentelemetry.instrumentation.openai import OpenAIInstrumentor # type: ignore
170
+
171
+ OpenAIInstrumentor().instrument()
172
+
173
+ def _openai_v2() -> Any:
174
+ from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor # type: ignore
175
+
176
+ OpenAIInstrumentor().instrument()
177
+
178
+ def _langchain() -> Any:
179
+ from opentelemetry.instrumentation.langchain import LangChainInstrumentor # type: ignore
180
+
181
+ LangChainInstrumentor().instrument()
182
+
183
+ def _llama_index() -> Any:
184
+ from opentelemetry.instrumentation.llama_index import LlamaIndexInstrumentor # type: ignore
185
+
186
+ LlamaIndexInstrumentor().instrument()
187
+
188
+ def _google_generativeai() -> Any:
189
+ from opentelemetry.instrumentation.google_generativeai import ( # type: ignore
190
+ GoogleGenerativeAIInstrumentor,
191
+ )
192
+
193
+ GoogleGenerativeAIInstrumentor().instrument()
194
+
195
+ def _vertexai() -> Any:
196
+ from opentelemetry.instrumentation.vertexai import VertexAIInstrumentor # type: ignore
197
+
198
+ VertexAIInstrumentor().instrument()
199
+
200
+ def _bedrock() -> Any:
201
+ from opentelemetry.instrumentation.bedrock import BedrockInstrumentor # type: ignore
202
+
203
+ BedrockInstrumentor().instrument()
204
+
205
+ def _cohere() -> Any:
206
+ from opentelemetry.instrumentation.cohere import CohereInstrumentor # type: ignore
207
+
208
+ CohereInstrumentor().instrument()
209
+
210
+ def _mistralai() -> Any:
211
+ from opentelemetry.instrumentation.mistralai import MistralAiInstrumentor # type: ignore
212
+
213
+ MistralAiInstrumentor().instrument()
214
+
215
+ def _haystack() -> Any:
216
+ from opentelemetry.instrumentation.haystack import HaystackInstrumentor # type: ignore
217
+
218
+ HaystackInstrumentor().instrument()
219
+
220
+ def _httpx() -> Any:
221
+ from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor # type: ignore
222
+
223
+ HTTPXClientInstrumentor().instrument()
224
+
225
+ def _requests() -> Any:
226
+ from opentelemetry.instrumentation.requests import RequestsInstrumentor # type: ignore
227
+
228
+ RequestsInstrumentor().instrument()
229
+
230
+ _INSTRUMENTORS = [
231
+ ("anthropic", _anthropic),
232
+ ("openai", _openai),
233
+ ("openai_v2", _openai_v2),
234
+ ("langchain", _langchain),
235
+ ("llama_index", _llama_index),
236
+ ("google_generativeai", _google_generativeai),
237
+ ("vertexai", _vertexai),
238
+ ("bedrock", _bedrock),
239
+ ("cohere", _cohere),
240
+ ("mistralai", _mistralai),
241
+ ("haystack", _haystack),
242
+ ("httpx", _httpx),
243
+ ("requests", _requests),
244
+ ]
245
+
246
+
247
+ def enable_auto_instrument(
248
+ processor: TrodoSpanProcessor,
249
+ disable: Optional[Iterable[str]] = None,
250
+ ) -> List[str]:
251
+ """Register OTel auto-instrumentations for installed packages.
252
+
253
+ Returns the list of framework ids that were actually instrumented.
254
+ Skipped silently if opentelemetry-sdk or the per-framework
255
+ instrumentation package isn't installed.
256
+ """
257
+ disabled = set(disable or [])
258
+ try:
259
+ from opentelemetry import trace # type: ignore
260
+ from opentelemetry.sdk.trace import TracerProvider # type: ignore
261
+ except Exception:
262
+ return []
263
+
264
+ provider = trace.get_tracer_provider()
265
+ if not isinstance(provider, TracerProvider):
266
+ provider = TracerProvider()
267
+ trace.set_tracer_provider(provider)
268
+
269
+ provider.add_span_processor(_OtelAdapter(processor))
270
+
271
+ _register_instrumentors()
272
+ active: List[str] = []
273
+ for name, register in _INSTRUMENTORS:
274
+ if name in disabled:
275
+ continue
276
+ try:
277
+ register()
278
+ active.append(name)
279
+ except Exception:
280
+ continue
281
+ return active
trodo/otel/context.py ADDED
@@ -0,0 +1,44 @@
1
+ """Active run/span context using contextvars — auto-propagates across awaits
2
+ and threading.local-style sync code.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import contextvars
8
+ from dataclasses import dataclass
9
+ from typing import Optional
10
+
11
+
12
+ @dataclass
13
+ class ActiveSpanContext:
14
+ run_id: str
15
+ span_id: str
16
+ parent_span_id: Optional[str]
17
+ team_site_id: str
18
+ processor: object # TrodoSpanProcessor — avoid circular import
19
+
20
+
21
+ _active: contextvars.ContextVar[Optional[ActiveSpanContext]] = contextvars.ContextVar(
22
+ "trodo_active_span", default=None,
23
+ )
24
+
25
+
26
+ def get_active_context() -> Optional[ActiveSpanContext]:
27
+ return _active.get()
28
+
29
+
30
+ class run_with_context:
31
+ """Context manager that sets the active span context for its duration."""
32
+
33
+ def __init__(self, ctx: ActiveSpanContext) -> None:
34
+ self._ctx = ctx
35
+ self._token: Optional[contextvars.Token] = None
36
+
37
+ def __enter__(self) -> ActiveSpanContext:
38
+ self._token = _active.set(self._ctx)
39
+ return self._ctx
40
+
41
+ def __exit__(self, exc_type, exc, tb) -> None:
42
+ if self._token is not None:
43
+ _active.reset(self._token)
44
+ self._token = None