efficientai-sdk 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.
@@ -0,0 +1,535 @@
1
+ """OpenTelemetry export to EfficientAI. Needs the ``otel`` extra:
2
+
3
+ pip install "efficientai-sdk[otel]"
4
+
5
+ Importing this module without OpenTelemetry installed is safe; the setup functions
6
+ then return ``False`` (or raise, for :func:`create_otlp_exporter`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import os
13
+ import threading
14
+ from collections.abc import Mapping, Sequence
15
+ from typing import TYPE_CHECKING, Any, Optional
16
+
17
+ from efficientai_sdk.tracing.context import get_call_attributes, set_call_attributes
18
+ from efficientai_sdk.tracing.correlation import (
19
+ ATTR_CALL_SHORT_ID,
20
+ ATTR_OTLP_EXPORT_ENDPOINT,
21
+ extract_call_short_id,
22
+ otlp_export_headers,
23
+ span_correlation_attributes,
24
+ )
25
+
26
+ logger = logging.getLogger("efficientai_sdk.tracing")
27
+
28
+ try:
29
+ from opentelemetry import trace
30
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
31
+ from opentelemetry.sdk.resources import Resource
32
+ from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider
33
+ from opentelemetry.sdk.trace.export import (
34
+ BatchSpanProcessor,
35
+ ConsoleSpanExporter,
36
+ SpanExporter,
37
+ SpanExportResult,
38
+ )
39
+
40
+ OTEL_AVAILABLE = True
41
+ except ImportError: # pragma: no cover - exercised only without the extra
42
+ OTEL_AVAILABLE = False
43
+ if not TYPE_CHECKING:
44
+ SpanExporter = object
45
+ SpanProcessor = object
46
+ TracerProvider = None
47
+
48
+ if TYPE_CHECKING:
49
+ from opentelemetry.context import Context
50
+ from opentelemetry.trace import Span
51
+
52
+ __all__ = [
53
+ "OTEL_AVAILABLE",
54
+ "create_otlp_exporter",
55
+ "ensure_export_pipeline",
56
+ "flush_efficientai_tracing",
57
+ "is_tracing_available",
58
+ "setup_efficientai_tracing",
59
+ "setup_tracer_provider",
60
+ ]
61
+
62
+ _OTEL_MISSING = (
63
+ "OpenTelemetry is not installed. Install the extra: pip install 'efficientai-sdk[otel]'"
64
+ )
65
+
66
+ _state_lock = threading.RLock()
67
+ _correlation_processor: Optional[_CorrelationSpanProcessor] = None
68
+ _mutable_exporter: Optional[_MutableOtlpExporter] = None
69
+ _exporter_attached = False
70
+ # Export pipelines added by ensure_export_pipeline, keyed by (endpoint, api_key, workspace).
71
+ _pipelines: dict[tuple[str, str, Optional[str]], Any] = {}
72
+
73
+
74
+ def is_tracing_available() -> bool:
75
+ return OTEL_AVAILABLE
76
+
77
+
78
+ def _env(name: str) -> Optional[str]:
79
+ value = os.environ.get(name)
80
+ if value is None or not value.strip():
81
+ return None
82
+ return value.strip()
83
+
84
+
85
+ class _MutableOtlpExporter(SpanExporter):
86
+ """OTLP exporter whose correlation headers can be switched per call.
87
+
88
+ One instance is attached to the tracer provider for the life of the process; each
89
+ new call reconfigures the headers instead of adding another span processor.
90
+ """
91
+
92
+ def __init__(self, *, endpoint: str, api_key: str) -> None:
93
+ self._endpoint = endpoint
94
+ self._api_key = api_key
95
+ self._inner: Any = None
96
+ self._lock = threading.Lock()
97
+
98
+ @property
99
+ def endpoint(self) -> str:
100
+ return self._endpoint
101
+
102
+ def configure(self, *, workspace_id: Optional[str] = None) -> None:
103
+ inner = OTLPSpanExporter(
104
+ endpoint=self._endpoint,
105
+ headers=otlp_export_headers(api_key=self._api_key, workspace_id=workspace_id),
106
+ )
107
+ with self._lock:
108
+ self._inner = inner
109
+
110
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
111
+ with self._lock:
112
+ if self._inner is None:
113
+ self._inner = OTLPSpanExporter(
114
+ endpoint=self._endpoint,
115
+ headers=otlp_export_headers(api_key=self._api_key),
116
+ )
117
+ inner = self._inner
118
+ owned = _spans_for_destination(spans, self._endpoint.rstrip("/"))
119
+ if not owned:
120
+ return SpanExportResult.SUCCESS
121
+ result: SpanExportResult = inner.export(owned)
122
+ return result
123
+
124
+ def shutdown(self) -> None:
125
+ with self._lock:
126
+ if self._inner is not None:
127
+ self._inner.shutdown()
128
+
129
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
130
+ with self._lock:
131
+ inner = self._inner
132
+ return True if inner is None else bool(inner.force_flush(timeout_millis))
133
+
134
+
135
+ _EFFICIENTAI_PREFIX = "efficientai."
136
+
137
+
138
+ def _active_export_destinations() -> set[str]:
139
+ with _state_lock:
140
+ destinations = {ep.rstrip("/") for ep, _, _ in _pipelines}
141
+ if _mutable_exporter is not None:
142
+ destinations.add(_mutable_exporter.endpoint.rstrip("/"))
143
+ return destinations
144
+
145
+
146
+ def _spans_for_destination(spans: Sequence[ReadableSpan], destination: str) -> list[ReadableSpan]:
147
+ dest = destination.rstrip("/")
148
+ allow_untagged = len(_active_export_destinations()) <= 1
149
+ owned: list[ReadableSpan] = []
150
+ for span in spans:
151
+ attrs = span.attributes or {}
152
+ stamped = attrs.get(ATTR_OTLP_EXPORT_ENDPOINT)
153
+ if stamped is not None:
154
+ if str(stamped).rstrip("/") == dest:
155
+ owned.append(span)
156
+ elif allow_untagged:
157
+ owned.append(span)
158
+ return owned
159
+
160
+
161
+ class _DestinationFilteredExporter(SpanExporter):
162
+ """Drop spans that belong to a different EfficientAI deployment."""
163
+
164
+ def __init__(self, destination: str, inner: SpanExporter) -> None:
165
+ self._destination = destination.rstrip("/")
166
+ self._inner = inner
167
+
168
+ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
169
+ owned = _spans_for_destination(spans, self._destination)
170
+ if not owned:
171
+ return SpanExportResult.SUCCESS
172
+ return self._inner.export(owned)
173
+
174
+ def shutdown(self) -> None:
175
+ self._inner.shutdown()
176
+
177
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
178
+ return bool(self._inner.force_flush(timeout_millis))
179
+
180
+
181
+ def _parent_call_attributes(parent_context: Optional[Context]) -> Optional[dict[str, str]]:
182
+ """``efficientai.*`` attributes of the parent span, when it belongs to a call."""
183
+ parent = trace.get_current_span(parent_context)
184
+ attrs = getattr(parent, "attributes", None)
185
+ if not attrs or ATTR_CALL_SHORT_ID not in attrs:
186
+ return None
187
+ return {k: str(v) for k, v in attrs.items() if k.startswith(_EFFICIENTAI_PREFIX)}
188
+
189
+
190
+ class _CorrelationSpanProcessor(SpanProcessor):
191
+ """Stamps EfficientAI correlation attributes on every span when it starts.
192
+
193
+ Source, in order: the call active in the current context, the parent span's call,
194
+ then the process-wide default set by :func:`setup_efficientai_tracing`. Attributes
195
+ already set on the span (for example by the SDK's own span helpers) are kept.
196
+ """
197
+
198
+ def __init__(self, attributes: Mapping[str, str]) -> None:
199
+ self._attributes = dict(attributes)
200
+ self.active = True
201
+
202
+ def update_attributes(self, attributes: Mapping[str, str]) -> None:
203
+ self._attributes = dict(attributes)
204
+
205
+ def on_start(self, span: Span, parent_context: Optional[Context] = None) -> None:
206
+ if not self.active:
207
+ return
208
+ attrs = get_call_attributes() or _parent_call_attributes(parent_context) or self._attributes
209
+ if not attrs:
210
+ return
211
+ existing = getattr(span, "attributes", None) or {}
212
+ for key, value in attrs.items():
213
+ if key not in existing:
214
+ span.set_attribute(key, value)
215
+
216
+ def on_end(self, span: ReadableSpan) -> None:
217
+ return
218
+
219
+ def shutdown(self) -> None:
220
+ return
221
+
222
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
223
+ return True
224
+
225
+
226
+ def _resolve_call_short_id(
227
+ *,
228
+ call_short_id: Optional[str] = None,
229
+ sip_headers: Optional[Mapping[str, Any]] = None,
230
+ webhook_params: Optional[Mapping[str, Any]] = None,
231
+ ) -> Optional[str]:
232
+ return (
233
+ call_short_id
234
+ or extract_call_short_id(sip_headers=sip_headers, webhook_params=webhook_params)
235
+ or _env("EFFICIENTAI_CALL_SHORT_ID")
236
+ )
237
+
238
+
239
+ def create_otlp_exporter(
240
+ *,
241
+ endpoint: Optional[str] = None,
242
+ api_key: Optional[str] = None,
243
+ call_short_id: Optional[str] = None,
244
+ evaluator_result_id: Optional[str] = None,
245
+ workspace_id: Optional[str] = None,
246
+ sip_headers: Optional[Mapping[str, Any]] = None,
247
+ webhook_params: Optional[Mapping[str, Any]] = None,
248
+ mutable: bool = True,
249
+ shared: bool = False,
250
+ ) -> Any:
251
+ """Build an OTLP/HTTP span exporter pointed at EfficientAI trace ingest.
252
+
253
+ With ``shared=True`` (used by :func:`setup_efficientai_tracing`) a single process-wide
254
+ exporter is reused; call ids stay on span attributes, not HTTP headers.
255
+
256
+ Factory callers should leave ``shared=False`` so each exporter keeps wire correlation
257
+ headers unless they set attributes on every span themselves.
258
+ """
259
+ global _mutable_exporter
260
+ if not OTEL_AVAILABLE:
261
+ raise RuntimeError(_OTEL_MISSING)
262
+
263
+ resolved_endpoint = endpoint or _env("EFFICIENTAI_OTLP_ENDPOINT")
264
+ resolved_key = api_key or _env("EFFICIENTAI_API_KEY")
265
+ if not resolved_endpoint:
266
+ raise ValueError("EFFICIENTAI_OTLP_ENDPOINT is required")
267
+ if not resolved_key:
268
+ raise ValueError("EFFICIENTAI_API_KEY is required")
269
+
270
+ cid = _resolve_call_short_id(
271
+ call_short_id=call_short_id, sip_headers=sip_headers, webhook_params=webhook_params
272
+ )
273
+ run_id = evaluator_result_id or _env("EFFICIENTAI_RUN_ID")
274
+ workspace = workspace_id or _env("EFFICIENTAI_WORKSPACE_ID")
275
+
276
+ headers = otlp_export_headers(
277
+ api_key=resolved_key,
278
+ call_short_id=cid,
279
+ evaluator_result_id=run_id,
280
+ workspace_id=workspace,
281
+ )
282
+
283
+ if not mutable or not shared:
284
+ return OTLPSpanExporter(endpoint=resolved_endpoint, headers=headers)
285
+
286
+ with _state_lock:
287
+ if _mutable_exporter is None:
288
+ _mutable_exporter = _MutableOtlpExporter(
289
+ endpoint=resolved_endpoint, api_key=resolved_key
290
+ )
291
+ elif (
292
+ _mutable_exporter.endpoint.rstrip("/") != resolved_endpoint.rstrip("/")
293
+ or _mutable_exporter._api_key != resolved_key
294
+ ):
295
+ raise ValueError(
296
+ f"EfficientAI OTLP exporter already targets {_mutable_exporter.endpoint}; "
297
+ f"refusing {resolved_endpoint}"
298
+ )
299
+ exporter = _mutable_exporter
300
+ exporter.configure(workspace_id=workspace)
301
+ return exporter
302
+
303
+
304
+ def setup_tracer_provider(
305
+ service_name: str = "efficientai-agent",
306
+ *,
307
+ exporter: Any = None,
308
+ console_export: bool = False,
309
+ ) -> bool:
310
+ """Install a global ``TracerProvider`` with optional exporter. Returns ``False`` on failure."""
311
+ if not OTEL_AVAILABLE:
312
+ return False
313
+ try:
314
+ resource = Resource.create(
315
+ {
316
+ "service.name": service_name,
317
+ "service.instance.id": os.getenv("HOSTNAME", "unknown"),
318
+ "deployment.environment": os.getenv("ENVIRONMENT", "development"),
319
+ }
320
+ )
321
+ provider = TracerProvider(resource=resource)
322
+ trace.set_tracer_provider(provider)
323
+ if console_export:
324
+ provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
325
+ if exporter is not None:
326
+ provider.add_span_processor(BatchSpanProcessor(exporter))
327
+ return True
328
+ except Exception:
329
+ logger.exception("Failed to set up OpenTelemetry tracing")
330
+ return False
331
+
332
+
333
+ def _attach_correlation_processor_unlocked(provider: Any, attrs: Optional[dict[str, str]]) -> None:
334
+ """Like :func:`_attach_correlation_processor` but caller holds ``_state_lock``."""
335
+ global _correlation_processor
336
+ if _correlation_processor is None:
337
+ _correlation_processor = _CorrelationSpanProcessor(attrs or {})
338
+ provider.add_span_processor(_correlation_processor)
339
+ elif attrs is not None:
340
+ _correlation_processor.update_attributes(attrs)
341
+
342
+
343
+ def _attach_correlation_processor(provider: Any, attrs: Optional[dict[str, str]]) -> None:
344
+ """Add the correlation processor once. ``attrs`` (if given) become the default."""
345
+ with _state_lock:
346
+ _attach_correlation_processor_unlocked(provider, attrs)
347
+
348
+
349
+ def ensure_export_pipeline(
350
+ *,
351
+ endpoint: str,
352
+ api_key: str,
353
+ workspace_id: Optional[str] = None,
354
+ service_name: str = "efficientai-agent",
355
+ console_export: bool = False,
356
+ ) -> bool:
357
+ """Make sure spans from this process are exported to EfficientAI. Idempotent.
358
+
359
+ Uses the app's ``TracerProvider`` if it has one, otherwise installs one. The exporter
360
+ carries only the API key and workspace; each span carries its own call id (see
361
+ :mod:`efficientai_sdk.tracing.context`), so one pipeline serves concurrent calls.
362
+ Returns ``False`` when OpenTelemetry is not installed or setup failed.
363
+ """
364
+ if not OTEL_AVAILABLE:
365
+ return False
366
+ key = (endpoint.rstrip("/"), api_key, workspace_id or None)
367
+ with _state_lock:
368
+ if key in _pipelines:
369
+ return True
370
+ if _pipelines:
371
+ logger.warning(
372
+ "EfficientAI span export already targets another deployment; ignoring %s",
373
+ key[0],
374
+ )
375
+ return False
376
+ try:
377
+ base_exporter = OTLPSpanExporter(
378
+ endpoint=key[0],
379
+ headers=otlp_export_headers(api_key=api_key, workspace_id=workspace_id),
380
+ )
381
+ filtered_exporter = _DestinationFilteredExporter(key[0], base_exporter)
382
+ pipeline_exporter: Any = filtered_exporter
383
+ provider = trace.get_tracer_provider()
384
+ if not isinstance(provider, TracerProvider):
385
+ if not setup_tracer_provider(
386
+ service_name, exporter=filtered_exporter, console_export=console_export
387
+ ):
388
+ return False
389
+ _exporter_attached = True
390
+ provider = trace.get_tracer_provider()
391
+ else:
392
+ if _mutable_exporter is not None and (
393
+ _mutable_exporter.endpoint.rstrip("/") == key[0].rstrip("/")
394
+ and _mutable_exporter._api_key == api_key
395
+ ):
396
+ pipeline_exporter = _mutable_exporter
397
+ _exporter_attached = True
398
+ else:
399
+ provider.add_span_processor(BatchSpanProcessor(filtered_exporter))
400
+ _exporter_attached = True
401
+ if isinstance(provider, TracerProvider):
402
+ _attach_correlation_processor_unlocked(provider, None)
403
+ _pipelines[key] = pipeline_exporter
404
+ except Exception:
405
+ logger.exception("Failed to set up EfficientAI span export")
406
+ return False
407
+ return True
408
+
409
+
410
+ def setup_efficientai_tracing(
411
+ *,
412
+ service_name: str = "pipecat-agent",
413
+ call_short_id: Optional[str] = None,
414
+ evaluator_result_id: Optional[str] = None,
415
+ agent_id: Optional[str] = None,
416
+ workspace_id: Optional[str] = None,
417
+ transport: Optional[str] = None,
418
+ otlp_endpoint: Optional[str] = None,
419
+ api_key: Optional[str] = None,
420
+ sip_headers: Optional[Mapping[str, Any]] = None,
421
+ webhook_params: Optional[Mapping[str, Any]] = None,
422
+ console_export: bool = False,
423
+ ) -> bool:
424
+ """Configure OpenTelemetry export to EfficientAI for the current call.
425
+
426
+ Call once per call, after reading the call's SIP, webhook or handshake metadata.
427
+ Works whether or not the process already has a ``TracerProvider``. Returns ``False``
428
+ when OpenTelemetry is not installed.
429
+ """
430
+ global _exporter_attached
431
+ if not OTEL_AVAILABLE:
432
+ return False
433
+
434
+ resolved_endpoint = (otlp_endpoint or _env("EFFICIENTAI_OTLP_ENDPOINT") or "").rstrip("/")
435
+ resolved_key = api_key or _env("EFFICIENTAI_API_KEY")
436
+ if not resolved_endpoint or not resolved_key:
437
+ return False
438
+
439
+ cid = _resolve_call_short_id(
440
+ call_short_id=call_short_id, sip_headers=sip_headers, webhook_params=webhook_params
441
+ )
442
+ run_id = evaluator_result_id or _env("EFFICIENTAI_RUN_ID")
443
+ agent = agent_id or _env("EFFICIENTAI_AGENT_ID")
444
+ workspace = workspace_id or _env("EFFICIENTAI_WORKSPACE_ID")
445
+ attrs = span_correlation_attributes(
446
+ call_short_id=cid,
447
+ evaluator_result_id=run_id,
448
+ agent_id=agent,
449
+ workspace_id=workspace,
450
+ transport=transport,
451
+ export_endpoint=resolved_endpoint,
452
+ )
453
+ # Tag the current task before any exporter/processor setup that might emit spans.
454
+ set_call_attributes(attrs)
455
+
456
+ with _state_lock:
457
+ if _mutable_exporter is not None and (
458
+ _mutable_exporter.endpoint.rstrip("/") != resolved_endpoint
459
+ or _mutable_exporter._api_key != resolved_key
460
+ ):
461
+ logger.warning(
462
+ "EfficientAI export already targets %s; refusing %s",
463
+ _mutable_exporter.endpoint,
464
+ resolved_endpoint,
465
+ )
466
+ return False
467
+ for pipeline_endpoint, pipeline_api_key, _ in _pipelines:
468
+ same_ep = pipeline_endpoint.rstrip("/") == resolved_endpoint.rstrip("/")
469
+ if not same_ep or pipeline_api_key != resolved_key:
470
+ logger.warning(
471
+ "EfficientAI export pipeline already uses another deployment; refused"
472
+ )
473
+ return False
474
+
475
+ try:
476
+ exporter = create_otlp_exporter(
477
+ endpoint=resolved_endpoint,
478
+ api_key=resolved_key,
479
+ call_short_id=cid,
480
+ evaluator_result_id=run_id,
481
+ workspace_id=workspace,
482
+ mutable=True,
483
+ shared=True,
484
+ )
485
+ except ValueError:
486
+ logger.warning("EfficientAI export refused due to endpoint conflict")
487
+ return False
488
+
489
+ dest = resolved_endpoint.rstrip("/")
490
+ pipeline_key = (dest, resolved_key, workspace or None)
491
+ with _state_lock:
492
+ provider = trace.get_tracer_provider()
493
+ export_attached = _exporter_attached or pipeline_key in _pipelines
494
+ if not isinstance(provider, TracerProvider):
495
+ if not setup_tracer_provider(
496
+ service_name, exporter=exporter, console_export=console_export
497
+ ):
498
+ return False
499
+ _exporter_attached = True
500
+ _pipelines.setdefault(pipeline_key, exporter)
501
+ provider = trace.get_tracer_provider()
502
+ elif not export_attached:
503
+ provider.add_span_processor(BatchSpanProcessor(exporter))
504
+ _exporter_attached = True
505
+ _pipelines.setdefault(pipeline_key, exporter)
506
+
507
+ if isinstance(provider, TracerProvider):
508
+ _attach_correlation_processor_unlocked(provider, attrs)
509
+ return True
510
+
511
+
512
+ def flush_efficientai_tracing(timeout_millis: int = 30000) -> bool:
513
+ """Block until queued spans are exported. Call before closing a trace session."""
514
+ if not OTEL_AVAILABLE:
515
+ return False
516
+ try:
517
+ provider = trace.get_tracer_provider()
518
+ if isinstance(provider, TracerProvider):
519
+ return bool(provider.force_flush(timeout_millis))
520
+ except Exception:
521
+ logger.exception("Failed to flush EfficientAI spans")
522
+ return False
523
+
524
+
525
+ def _reset_for_tests() -> None:
526
+ """Forget process-wide exporter state (tests only)."""
527
+ global _correlation_processor, _mutable_exporter, _exporter_attached
528
+ with _state_lock:
529
+ # Processors can't be removed from a TracerProvider; switch the old one off.
530
+ if _correlation_processor is not None:
531
+ _correlation_processor.active = False
532
+ _correlation_processor = None
533
+ _mutable_exporter = None
534
+ _exporter_attached = False
535
+ _pipelines.clear()