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.
- efficientai_sdk/__init__.py +40 -0
- efficientai_sdk/_base_client.py +313 -0
- efficientai_sdk/_client.py +196 -0
- efficientai_sdk/_config.py +139 -0
- efficientai_sdk/_exceptions.py +142 -0
- efficientai_sdk/_version.py +1 -0
- efficientai_sdk/cli.py +99 -0
- efficientai_sdk/integrations/__init__.py +4 -0
- efficientai_sdk/integrations/livekit.py +134 -0
- efficientai_sdk/integrations/pipecat.py +126 -0
- efficientai_sdk/py.typed +0 -0
- efficientai_sdk/simulations/__init__.py +25 -0
- efficientai_sdk/simulations/api.py +682 -0
- efficientai_sdk/simulations/models.py +186 -0
- efficientai_sdk/simulations/polling.py +62 -0
- efficientai_sdk/tracing/__init__.py +110 -0
- efficientai_sdk/tracing/api.py +835 -0
- efficientai_sdk/tracing/context.py +57 -0
- efficientai_sdk/tracing/correlation.py +191 -0
- efficientai_sdk/tracing/handshake.py +42 -0
- efficientai_sdk/tracing/otel.py +535 -0
- efficientai_sdk/tracing/session.py +385 -0
- efficientai_sdk-0.1.0.dist-info/METADATA +168 -0
- efficientai_sdk-0.1.0.dist-info/RECORD +27 -0
- efficientai_sdk-0.1.0.dist-info/WHEEL +4 -0
- efficientai_sdk-0.1.0.dist-info/entry_points.txt +2 -0
- efficientai_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""Trace sessions: open a session per call, export spans against it, close it at hang-up.
|
|
2
|
+
|
|
3
|
+
Typical flow for any agent stack::
|
|
4
|
+
|
|
5
|
+
trace_ctx = await ensure_trace_session(transport="websocket", handshake=first_message)
|
|
6
|
+
setup_worker_tracing(trace_ctx) # point OTLP export at this call
|
|
7
|
+
... # run the call; spans are exported
|
|
8
|
+
await close_trace_session(trace_ctx) # flush spans and close the session
|
|
9
|
+
|
|
10
|
+
Every function here degrades gracefully: unless ``strict=True``, failures are logged and
|
|
11
|
+
the agent keeps running without traces.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
from typing import Any, Optional
|
|
19
|
+
|
|
20
|
+
from efficientai_sdk._client import AsyncEfficientAI
|
|
21
|
+
from efficientai_sdk._config import (
|
|
22
|
+
DEFAULT_API_PREFIX,
|
|
23
|
+
ENV_API_KEY,
|
|
24
|
+
ENV_API_PREFIX,
|
|
25
|
+
ENV_WORKSPACE_ID,
|
|
26
|
+
normalize_api_prefix,
|
|
27
|
+
resolve_config,
|
|
28
|
+
)
|
|
29
|
+
from efficientai_sdk._exceptions import (
|
|
30
|
+
APIConnectionError,
|
|
31
|
+
APIStatusError,
|
|
32
|
+
APITimeoutError,
|
|
33
|
+
ConfigurationError,
|
|
34
|
+
EfficientAIError,
|
|
35
|
+
)
|
|
36
|
+
from efficientai_sdk.tracing.correlation import span_correlation_attributes
|
|
37
|
+
from efficientai_sdk.tracing.handshake import parse_trace_handshake
|
|
38
|
+
from efficientai_sdk.tracing.otel import flush_efficientai_tracing, setup_efficientai_tracing
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger("efficientai_sdk.tracing")
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"DEFAULT_OTLP_PATH",
|
|
44
|
+
"SESSIONS_PATH",
|
|
45
|
+
"VALID_TRANSPORTS",
|
|
46
|
+
"TraceSessionError",
|
|
47
|
+
"close_trace_session",
|
|
48
|
+
"ensure_trace_session",
|
|
49
|
+
"mint_trace_session",
|
|
50
|
+
"missing_deployment_trace_env",
|
|
51
|
+
"require_deployment_trace_env",
|
|
52
|
+
"resolve_otlp_endpoint",
|
|
53
|
+
"resolve_trace_transport",
|
|
54
|
+
"setup_worker_tracing",
|
|
55
|
+
"trace_session_enabled",
|
|
56
|
+
"warn_deployment_trace_env",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
DEFAULT_OTLP_PATH = "/api/v1/observability/traces"
|
|
60
|
+
SESSIONS_PATH = "/api/v1/observability/traces/sessions"
|
|
61
|
+
VALID_TRANSPORTS = frozenset({"webrtc", "websocket", "phone", "custom"})
|
|
62
|
+
_SESSION_TIMEOUT = 20.0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class TraceSessionError(EfficientAIError):
|
|
66
|
+
"""The session API failed (connection, HTTP status, or bad response)."""
|
|
67
|
+
|
|
68
|
+
def __init__(self, message: str, *, status_code: Optional[int] = None) -> None:
|
|
69
|
+
super().__init__(message)
|
|
70
|
+
self.status_code = status_code
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _env(name: str) -> Optional[str]:
|
|
74
|
+
value = os.environ.get(name)
|
|
75
|
+
if value is None or not value.strip():
|
|
76
|
+
return None
|
|
77
|
+
return value.strip()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _api_base_url(explicit: Optional[str] = None) -> str:
|
|
81
|
+
# Any non-empty key works here: only the base URL is used.
|
|
82
|
+
return resolve_config(api_key="unused", base_url=explicit).base_url
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _otlp_path(explicit: Optional[str] = None) -> str:
|
|
86
|
+
"""Path appended to the API host. A client ``api_prefix`` overrides the default."""
|
|
87
|
+
if explicit and explicit.strip():
|
|
88
|
+
return "/" + explicit.strip().lstrip("/").rstrip("/")
|
|
89
|
+
prefix = normalize_api_prefix(_env(ENV_API_PREFIX) or DEFAULT_API_PREFIX)
|
|
90
|
+
return f"{prefix}/observability/traces"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def resolve_otlp_endpoint(
|
|
94
|
+
server_hint: Optional[str] = None,
|
|
95
|
+
*,
|
|
96
|
+
api_base_url: Optional[str] = None,
|
|
97
|
+
otlp_path: Optional[str] = None,
|
|
98
|
+
) -> str:
|
|
99
|
+
"""OTLP ingest URL to export to.
|
|
100
|
+
|
|
101
|
+
``EFFICIENTAI_OTLP_ENDPOINT`` wins. Otherwise the server's hint is used, unless it
|
|
102
|
+
would downgrade an https deployment to http (common behind TLS-terminating proxies).
|
|
103
|
+
When neither is set, the path follows ``otlp_path`` or ``EFFICIENTAI_API_PREFIX``.
|
|
104
|
+
"""
|
|
105
|
+
explicit = _env("EFFICIENTAI_OTLP_ENDPOINT")
|
|
106
|
+
if explicit:
|
|
107
|
+
return explicit.rstrip("/")
|
|
108
|
+
base = _api_base_url(api_base_url)
|
|
109
|
+
canonical = f"{base}{_otlp_path(otlp_path)}"
|
|
110
|
+
if not server_hint or not str(server_hint).strip():
|
|
111
|
+
return canonical
|
|
112
|
+
hint = str(server_hint).strip().rstrip("/")
|
|
113
|
+
if base.startswith("https://") and hint.startswith("http://"):
|
|
114
|
+
return canonical
|
|
115
|
+
return hint
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def missing_deployment_trace_env() -> list[str]:
|
|
119
|
+
"""Environment variables still needed when no handshake is present."""
|
|
120
|
+
return [name for name in (ENV_API_KEY, ENV_WORKSPACE_ID) if not _env(name)]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def require_deployment_trace_env() -> None:
|
|
124
|
+
"""Raise ``ConfigurationError`` if the trace environment is incomplete."""
|
|
125
|
+
missing = missing_deployment_trace_env()
|
|
126
|
+
if missing:
|
|
127
|
+
raise ConfigurationError(
|
|
128
|
+
"Missing EfficientAI trace environment variables: "
|
|
129
|
+
+ ", ".join(missing)
|
|
130
|
+
+ ". Set them in the agent's environment and restart it."
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def warn_deployment_trace_env() -> list[str]:
|
|
135
|
+
"""Log missing variables and return them. The agent can still run without traces."""
|
|
136
|
+
missing = missing_deployment_trace_env()
|
|
137
|
+
if missing:
|
|
138
|
+
logger.warning(
|
|
139
|
+
"EfficientAI call traces disabled: missing %s. The agent will run without "
|
|
140
|
+
"exporting spans.",
|
|
141
|
+
", ".join(missing),
|
|
142
|
+
)
|
|
143
|
+
return missing
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def resolve_trace_transport(runner_args: Any = None, transport: Any = None) -> str:
|
|
147
|
+
"""Infer the call transport (webrtc, websocket, phone, custom) for session labelling."""
|
|
148
|
+
explicit = (_env("EFFICIENTAI_TRACE_TRANSPORT") or "").lower()
|
|
149
|
+
if explicit in VALID_TRANSPORTS:
|
|
150
|
+
return explicit
|
|
151
|
+
|
|
152
|
+
if runner_args is not None:
|
|
153
|
+
runner_transport = getattr(runner_args, "transport", None)
|
|
154
|
+
if isinstance(runner_transport, str) and runner_transport.lower() in VALID_TRANSPORTS:
|
|
155
|
+
return runner_transport.lower()
|
|
156
|
+
if getattr(runner_args, "websocket", None) is not None:
|
|
157
|
+
return "websocket"
|
|
158
|
+
|
|
159
|
+
if transport is not None:
|
|
160
|
+
type_name = type(transport).__name__.lower()
|
|
161
|
+
module_name = (type(transport).__module__ or "").lower()
|
|
162
|
+
if "webrtc" in type_name or "webrtc" in module_name:
|
|
163
|
+
return "webrtc"
|
|
164
|
+
if "websocket" in type_name or "websocket" in module_name:
|
|
165
|
+
return "websocket"
|
|
166
|
+
|
|
167
|
+
return "webrtc"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _run_id_from(otel: dict[str, Any], fallback: Any = None) -> Optional[str]:
|
|
171
|
+
"""Simulation result id carried in the server's ``otel_correlation`` block."""
|
|
172
|
+
attrs = otel.get("suggested_span_attributes") or {}
|
|
173
|
+
value = attrs.get("efficientai.evaluator_result_id") or fallback
|
|
174
|
+
return str(value) if value else None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _disabled_trace_context(error: str) -> dict[str, Any]:
|
|
178
|
+
return {"enabled": False, "error": error, "call_short_id": None}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def trace_session_enabled(trace_ctx: dict[str, Any]) -> bool:
|
|
182
|
+
return bool(trace_ctx.get("enabled") and trace_ctx.get("call_short_id"))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
async def mint_trace_session(
|
|
186
|
+
*,
|
|
187
|
+
workspace_id: str,
|
|
188
|
+
api_key: str,
|
|
189
|
+
api_base_url: Optional[str] = None,
|
|
190
|
+
transport: str = "websocket",
|
|
191
|
+
evaluator_result_id: Optional[str] = None,
|
|
192
|
+
agent_id: Optional[str] = None,
|
|
193
|
+
) -> dict[str, Any]:
|
|
194
|
+
"""Open a trace session. The server mints the six-digit ``call_short_id``.
|
|
195
|
+
|
|
196
|
+
Raises ``TraceSessionError`` on any failure.
|
|
197
|
+
"""
|
|
198
|
+
payload: dict[str, Any] = {"transport": transport}
|
|
199
|
+
if evaluator_result_id:
|
|
200
|
+
payload["evaluator_result_id"] = str(evaluator_result_id)
|
|
201
|
+
if agent_id:
|
|
202
|
+
payload["agent_id"] = str(agent_id)
|
|
203
|
+
|
|
204
|
+
try:
|
|
205
|
+
client = AsyncEfficientAI(
|
|
206
|
+
api_key=api_key,
|
|
207
|
+
workspace_id=workspace_id,
|
|
208
|
+
base_url=api_base_url,
|
|
209
|
+
timeout=_SESSION_TIMEOUT,
|
|
210
|
+
)
|
|
211
|
+
except ConfigurationError as exc:
|
|
212
|
+
raise TraceSessionError(str(exc)) from exc
|
|
213
|
+
url = f"{client.base_url}{SESSIONS_PATH}"
|
|
214
|
+
try:
|
|
215
|
+
body = await client.request("POST", SESSIONS_PATH, json=payload)
|
|
216
|
+
except APIStatusError as exc:
|
|
217
|
+
raise TraceSessionError(
|
|
218
|
+
f"Session API error {exc} (POST {url})", status_code=exc.status_code
|
|
219
|
+
) from exc
|
|
220
|
+
except APITimeoutError as exc:
|
|
221
|
+
raise TraceSessionError(f"Timed out calling EfficientAI session API at {url}") from exc
|
|
222
|
+
except APIConnectionError as exc:
|
|
223
|
+
raise TraceSessionError(
|
|
224
|
+
f"Cannot connect to EfficientAI at {url} (check EFFICIENTAI_BASE_URL and the "
|
|
225
|
+
f"network). Detail: {exc}"
|
|
226
|
+
) from exc
|
|
227
|
+
finally:
|
|
228
|
+
await client.close()
|
|
229
|
+
|
|
230
|
+
if not isinstance(body, dict) or not body.get("call_short_id"):
|
|
231
|
+
raise TraceSessionError(f"Unexpected response from {url}: {body!r}")
|
|
232
|
+
return body
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
async def ensure_trace_session(
|
|
236
|
+
*,
|
|
237
|
+
transport: str = "websocket",
|
|
238
|
+
handshake: Optional[dict[str, Any]] = None,
|
|
239
|
+
strict: bool = False,
|
|
240
|
+
) -> dict[str, Any]:
|
|
241
|
+
"""Resolve the trace context for this call.
|
|
242
|
+
|
|
243
|
+
Sources, in order:
|
|
244
|
+
|
|
245
|
+
1. An EfficientAI handshake message (test calls from the platform).
|
|
246
|
+
2. ``EFFICIENTAI_CALL_SHORT_ID`` (manual development fallback).
|
|
247
|
+
3. A new session from the session API, using ``EFFICIENTAI_API_KEY`` and
|
|
248
|
+
``EFFICIENTAI_WORKSPACE_ID``.
|
|
249
|
+
|
|
250
|
+
Unless ``strict`` is set, failures return ``{"enabled": False, "error": ...}`` so the
|
|
251
|
+
agent can carry on without traces.
|
|
252
|
+
"""
|
|
253
|
+
if handshake:
|
|
254
|
+
parsed = parse_trace_handshake(handshake)
|
|
255
|
+
if parsed:
|
|
256
|
+
otel = parsed.get("otel_correlation") or {}
|
|
257
|
+
return {
|
|
258
|
+
"enabled": True,
|
|
259
|
+
"call_short_id": parsed["call_short_id"],
|
|
260
|
+
"agent_id": parsed.get("agent_id"),
|
|
261
|
+
"workspace_id": parsed.get("workspace_id"),
|
|
262
|
+
"transport": parsed.get("transport") or transport,
|
|
263
|
+
"evaluator_result_id": _run_id_from(otel, handshake.get("evaluator_result_id")),
|
|
264
|
+
"otlp_endpoint": resolve_otlp_endpoint(otel.get("otlp_endpoint")),
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
call_short_id = _env("EFFICIENTAI_CALL_SHORT_ID")
|
|
268
|
+
if call_short_id:
|
|
269
|
+
return {
|
|
270
|
+
"enabled": True,
|
|
271
|
+
"call_short_id": call_short_id,
|
|
272
|
+
"agent_id": _env("EFFICIENTAI_AGENT_ID"),
|
|
273
|
+
"workspace_id": _env(ENV_WORKSPACE_ID),
|
|
274
|
+
"transport": transport,
|
|
275
|
+
"otlp_endpoint": resolve_otlp_endpoint(),
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
missing = missing_deployment_trace_env()
|
|
279
|
+
if missing:
|
|
280
|
+
if strict:
|
|
281
|
+
require_deployment_trace_env()
|
|
282
|
+
msg = "Missing EfficientAI env: " + ", ".join(missing)
|
|
283
|
+
logger.warning("%s. The agent will run without call traces.", msg)
|
|
284
|
+
return _disabled_trace_context(msg)
|
|
285
|
+
|
|
286
|
+
api_key = _env(ENV_API_KEY) or ""
|
|
287
|
+
workspace_id = _env(ENV_WORKSPACE_ID) or ""
|
|
288
|
+
try:
|
|
289
|
+
session = await mint_trace_session(
|
|
290
|
+
workspace_id=workspace_id,
|
|
291
|
+
api_key=api_key,
|
|
292
|
+
transport=transport,
|
|
293
|
+
agent_id=_env("EFFICIENTAI_AGENT_ID"),
|
|
294
|
+
)
|
|
295
|
+
except TraceSessionError as exc:
|
|
296
|
+
if strict:
|
|
297
|
+
raise
|
|
298
|
+
logger.error("EfficientAI trace session failed: %s", exc)
|
|
299
|
+
return _disabled_trace_context(str(exc))
|
|
300
|
+
|
|
301
|
+
otel = session.get("otel_correlation") or {}
|
|
302
|
+
return {
|
|
303
|
+
"enabled": True,
|
|
304
|
+
"call_short_id": session["call_short_id"],
|
|
305
|
+
"trace_id": session.get("trace_id"),
|
|
306
|
+
"workspace_id": session.get("workspace_id") or workspace_id,
|
|
307
|
+
"transport": session.get("transport") or transport,
|
|
308
|
+
"evaluator_result_id": _run_id_from(otel),
|
|
309
|
+
"otlp_endpoint": resolve_otlp_endpoint(otel.get("otlp_endpoint")),
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def setup_worker_tracing(
|
|
314
|
+
trace_ctx: dict[str, Any], *, service_name: str = "pipecat-agent"
|
|
315
|
+
) -> dict[str, Any]:
|
|
316
|
+
"""Point OTLP export at the call in ``trace_ctx``.
|
|
317
|
+
|
|
318
|
+
Returns ``enabled`` plus ``additional_span_attributes`` to pass to a pipeline (for
|
|
319
|
+
example Pipecat's ``PipelineTask``). A disabled context is a no-op.
|
|
320
|
+
"""
|
|
321
|
+
if not trace_session_enabled(trace_ctx):
|
|
322
|
+
return {
|
|
323
|
+
"enabled": False,
|
|
324
|
+
"additional_span_attributes": {},
|
|
325
|
+
"call_short_id": None,
|
|
326
|
+
"transport": trace_ctx.get("transport"),
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
call_short_id = trace_ctx["call_short_id"]
|
|
330
|
+
agent_id = trace_ctx.get("agent_id")
|
|
331
|
+
workspace_id = trace_ctx.get("workspace_id")
|
|
332
|
+
transport = trace_ctx.get("transport")
|
|
333
|
+
run_id = trace_ctx.get("evaluator_result_id")
|
|
334
|
+
|
|
335
|
+
setup_efficientai_tracing(
|
|
336
|
+
service_name=service_name,
|
|
337
|
+
call_short_id=call_short_id,
|
|
338
|
+
evaluator_result_id=str(run_id) if run_id else None,
|
|
339
|
+
agent_id=str(agent_id) if agent_id else None,
|
|
340
|
+
workspace_id=str(workspace_id) if workspace_id else None,
|
|
341
|
+
transport=str(transport) if transport else None,
|
|
342
|
+
otlp_endpoint=trace_ctx.get("otlp_endpoint"),
|
|
343
|
+
api_key=_env(ENV_API_KEY),
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
attrs = span_correlation_attributes(
|
|
347
|
+
call_short_id=call_short_id,
|
|
348
|
+
evaluator_result_id=str(run_id) if run_id else None,
|
|
349
|
+
agent_id=str(agent_id) if agent_id else None,
|
|
350
|
+
workspace_id=str(workspace_id) if workspace_id else None,
|
|
351
|
+
transport=str(transport) if transport else None,
|
|
352
|
+
)
|
|
353
|
+
return {
|
|
354
|
+
"enabled": True,
|
|
355
|
+
"additional_span_attributes": attrs,
|
|
356
|
+
"call_short_id": call_short_id,
|
|
357
|
+
"transport": transport,
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
async def close_trace_session(trace_ctx: dict[str, Any]) -> None:
|
|
362
|
+
"""Flush spans and close the session. Never raises; failures are logged."""
|
|
363
|
+
if not trace_session_enabled(trace_ctx):
|
|
364
|
+
return
|
|
365
|
+
flush_efficientai_tracing()
|
|
366
|
+
|
|
367
|
+
call_short_id = trace_ctx.get("call_short_id")
|
|
368
|
+
api_key = _env(ENV_API_KEY)
|
|
369
|
+
workspace_id = trace_ctx.get("workspace_id") or _env(ENV_WORKSPACE_ID)
|
|
370
|
+
if not call_short_id or not api_key or not workspace_id:
|
|
371
|
+
return
|
|
372
|
+
|
|
373
|
+
try:
|
|
374
|
+
client = AsyncEfficientAI(
|
|
375
|
+
api_key=api_key, workspace_id=str(workspace_id), timeout=_SESSION_TIMEOUT
|
|
376
|
+
)
|
|
377
|
+
except EfficientAIError as exc:
|
|
378
|
+
logger.warning("EfficientAI trace close skipped: %s", exc)
|
|
379
|
+
return
|
|
380
|
+
try:
|
|
381
|
+
await client.request("POST", f"{SESSIONS_PATH}/{call_short_id}/close")
|
|
382
|
+
except EfficientAIError as exc:
|
|
383
|
+
logger.warning("EfficientAI trace close failed: %s", exc)
|
|
384
|
+
finally:
|
|
385
|
+
await client.close()
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: efficientai-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for EfficientAI: live traces, simulations and evaluations for voice and chat agents.
|
|
5
|
+
Project-URL: Homepage, https://efficientai.cloud
|
|
6
|
+
Project-URL: Documentation, https://docs.efficientai.cloud
|
|
7
|
+
Project-URL: Source, https://github.com/EfficientAI-tech/efficientAI/tree/main/sdks/python
|
|
8
|
+
Project-URL: Changelog, https://github.com/EfficientAI-tech/efficientAI/blob/main/sdks/python/CHANGELOG.md
|
|
9
|
+
Author: EfficientAI
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: efficientai,evaluation,observability,opentelemetry,simulation,voice agents
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Requires-Dist: httpx<1,>=0.25
|
|
27
|
+
Requires-Dist: pydantic<3,>=2.5
|
|
28
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
29
|
+
Provides-Extra: otel
|
|
30
|
+
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27.0; extra == 'otel'
|
|
31
|
+
Requires-Dist: opentelemetry-sdk>=1.27.0; extra == 'otel'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# EfficientAI Python SDK
|
|
35
|
+
|
|
36
|
+
The official Python client for [EfficientAI](https://efficientai.cloud). Use it to send live traces from your voice and chat agents, run simulations, and read evaluation results.
|
|
37
|
+
|
|
38
|
+
> **Status: alpha (0.x).** The client core is in place. Live tracing and simulations are being added; see the [changelog](CHANGELOG.md).
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install efficientai-sdk
|
|
44
|
+
# with OpenTelemetry tracing support
|
|
45
|
+
pip install "efficientai-sdk[otel]"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Requires Python 3.9 or newer.
|
|
49
|
+
|
|
50
|
+
## Configure
|
|
51
|
+
|
|
52
|
+
EfficientAI is self-hosted, so point the SDK at your own deployment. If no URL is set, it uses `http://localhost:8000`.
|
|
53
|
+
|
|
54
|
+
Create an API key in your EfficientAI dashboard. Then either set environment variables:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
export EFFICIENTAI_BASE_URL="https://efficientai.your-company.com" # your deployment; default http://localhost:8000
|
|
58
|
+
export EFFICIENTAI_API_KEY="..."
|
|
59
|
+
export EFFICIENTAI_WORKSPACE_ID="..." # optional; the key's default workspace is used otherwise
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
or pass the same values to the client:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from efficientai_sdk import EfficientAI
|
|
66
|
+
|
|
67
|
+
client = EfficientAI(
|
|
68
|
+
base_url="https://efficientai.your-company.com",
|
|
69
|
+
api_key="...",
|
|
70
|
+
workspace_id="...",
|
|
71
|
+
)
|
|
72
|
+
client.verify() # True, or raises AuthenticationError
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
An async client with the same arguments is available:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from efficientai_sdk import AsyncEfficientAI
|
|
79
|
+
|
|
80
|
+
async with AsyncEfficientAI() as client:
|
|
81
|
+
await client.verify()
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Live call tracing
|
|
85
|
+
|
|
86
|
+
Install the `otel` extra, then wrap each call in a trace session. Spans created inside the session are tagged with the call's id and exported to EfficientAI. The session closes when the block ends.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from efficientai_sdk import AsyncEfficientAI
|
|
90
|
+
|
|
91
|
+
efficientai = AsyncEfficientAI()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def handle_call(first_message=None):
|
|
95
|
+
async with efficientai.trace.session(transport="websocket", handshake=first_message) as call:
|
|
96
|
+
with call.turn():
|
|
97
|
+
with call.stt(model="nova-3", provider="deepgram") as stt:
|
|
98
|
+
stt.set_transcript(user_text)
|
|
99
|
+
with call.llm(model="gpt-4o", provider="openai") as llm:
|
|
100
|
+
llm.set_output(reply).set_ttfb(0.31)
|
|
101
|
+
with call.tts(model="sonic", provider="cartesia") as tts:
|
|
102
|
+
tts.set_text(reply)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
- **Chat agents:** `session(channel="chat")` plus `call.user_message()`, `call.tool()`, `call.retrieval()` and `call.llm()`. Each turn shows the user message, the final reply, tool calls and response time.
|
|
106
|
+
- **Pipecat:** `PipelineTask(pipeline, **task_kwargs(call))` with `from efficientai_sdk.integrations.pipecat import task_kwargs`.
|
|
107
|
+
- **LiveKit Agents:** `async with livekit.trace_session(client, ctx) as call:` with `from efficientai_sdk.integrations import livekit`.
|
|
108
|
+
- **Existing OpenTelemetry setup:** call `efficientai.trace.instrument()` once at startup.
|
|
109
|
+
- **Test calls from EfficientAI:** pass the platform's `handshake=`, `headers=` or `sip_headers=` so traces link to the simulation result.
|
|
110
|
+
- **Concurrent calls:** each session is tracked per asyncio task, so one process can serve many calls.
|
|
111
|
+
- **Failures:** tracing never breaks a call. If EfficientAI is unreachable, the call runs untraced and a warning is logged. Pass `strict=True` to raise instead.
|
|
112
|
+
|
|
113
|
+
A runnable example is in [`examples/custom_agent_tracing.py`](examples/custom_agent_tracing.py). The full guide is on the "Python SDK" page of the EfficientAI docs.
|
|
114
|
+
|
|
115
|
+
## Run simulations
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
run = client.simulations.run(
|
|
119
|
+
agent_id="...", scenario_ids=["..."], persona_ids=["..."], n_attempts=2
|
|
120
|
+
)
|
|
121
|
+
run = run.wait(timeout=1800)
|
|
122
|
+
assert run.passed, run.summary
|
|
123
|
+
|
|
124
|
+
suite = client.suites.run("suite-id", runs_per_combination=3)
|
|
125
|
+
suite = suite.wait()
|
|
126
|
+
assert suite.passed, suite.pass_rate
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
From CI:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
efficientai simulate --suite "$EFFICIENTAI_SUITE_ID" --fail-under 0.8
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The command exits `0` at or above the threshold, `1` when the suite scores lower or a result errors, and `2` when the arguments or the API call fail. See `examples/ci/simulate.yml`.
|
|
136
|
+
|
|
137
|
+
## Errors and retries
|
|
138
|
+
|
|
139
|
+
Every error the SDK raises inherits from `EfficientAIError`.
|
|
140
|
+
|
|
141
|
+
| Exception | When |
|
|
142
|
+
|---|---|
|
|
143
|
+
| `ConfigurationError` | Missing API key or invalid settings |
|
|
144
|
+
| `APIConnectionError` / `APITimeoutError` | The server could not be reached |
|
|
145
|
+
| `AuthenticationError` | 401: the key is invalid or inactive |
|
|
146
|
+
| `PermissionDeniedError` | 403 |
|
|
147
|
+
| `NotFoundError` | 404 |
|
|
148
|
+
| `UnprocessableEntityError` | 422: the request failed validation |
|
|
149
|
+
| `RateLimitError` | 429; `retry_after` holds the server's hint |
|
|
150
|
+
| `InternalServerError` | 5xx |
|
|
151
|
+
|
|
152
|
+
The client retries failed requests up to `max_retries` times (default 2), with exponential backoff and jitter. It honours the server's `Retry-After` header.
|
|
153
|
+
- `GET`, `PUT` and `DELETE` retry on timeouts, 408, 429 and 5xx responses.
|
|
154
|
+
- `POST` and `PATCH` retry only when the server certainly didn't process the request: 429, 503, or a failed connection.
|
|
155
|
+
|
|
156
|
+
Set `max_retries=0` to turn retries off.
|
|
157
|
+
|
|
158
|
+
## Development
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
cd sdks/python
|
|
162
|
+
uv sync
|
|
163
|
+
uv run pytest
|
|
164
|
+
uv run ruff check . && uv run ruff format --check .
|
|
165
|
+
uv run mypy
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Releases are published to PyPI from tags named `sdk-py-v<version>`, which must match `src/efficientai_sdk/_version.py`.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
efficientai_sdk/__init__.py,sha256=3y6bIWEalCLDvf0Z_OvBfC0mZXH3_m8DK9V1C5dAhA0,964
|
|
2
|
+
efficientai_sdk/_base_client.py,sha256=5nkIRiEoiFOmdczrj8ZIfmVHLvkIXNa5lzpf-pVpZl0,11159
|
|
3
|
+
efficientai_sdk/_client.py,sha256=HsTWZubvQYj-nK4YtFf9brYVV5NxM04ARUKrk5MEAwI,6209
|
|
4
|
+
efficientai_sdk/_config.py,sha256=rCIo6PweDCO2iPbM2JbatMbUVAW6IaF9oIER0ThV2ow,4624
|
|
5
|
+
efficientai_sdk/_exceptions.py,sha256=czJwsT5L9z1b8ogAkk48MER6wXc8QwCqw108zN2TyFY,4231
|
|
6
|
+
efficientai_sdk/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
7
|
+
efficientai_sdk/cli.py,sha256=XsMvd4-HWwutcWS7jIEPoNZuX6b1_gv1WG55pSnwFR8,3345
|
|
8
|
+
efficientai_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
efficientai_sdk/integrations/__init__.py,sha256=FVZqDbnGieoJWyD-6ot4lJfdr49gFK7KYj2-WFb7UJ8,132
|
|
10
|
+
efficientai_sdk/integrations/livekit.py,sha256=xGRyJD9gqMv_UnEYzdmW_rcms4-iCJxHXILE1WsP7lM,3945
|
|
11
|
+
efficientai_sdk/integrations/pipecat.py,sha256=ZwoIFFf7jQhDgI4coxDr6Uos6EBoNbh-aaLnEtLHbyw,4573
|
|
12
|
+
efficientai_sdk/simulations/__init__.py,sha256=SwPNQfJwSLzLOkR8DiVk497dkCy_oeWKS_G8CVi7Zlg,549
|
|
13
|
+
efficientai_sdk/simulations/api.py,sha256=Flixomn0lp50iMc4LrxJd_j_Q0nOyjcD7c4LT1Z-tfk,24220
|
|
14
|
+
efficientai_sdk/simulations/models.py,sha256=FDUTEzCLhpaiCrRPFjl9kUonmvxt25OtFM4bmoEL5ec,6417
|
|
15
|
+
efficientai_sdk/simulations/polling.py,sha256=gKgqTcj_rOWue6KsNOaE_JRe7yeQXt50PdhlbsOtYqs,1838
|
|
16
|
+
efficientai_sdk/tracing/__init__.py,sha256=0qBxJQhDJ2qz_URpOab8THvdZnPpR_1EcUJus_FsiqI,2882
|
|
17
|
+
efficientai_sdk/tracing/api.py,sha256=y_rNDoePatPP9H2bgcgCsARCt8pa2iS7cn1_4GSeS_E,31166
|
|
18
|
+
efficientai_sdk/tracing/context.py,sha256=nza9WhLeeRKXeVq6aw9Mwhg7xWVvPOH1xCMAl8wl9Bo,1955
|
|
19
|
+
efficientai_sdk/tracing/correlation.py,sha256=TcJgVW1GRsKnJEvV8ih8GZLAysTUEFT_N3gSw0YHXrs,6266
|
|
20
|
+
efficientai_sdk/tracing/handshake.py,sha256=nk2xsIi4XRCqXSaCusXjezjQxtdPK295M1TZ7vDTkLk,1502
|
|
21
|
+
efficientai_sdk/tracing/otel.py,sha256=rZnVgrBa_v_kdP1LWHfoY-ccatpjQ3fJhtM8qEMxHxs,19593
|
|
22
|
+
efficientai_sdk/tracing/session.py,sha256=j6Wdw9Yr43P924JMgSXwUmaN4O5EuY94eZUGSkZZTLk,13795
|
|
23
|
+
efficientai_sdk-0.1.0.dist-info/METADATA,sha256=x-NeIL12w_0lal7bdBbQ3VVKyKnQ-KabqkWxVaHQpEE,6730
|
|
24
|
+
efficientai_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
25
|
+
efficientai_sdk-0.1.0.dist-info/entry_points.txt,sha256=XRU-iWz5x1WYS8GUT3lFcA4Q0FaHwdugSbbbiJNEjmI,58
|
|
26
|
+
efficientai_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=mvLnS-2bOI2yuVy_C-zNewJ1uVD8xypBmnUQOG9vKBw,1073
|
|
27
|
+
efficientai_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 EfficientAI.tech
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|