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,835 @@
1
+ """High-level tracing API, reached through ``client.trace``.
2
+
3
+ Async::
4
+
5
+ client = AsyncEfficientAI()
6
+ async with client.trace.session(agent_id="...", transport="websocket") as call:
7
+ with call.turn():
8
+ with call.stt(model="nova-3", provider="deepgram") as stt:
9
+ stt.set_transcript("I'd like to book a table")
10
+ with call.llm(model="gpt-4o", provider="openai") as llm:
11
+ llm.set_output("Sure, for how many people?")
12
+ with call.tts(model="sonic", provider="cartesia") as tts:
13
+ tts.set_text("Sure, for how many people?")
14
+
15
+ Sync code uses ``EfficientAI`` and a plain ``with``. Nothing here raises because of
16
+ EfficientAI: if the session can't be opened, the call is disabled, a warning is logged,
17
+ and every span helper becomes a no-op. Exceptions from your own code inside a span are
18
+ recorded on the span and re-raised unchanged.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import contextvars
25
+ import logging
26
+ from collections.abc import Iterator, Mapping
27
+ from contextlib import AbstractContextManager, contextmanager
28
+ from typing import TYPE_CHECKING, Any, Optional, Union
29
+
30
+ from efficientai_sdk._exceptions import EfficientAIError
31
+ from efficientai_sdk._version import __version__
32
+ from efficientai_sdk.tracing import otel
33
+ from efficientai_sdk.tracing.context import (
34
+ call_attributes,
35
+ reset_call_attributes,
36
+ set_call_attributes,
37
+ )
38
+ from efficientai_sdk.tracing.correlation import (
39
+ extract_call_short_id,
40
+ span_correlation_attributes,
41
+ )
42
+ from efficientai_sdk.tracing.handshake import parse_trace_handshake
43
+ from efficientai_sdk.tracing.session import (
44
+ SESSIONS_PATH,
45
+ VALID_TRANSPORTS,
46
+ TraceSessionError,
47
+ _run_id_from,
48
+ resolve_otlp_endpoint,
49
+ )
50
+
51
+ if TYPE_CHECKING:
52
+ from efficientai_sdk._base_client import AsyncAPIClient, SyncAPIClient
53
+
54
+ logger = logging.getLogger("efficientai_sdk.tracing")
55
+
56
+ __all__ = [
57
+ "AsyncTraceResource",
58
+ "CallTrace",
59
+ "ComponentSpan",
60
+ "RetrievalSpan",
61
+ "ToolSpan",
62
+ "TraceResource",
63
+ "TurnSpan",
64
+ ]
65
+
66
+ AttributeValue = Union[str, bool, int, float]
67
+
68
+ # Long tool arguments/results or prompts are truncated so a single span can't blow up
69
+ # the OTLP request (the server keeps attributes as strings).
70
+ MAX_ATTRIBUTE_CHARS = 8192
71
+
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Span wrappers
75
+ # ---------------------------------------------------------------------------
76
+
77
+
78
+ class ComponentSpan:
79
+ """A span for one step of a turn. Setters are safe no-ops when tracing is off."""
80
+
81
+ def __init__(self, span: Any = None) -> None:
82
+ self._span = span
83
+
84
+ @property
85
+ def recording(self) -> bool:
86
+ return self._span is not None
87
+
88
+ def set_attribute(self, key: str, value: Optional[AttributeValue]) -> ComponentSpan:
89
+ if self._span is not None and value is not None:
90
+ if isinstance(value, str) and len(value) > MAX_ATTRIBUTE_CHARS:
91
+ value = value[:MAX_ATTRIBUTE_CHARS] + "...[truncated]"
92
+ try:
93
+ self._span.set_attribute(key, value)
94
+ except Exception:
95
+ logger.debug("Failed to set span attribute %s", key, exc_info=True)
96
+ return self
97
+
98
+ def set_attributes(self, attributes: Mapping[str, Optional[AttributeValue]]) -> ComponentSpan:
99
+ for key, value in attributes.items():
100
+ self.set_attribute(key, value)
101
+ return self
102
+
103
+ def set_ttfb(self, seconds: float) -> ComponentSpan:
104
+ """Time to first byte/token, in seconds. Shown as the component's latency."""
105
+ return self.set_attribute("metrics.ttfb", float(seconds))
106
+
107
+ # STT
108
+ def set_transcript(self, text: str) -> ComponentSpan:
109
+ """What the user said (STT) or, on an s2s span, the user's transcript."""
110
+ self.set_attribute("transcript", text)
111
+ return self.set_attribute("transcript.is_input", True)
112
+
113
+ # LLM / s2s
114
+ def set_input(self, text: str) -> ComponentSpan:
115
+ return self.set_attribute("input", text)
116
+
117
+ def set_output(self, text: str) -> ComponentSpan:
118
+ """The agent's reply (LLM or s2s)."""
119
+ return self.set_attribute("output", text)
120
+
121
+ def set_usage(
122
+ self, *, input_tokens: Optional[int] = None, output_tokens: Optional[int] = None
123
+ ) -> ComponentSpan:
124
+ self.set_attribute("gen_ai.usage.input_tokens", input_tokens)
125
+ return self.set_attribute("gen_ai.usage.output_tokens", output_tokens)
126
+
127
+ # TTS
128
+ def set_text(self, text: str) -> ComponentSpan:
129
+ """The text that was spoken (TTS)."""
130
+ return self.set_attribute("text", text)
131
+
132
+
133
+ class ToolSpan(ComponentSpan):
134
+ """A tool/function call made by the agent."""
135
+
136
+ def set_arguments(self, arguments: str) -> ToolSpan:
137
+ self.set_attribute("gen_ai.tool.call.arguments", arguments)
138
+ return self
139
+
140
+ def set_result(self, result: str) -> ToolSpan:
141
+ self.set_attribute("gen_ai.tool.call.result", result)
142
+ return self
143
+
144
+ def set_error(self, message: str) -> ToolSpan:
145
+ self.set_attribute("error", True)
146
+ self.set_attribute("error.message", message)
147
+ return self
148
+
149
+
150
+ class RetrievalSpan(ComponentSpan):
151
+ """A knowledge-base / RAG lookup."""
152
+
153
+ def set_documents(self, count: int) -> RetrievalSpan:
154
+ self.set_attribute("retrieval.documents.count", int(count))
155
+ return self
156
+
157
+
158
+ class TurnSpan(ComponentSpan):
159
+ """The span grouping one user/agent exchange."""
160
+
161
+ def set_user_bot_latency(self, seconds: float) -> TurnSpan:
162
+ """End of user speech to start of agent speech, measured by your stack."""
163
+ self.set_attribute("turn.user_bot_latency_seconds", float(seconds))
164
+ return self
165
+
166
+ def set_interrupted(self, interrupted: bool = True) -> TurnSpan:
167
+ self.set_attribute("turn.was_interrupted", bool(interrupted))
168
+ return self
169
+
170
+
171
+ def _component_attributes(
172
+ operation: str,
173
+ *,
174
+ model: Optional[str],
175
+ provider: Optional[str],
176
+ extra: Mapping[str, Optional[AttributeValue]],
177
+ ) -> dict[str, AttributeValue]:
178
+ attrs: dict[str, AttributeValue] = {"gen_ai.operation.name": operation}
179
+ if model:
180
+ attrs["gen_ai.request.model"] = model
181
+ if provider:
182
+ attrs["gen_ai.provider.name"] = provider.lower()
183
+ for key, value in extra.items():
184
+ if value is None:
185
+ continue
186
+ if isinstance(value, str) and len(value) > MAX_ATTRIBUTE_CHARS:
187
+ value = value[:MAX_ATTRIBUTE_CHARS] + "...[truncated]"
188
+ attrs[key] = value
189
+ return attrs
190
+
191
+
192
+ # ---------------------------------------------------------------------------
193
+ # Call
194
+ # ---------------------------------------------------------------------------
195
+
196
+
197
+ class CallTrace:
198
+ """One traced call. Get it from ``client.trace.session(...)``."""
199
+
200
+ def __init__(
201
+ self,
202
+ *,
203
+ call_short_id: Optional[str],
204
+ enabled: bool,
205
+ workspace_id: Optional[str] = None,
206
+ agent_id: Optional[str] = None,
207
+ transport: Optional[str] = None,
208
+ evaluator_result_id: Optional[str] = None,
209
+ trace_id: Optional[str] = None,
210
+ owns_session: bool = False,
211
+ error: Optional[str] = None,
212
+ extra_attributes: Optional[Mapping[str, str]] = None,
213
+ channel: Optional[str] = None,
214
+ ) -> None:
215
+ self.call_short_id = call_short_id
216
+ self.enabled = enabled and bool(call_short_id)
217
+ self.workspace_id = workspace_id
218
+ self.agent_id = agent_id
219
+ self.transport = transport
220
+ self.evaluator_result_id = evaluator_result_id
221
+ self.trace_id = trace_id
222
+ self.owns_session = owns_session
223
+ self.error = error
224
+ self.channel = channel
225
+ self._turns = 0
226
+ self._token: Optional[contextvars.Token[Optional[dict[str, str]]]] = None
227
+ attrs = (
228
+ span_correlation_attributes(
229
+ call_short_id=call_short_id,
230
+ evaluator_result_id=evaluator_result_id,
231
+ agent_id=agent_id,
232
+ workspace_id=workspace_id,
233
+ transport=transport,
234
+ )
235
+ if self.enabled
236
+ else {}
237
+ )
238
+ if self.enabled and channel:
239
+ attrs["efficientai.channel"] = channel
240
+ if self.enabled and extra_attributes:
241
+ attrs.update(extra_attributes)
242
+ self._attributes = attrs
243
+
244
+ def __repr__(self) -> str:
245
+ return (
246
+ f"CallTrace(call_short_id={self.call_short_id!r}, enabled={self.enabled}, "
247
+ f"transport={self.transport!r})"
248
+ )
249
+
250
+ @property
251
+ def attributes(self) -> dict[str, str]:
252
+ """``efficientai.*`` attributes for this call (empty when disabled).
253
+
254
+ Pass these to frameworks that take extra span attributes, such as Pipecat's
255
+ ``PipelineTask(additional_span_attributes=...)``.
256
+ """
257
+ return dict(self._attributes)
258
+
259
+ # ---- context ---------------------------------------------------------
260
+
261
+ @contextmanager
262
+ def activate(self) -> Iterator[CallTrace]:
263
+ """Tag spans created in this block (and tasks started from it) with this call.
264
+
265
+ Sessions activate themselves; use this when work for the call runs in another
266
+ thread or a task created before the session opened.
267
+ """
268
+ if not self.enabled:
269
+ yield self
270
+ return
271
+ with call_attributes(self._attributes):
272
+ yield self
273
+
274
+ def _enter_context(self) -> None:
275
+ if self.enabled:
276
+ self._token = set_call_attributes(self._attributes)
277
+
278
+ def _exit_context(self) -> None:
279
+ if self._token is not None:
280
+ reset_call_attributes(self._token)
281
+ self._token = None
282
+
283
+ # ---- spans -----------------------------------------------------------
284
+
285
+ @contextmanager
286
+ def _span(
287
+ self,
288
+ name: str,
289
+ attributes: Mapping[str, AttributeValue],
290
+ wrapper: type[ComponentSpan] = ComponentSpan,
291
+ ) -> Iterator[Any]:
292
+ manager: Any = None
293
+ span: Any = None
294
+ if self.enabled and otel.OTEL_AVAILABLE:
295
+ try:
296
+ from opentelemetry import trace as otel_trace
297
+
298
+ tracer = otel_trace.get_tracer("efficientai_sdk", __version__)
299
+ manager = tracer.start_as_current_span(
300
+ name, attributes={**self._attributes, **attributes}
301
+ )
302
+ span = manager.__enter__()
303
+ except Exception:
304
+ logger.warning("EfficientAI: could not start span %r", name, exc_info=True)
305
+ manager = None
306
+ if manager is None:
307
+ yield wrapper()
308
+ return
309
+ try:
310
+ yielded = wrapper(span)
311
+ yield yielded
312
+ except BaseException as exc:
313
+ manager.__exit__(type(exc), exc, exc.__traceback__)
314
+ raise
315
+ else:
316
+ try:
317
+ if name in ("stt", "tts", "llm"):
318
+ existing = getattr(span, "attributes", None) or {}
319
+ start_ns = getattr(span, "start_time", None)
320
+ if "metrics.ttfb" not in existing and start_ns:
321
+ import time
322
+
323
+ yielded.set_ttfb(max(0.0, (time.time_ns() - int(start_ns)) / 1_000_000_000))
324
+ manager.__exit__(None, None, None)
325
+ except Exception:
326
+ logger.debug("EfficientAI: failed to end span %r", name, exc_info=True)
327
+
328
+ def turn(self, number: Optional[int] = None, **attributes: AttributeValue) -> Any:
329
+ """Group one user/agent exchange. Yields a :class:`TurnSpan`."""
330
+ self._turns = number if number is not None else self._turns + 1
331
+ return self._span("turn", {"turn.number": self._turns, **attributes}, TurnSpan)
332
+
333
+ def stt(
334
+ self,
335
+ *,
336
+ model: Optional[str] = None,
337
+ provider: Optional[str] = None,
338
+ transcript: Optional[str] = None,
339
+ **attributes: AttributeValue,
340
+ ) -> Any:
341
+ """Speech-to-text. Set the user's words with ``set_transcript``."""
342
+ extra: dict[str, Optional[AttributeValue]] = {**attributes}
343
+ if transcript is not None:
344
+ extra.update({"transcript": transcript, "transcript.is_input": True})
345
+ return self._span(
346
+ "stt", _component_attributes("stt", model=model, provider=provider, extra=extra)
347
+ )
348
+
349
+ def llm(
350
+ self,
351
+ *,
352
+ model: Optional[str] = None,
353
+ provider: Optional[str] = None,
354
+ input: Optional[str] = None,
355
+ output: Optional[str] = None,
356
+ **attributes: AttributeValue,
357
+ ) -> Any:
358
+ """LLM call. Set the reply with ``set_output``."""
359
+ extra: dict[str, Optional[AttributeValue]] = {
360
+ "input": input,
361
+ "output": output,
362
+ **attributes,
363
+ }
364
+ return self._span(
365
+ "llm", _component_attributes("chat", model=model, provider=provider, extra=extra)
366
+ )
367
+
368
+ def tts(
369
+ self,
370
+ *,
371
+ model: Optional[str] = None,
372
+ provider: Optional[str] = None,
373
+ text: Optional[str] = None,
374
+ **attributes: AttributeValue,
375
+ ) -> Any:
376
+ """Text-to-speech. Set the spoken text with ``set_text``."""
377
+ extra: dict[str, Optional[AttributeValue]] = {"text": text, **attributes}
378
+ return self._span(
379
+ "tts", _component_attributes("tts", model=model, provider=provider, extra=extra)
380
+ )
381
+
382
+ def s2s(
383
+ self,
384
+ *,
385
+ model: Optional[str] = None,
386
+ provider: Optional[str] = None,
387
+ **attributes: AttributeValue,
388
+ ) -> Any:
389
+ """Speech-to-speech / realtime model turn (replaces stt + llm + tts)."""
390
+ return self._span(
391
+ "s2s",
392
+ _component_attributes("s2s", model=model, provider=provider, extra=attributes),
393
+ )
394
+
395
+ # ---- chat ------------------------------------------------------------
396
+
397
+ def _message(self, name: str, text: str, attributes: Mapping[str, AttributeValue]) -> None:
398
+ message = text
399
+ if len(message) > MAX_ATTRIBUTE_CHARS:
400
+ message = message[:MAX_ATTRIBUTE_CHARS] + "...[truncated]"
401
+ with self._span(name, {"gen_ai.operation.name": name, "message": message, **attributes}):
402
+ pass
403
+
404
+ def user_message(self, text: str, **attributes: AttributeValue) -> None:
405
+ """Record what the user typed. Call it when the message arrives."""
406
+ self._message("user_message", text, attributes)
407
+
408
+ def assistant_message(self, text: str, **attributes: AttributeValue) -> None:
409
+ """Record the reply sent to the user.
410
+
411
+ Optional: without it, the last LLM output in the turn is used as the reply.
412
+ Useful when the agent post-processes the LLM output before sending it.
413
+ """
414
+ self._message("assistant_message", text, attributes)
415
+
416
+ def tool(
417
+ self, name: str, *, arguments: Optional[str] = None, **attributes: AttributeValue
418
+ ) -> Any:
419
+ """A tool/function call. Yields a :class:`ToolSpan` (``set_result``, ``set_error``)."""
420
+ if arguments is not None and len(arguments) > MAX_ATTRIBUTE_CHARS:
421
+ arguments = arguments[:MAX_ATTRIBUTE_CHARS] + "...[truncated]"
422
+ extra: dict[str, Optional[AttributeValue]] = {
423
+ "gen_ai.tool.name": name,
424
+ "gen_ai.tool.call.arguments": arguments,
425
+ **attributes,
426
+ }
427
+ return self._span(
428
+ f"execute_tool {name}",
429
+ _component_attributes("execute_tool", model=None, provider=None, extra=extra),
430
+ ToolSpan,
431
+ )
432
+
433
+ def retrieval(
434
+ self,
435
+ *,
436
+ source: Optional[str] = None,
437
+ query: Optional[str] = None,
438
+ **attributes: AttributeValue,
439
+ ) -> Any:
440
+ """A knowledge-base / RAG lookup. Yields a :class:`RetrievalSpan` (``set_documents``)."""
441
+ extra: dict[str, Optional[AttributeValue]] = {
442
+ "retrieval.source": source,
443
+ "retrieval.query": query,
444
+ **attributes,
445
+ }
446
+ return self._span(
447
+ "retrieval",
448
+ _component_attributes("retrieval", model=None, provider=None, extra=extra),
449
+ RetrievalSpan,
450
+ )
451
+
452
+ def span(self, name: str, **attributes: AttributeValue) -> Any:
453
+ """Any other span you want attached to this call (tool calls, retrieval, ...)."""
454
+ return self._span(name, attributes)
455
+
456
+
457
+ # ---------------------------------------------------------------------------
458
+ # Session open/close
459
+ # ---------------------------------------------------------------------------
460
+
461
+
462
+ def _session_payload(
463
+ transport: str, agent_id: Optional[str], evaluator_result_id: Optional[str]
464
+ ) -> dict[str, Any]:
465
+ payload: dict[str, Any] = {"transport": transport}
466
+ if agent_id:
467
+ payload["agent_id"] = str(agent_id)
468
+ if evaluator_result_id:
469
+ payload["evaluator_result_id"] = str(evaluator_result_id)
470
+ return payload
471
+
472
+
473
+ def _call_from_correlation(
474
+ *,
475
+ channel: Optional[str],
476
+ handshake: Optional[Mapping[str, Any]],
477
+ call_short_id: Optional[str],
478
+ sip_headers: Optional[Mapping[str, Any]],
479
+ headers: Optional[Mapping[str, Any]],
480
+ transport: str,
481
+ agent_id: Optional[str],
482
+ workspace_id: Optional[str],
483
+ evaluator_result_id: Optional[str],
484
+ attributes: Optional[Mapping[str, str]],
485
+ ) -> tuple[Optional[CallTrace], Optional[str]]:
486
+ """A call id the platform already gave us (handshake, SIP or HTTP headers).
487
+
488
+ Returns ``(call, otlp_endpoint_hint)``, or ``(None, None)`` to mint a new session.
489
+ """
490
+ parsed = parse_trace_handshake(handshake) if handshake else None
491
+ if parsed:
492
+ otel_block = parsed.get("otel_correlation") or {}
493
+ return (
494
+ CallTrace(
495
+ call_short_id=parsed["call_short_id"],
496
+ enabled=True,
497
+ workspace_id=str(parsed.get("workspace_id") or workspace_id or "") or None,
498
+ agent_id=str(parsed.get("agent_id") or agent_id or "") or None,
499
+ transport=parsed.get("transport") or transport,
500
+ evaluator_result_id=_run_id_from(otel_block, evaluator_result_id),
501
+ trace_id=parsed.get("trace_id"),
502
+ extra_attributes=attributes,
503
+ channel=channel,
504
+ ),
505
+ otel_block.get("otlp_endpoint"),
506
+ )
507
+
508
+ found = call_short_id or extract_call_short_id(sip_headers=sip_headers, webhook_params=headers)
509
+ if found:
510
+ run_id = evaluator_result_id
511
+ if not run_id and headers:
512
+ run_id = next(
513
+ (str(v) for k, v in headers.items() if k.lower() == "x-efficientai-run-id"),
514
+ None,
515
+ )
516
+ return (
517
+ CallTrace(
518
+ call_short_id=found,
519
+ enabled=True,
520
+ workspace_id=workspace_id,
521
+ agent_id=agent_id,
522
+ transport=transport,
523
+ evaluator_result_id=run_id,
524
+ extra_attributes=attributes,
525
+ channel=channel,
526
+ ),
527
+ None,
528
+ )
529
+ return None, None
530
+
531
+
532
+ def _call_from_session(
533
+ body: Any,
534
+ *,
535
+ channel: Optional[str],
536
+ transport: str,
537
+ agent_id: Optional[str],
538
+ workspace_id: Optional[str],
539
+ attributes: Optional[Mapping[str, str]],
540
+ ) -> tuple[CallTrace, Optional[str]]:
541
+ if not isinstance(body, dict) or not body.get("call_short_id"):
542
+ raise TraceSessionError(f"Unexpected session response: {body!r}")
543
+ otel_block = body.get("otel_correlation") or {}
544
+ return (
545
+ CallTrace(
546
+ call_short_id=str(body["call_short_id"]),
547
+ enabled=True,
548
+ workspace_id=str(body.get("workspace_id") or workspace_id or "") or None,
549
+ agent_id=agent_id,
550
+ transport=body.get("transport") or transport,
551
+ evaluator_result_id=_run_id_from(otel_block),
552
+ trace_id=str(body["trace_id"]) if body.get("trace_id") else None,
553
+ owns_session=True,
554
+ extra_attributes=attributes,
555
+ channel=channel,
556
+ ),
557
+ otel_block.get("otlp_endpoint"),
558
+ )
559
+
560
+
561
+ def _as_session_error(exc: EfficientAIError) -> TraceSessionError:
562
+ if isinstance(exc, TraceSessionError):
563
+ return exc
564
+ return TraceSessionError(str(exc), status_code=getattr(exc, "status_code", None))
565
+
566
+
567
+ def _disabled(error: str, transport: str) -> CallTrace:
568
+ return CallTrace(call_short_id=None, enabled=False, transport=transport, error=error)
569
+
570
+
571
+ def _check_transport(transport: str) -> str:
572
+ value = (transport or "custom").lower()
573
+ if value not in VALID_TRANSPORTS:
574
+ raise ValueError(f"transport must be one of {sorted(VALID_TRANSPORTS)}")
575
+ return value
576
+
577
+
578
+ class _TraceResourceBase:
579
+ def __init__(self, client: Any, *, service_name: str = "efficientai-agent") -> None:
580
+ self._client = client
581
+ self.service_name = service_name
582
+
583
+ def _start_export(self, call: CallTrace, endpoint_hint: Optional[str]) -> None:
584
+ if not call.enabled:
585
+ return
586
+ config = self._client._config
587
+ otlp_path = config.api_path("observability/traces")
588
+ ok = otel.ensure_export_pipeline(
589
+ endpoint=resolve_otlp_endpoint(
590
+ endpoint_hint, api_base_url=config.base_url, otlp_path=otlp_path
591
+ ),
592
+ api_key=config.api_key,
593
+ workspace_id=call.workspace_id or config.workspace_id,
594
+ service_name=self.service_name,
595
+ )
596
+ if not ok and not otel.OTEL_AVAILABLE:
597
+ logger.warning(
598
+ "EfficientAI: OpenTelemetry is not installed, so spans for call %s won't be "
599
+ "exported. Install with: pip install 'efficientai-sdk[otel]'",
600
+ call.call_short_id,
601
+ )
602
+
603
+ def instrument(self, *, console_export: bool = False) -> bool:
604
+ """Export this process's OpenTelemetry spans to EfficientAI.
605
+
606
+ For stacks that already create their own spans. Spans are tagged with the call
607
+ active in the current context (see :meth:`CallTrace.activate`).
608
+ """
609
+ config = self._client._config
610
+ return otel.ensure_export_pipeline(
611
+ endpoint=resolve_otlp_endpoint(
612
+ api_base_url=config.base_url,
613
+ otlp_path=config.api_path("observability/traces"),
614
+ ),
615
+ api_key=config.api_key,
616
+ workspace_id=config.workspace_id,
617
+ service_name=self.service_name,
618
+ console_export=console_export,
619
+ )
620
+
621
+
622
+ class TraceResource(_TraceResourceBase):
623
+ """``EfficientAI().trace``: tracing for synchronous code."""
624
+
625
+ _client: SyncAPIClient
626
+
627
+ def start_session(
628
+ self,
629
+ *,
630
+ transport: str = "custom",
631
+ agent_id: Optional[str] = None,
632
+ evaluator_result_id: Optional[str] = None,
633
+ handshake: Optional[Mapping[str, Any]] = None,
634
+ call_short_id: Optional[str] = None,
635
+ sip_headers: Optional[Mapping[str, Any]] = None,
636
+ headers: Optional[Mapping[str, Any]] = None,
637
+ attributes: Optional[Mapping[str, str]] = None,
638
+ channel: Optional[str] = None,
639
+ strict: bool = False,
640
+ ) -> CallTrace:
641
+ """Open a call and activate it in the current context. Pair with :meth:`end_session`.
642
+
643
+ Reuses the platform's call id when one is supplied (``handshake``,
644
+ ``call_short_id``, ``sip_headers`` or ``headers``); otherwise opens a new session.
645
+ Pass ``channel="chat"`` for text agents so turns are built from messages, tool
646
+ calls and LLM output instead of STT/TTS.
647
+ """
648
+ transport = _check_transport(transport)
649
+ call, hint = _call_from_correlation(
650
+ channel=channel,
651
+ handshake=handshake,
652
+ call_short_id=call_short_id,
653
+ sip_headers=sip_headers,
654
+ headers=headers,
655
+ transport=transport,
656
+ agent_id=agent_id,
657
+ workspace_id=self._client.workspace_id,
658
+ evaluator_result_id=evaluator_result_id,
659
+ attributes=attributes,
660
+ )
661
+ if call is None:
662
+ try:
663
+ body = self._client.request(
664
+ "POST",
665
+ SESSIONS_PATH,
666
+ json=_session_payload(transport, agent_id, evaluator_result_id),
667
+ )
668
+ call, hint = _call_from_session(
669
+ body,
670
+ channel=channel,
671
+ transport=transport,
672
+ agent_id=agent_id,
673
+ workspace_id=self._client.workspace_id,
674
+ attributes=attributes,
675
+ )
676
+ except EfficientAIError as exc:
677
+ if strict:
678
+ raise _as_session_error(exc) from exc
679
+ logger.warning("EfficientAI trace session failed, tracing disabled: %s", exc)
680
+ return _disabled(str(exc), transport)
681
+ call._enter_context()
682
+ self._start_export(call, hint)
683
+ return call
684
+
685
+ def end_session(self, call: CallTrace, *, close: Optional[bool] = None) -> None:
686
+ """Flush spans and close the session. Never raises.
687
+
688
+ ``close=None`` closes only sessions this SDK opened; platform-owned test calls
689
+ are closed by the platform.
690
+ """
691
+ call._exit_context()
692
+ if not call.enabled:
693
+ return
694
+ otel.flush_efficientai_tracing()
695
+ if not (call.owns_session if close is None else close):
696
+ return
697
+ try:
698
+ self._client.request("POST", f"{SESSIONS_PATH}/{call.call_short_id}/close")
699
+ except EfficientAIError as exc:
700
+ logger.warning("EfficientAI trace close failed: %s", exc)
701
+
702
+ @contextmanager
703
+ def session(self, **kwargs: Any) -> Iterator[CallTrace]:
704
+ """``with client.trace.session(...) as call:``. Same arguments as :meth:`start_session`."""
705
+ call = self.start_session(**kwargs)
706
+ try:
707
+ yield call
708
+ finally:
709
+ self.end_session(call)
710
+
711
+ def from_request(
712
+ self, headers: Mapping[str, Any], **kwargs: Any
713
+ ) -> AbstractContextManager[CallTrace]:
714
+ """Resume the platform call id from HTTP headers such as ``X-EfficientAI-Call-Short-Id``."""
715
+ return self.session(headers=headers, **kwargs)
716
+
717
+ def from_sip_headers(
718
+ self, sip_headers: Mapping[str, Any], **kwargs: Any
719
+ ) -> AbstractContextManager[CallTrace]:
720
+ """Resume the platform call id from SIP headers on a phone simulation."""
721
+ return self.session(sip_headers=sip_headers, **kwargs)
722
+
723
+ def from_handshake(
724
+ self, message: Mapping[str, Any], **kwargs: Any
725
+ ) -> AbstractContextManager[CallTrace]:
726
+ """Resume the platform call id from an ``efficientai_trace_handshake`` message."""
727
+ return self.session(handshake=message, **kwargs)
728
+
729
+
730
+ class _AsyncSession:
731
+ def __init__(self, resource: AsyncTraceResource, kwargs: dict[str, Any]) -> None:
732
+ self._resource = resource
733
+ self._kwargs = kwargs
734
+ self._call: Optional[CallTrace] = None
735
+
736
+ async def __aenter__(self) -> CallTrace:
737
+ self._call = await self._resource.start_session(**self._kwargs)
738
+ return self._call
739
+
740
+ async def __aexit__(self, *exc_info: object) -> None:
741
+ if self._call is not None:
742
+ await self._resource.end_session(self._call)
743
+
744
+
745
+ class AsyncTraceResource(_TraceResourceBase):
746
+ """``AsyncEfficientAI().trace``: tracing for asyncio code."""
747
+
748
+ _client: AsyncAPIClient
749
+
750
+ async def start_session(
751
+ self,
752
+ *,
753
+ transport: str = "custom",
754
+ agent_id: Optional[str] = None,
755
+ evaluator_result_id: Optional[str] = None,
756
+ handshake: Optional[Mapping[str, Any]] = None,
757
+ call_short_id: Optional[str] = None,
758
+ sip_headers: Optional[Mapping[str, Any]] = None,
759
+ headers: Optional[Mapping[str, Any]] = None,
760
+ attributes: Optional[Mapping[str, str]] = None,
761
+ channel: Optional[str] = None,
762
+ strict: bool = False,
763
+ ) -> CallTrace:
764
+ """Async version of :meth:`TraceResource.start_session`.
765
+
766
+ The call is activated in the calling task's context, so tasks it creates
767
+ afterwards inherit it.
768
+ """
769
+ transport = _check_transport(transport)
770
+ call, hint = _call_from_correlation(
771
+ channel=channel,
772
+ handshake=handshake,
773
+ call_short_id=call_short_id,
774
+ sip_headers=sip_headers,
775
+ headers=headers,
776
+ transport=transport,
777
+ agent_id=agent_id,
778
+ workspace_id=self._client.workspace_id,
779
+ evaluator_result_id=evaluator_result_id,
780
+ attributes=attributes,
781
+ )
782
+ if call is None:
783
+ try:
784
+ body = await self._client.request(
785
+ "POST",
786
+ SESSIONS_PATH,
787
+ json=_session_payload(transport, agent_id, evaluator_result_id),
788
+ )
789
+ call, hint = _call_from_session(
790
+ body,
791
+ channel=channel,
792
+ transport=transport,
793
+ agent_id=agent_id,
794
+ workspace_id=self._client.workspace_id,
795
+ attributes=attributes,
796
+ )
797
+ except EfficientAIError as exc:
798
+ if strict:
799
+ raise _as_session_error(exc) from exc
800
+ logger.warning("EfficientAI trace session failed, tracing disabled: %s", exc)
801
+ return _disabled(str(exc), transport)
802
+ call._enter_context()
803
+ self._start_export(call, hint)
804
+ return call
805
+
806
+ async def end_session(self, call: CallTrace, *, close: Optional[bool] = None) -> None:
807
+ """Async version of :meth:`TraceResource.end_session`."""
808
+ call._exit_context()
809
+ if not call.enabled:
810
+ return
811
+ # force_flush blocks on network I/O; keep it off the event loop.
812
+ await asyncio.get_running_loop().run_in_executor(None, otel.flush_efficientai_tracing)
813
+ if not (call.owns_session if close is None else close):
814
+ return
815
+ try:
816
+ await self._client.request("POST", f"{SESSIONS_PATH}/{call.call_short_id}/close")
817
+ except EfficientAIError as exc:
818
+ logger.warning("EfficientAI trace close failed: %s", exc)
819
+
820
+ def session(self, **kwargs: Any) -> _AsyncSession:
821
+ """``async with client.trace.session(...) as call:``. Same arguments as
822
+ :meth:`start_session`."""
823
+ return _AsyncSession(self, kwargs)
824
+
825
+ def from_request(self, headers: Mapping[str, Any], **kwargs: Any) -> _AsyncSession:
826
+ """Async form of :meth:`TraceResource.from_request`."""
827
+ return self.session(headers=headers, **kwargs)
828
+
829
+ def from_sip_headers(self, sip_headers: Mapping[str, Any], **kwargs: Any) -> _AsyncSession:
830
+ """Async form of :meth:`TraceResource.from_sip_headers`."""
831
+ return self.session(sip_headers=sip_headers, **kwargs)
832
+
833
+ def from_handshake(self, message: Mapping[str, Any], **kwargs: Any) -> _AsyncSession:
834
+ """Async form of :meth:`TraceResource.from_handshake`."""
835
+ return self.session(handshake=message, **kwargs)