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,142 @@
1
+ """Exception hierarchy. Catch ``EfficientAIError`` to handle everything the SDK raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+ import httpx
8
+
9
+
10
+ class EfficientAIError(Exception):
11
+ """Base class for all SDK errors."""
12
+
13
+
14
+ class ConfigurationError(EfficientAIError, ValueError):
15
+ """The client was configured incorrectly (for example, no API key).
16
+
17
+ Also a ``ValueError``, so code written against the older trace helpers keeps working.
18
+ """
19
+
20
+
21
+ class APIConnectionError(EfficientAIError):
22
+ """The request never got a response (DNS, connection refused, TLS, ...)."""
23
+
24
+ def __init__(
25
+ self, message: str = "Connection error.", *, request: Optional[httpx.Request] = None
26
+ ):
27
+ super().__init__(message)
28
+ self.request = request
29
+
30
+
31
+ class APITimeoutError(APIConnectionError):
32
+ """The request timed out, or a polled run did not finish in time."""
33
+
34
+ def __init__(
35
+ self,
36
+ message: str = "Request timed out.",
37
+ *,
38
+ request: Optional[httpx.Request] = None,
39
+ ):
40
+ super().__init__(message, request=request)
41
+
42
+
43
+ class APIStatusError(EfficientAIError):
44
+ """The API returned a non-success status code."""
45
+
46
+ status_code: int
47
+
48
+ def __init__(self, message: str, *, response: httpx.Response, body: Any):
49
+ super().__init__(message)
50
+ self.response = response
51
+ self.status_code = response.status_code
52
+ self.body = body
53
+ self.request_id: Optional[str] = response.headers.get("x-request-id")
54
+
55
+
56
+ class BadRequestError(APIStatusError):
57
+ """400"""
58
+
59
+
60
+ class AuthenticationError(APIStatusError):
61
+ """401: the API key is missing, invalid or inactive."""
62
+
63
+
64
+ class PermissionDeniedError(APIStatusError):
65
+ """403: the key is valid but cannot access this resource or workspace."""
66
+
67
+
68
+ class NotFoundError(APIStatusError):
69
+ """404"""
70
+
71
+
72
+ class ConflictError(APIStatusError):
73
+ """409"""
74
+
75
+
76
+ class UnprocessableEntityError(APIStatusError):
77
+ """422: the request body failed validation."""
78
+
79
+
80
+ class RateLimitError(APIStatusError):
81
+ """429: slow down. ``retry_after`` is the server's hint in seconds, if it sent one."""
82
+
83
+ def __init__(self, message: str, *, response: httpx.Response, body: Any):
84
+ super().__init__(message, response=response, body=body)
85
+ self.retry_after: Optional[float] = parse_retry_after(response.headers.get("retry-after"))
86
+
87
+
88
+ class InternalServerError(APIStatusError):
89
+ """5xx"""
90
+
91
+
92
+ _STATUS_ERRORS: dict[int, type[APIStatusError]] = {
93
+ 400: BadRequestError,
94
+ 401: AuthenticationError,
95
+ 403: PermissionDeniedError,
96
+ 404: NotFoundError,
97
+ 409: ConflictError,
98
+ 422: UnprocessableEntityError,
99
+ 429: RateLimitError,
100
+ }
101
+
102
+
103
+ def parse_retry_after(value: Optional[str]) -> Optional[float]:
104
+ """Parse a Retry-After header given in seconds. HTTP-date values are ignored."""
105
+ if not value:
106
+ return None
107
+ try:
108
+ seconds = float(value.strip())
109
+ except ValueError:
110
+ return None
111
+ return seconds if seconds >= 0 else None
112
+
113
+
114
+ def _error_message(response: httpx.Response, body: Any) -> str:
115
+ detail: Any = None
116
+ if isinstance(body, dict):
117
+ detail = body.get("detail") or body.get("message") or body.get("error")
118
+ elif isinstance(body, str) and body.strip():
119
+ detail = body.strip()
120
+
121
+ if isinstance(detail, list): # FastAPI validation errors
122
+ parts = []
123
+ for item in detail:
124
+ if isinstance(item, dict):
125
+ loc = ".".join(str(p) for p in item.get("loc", []) if p != "body")
126
+ msg = item.get("msg", "")
127
+ parts.append(f"{loc}: {msg}" if loc else str(msg))
128
+ else:
129
+ parts.append(str(item))
130
+ detail = "; ".join(parts)
131
+
132
+ text = str(detail) if detail else response.reason_phrase or "Unknown error"
133
+ if len(text) > 500:
134
+ text = text[:500] + "..."
135
+ return f"{response.status_code}: {text}"
136
+
137
+
138
+ def make_status_error(response: httpx.Response, body: Any) -> APIStatusError:
139
+ cls = _STATUS_ERRORS.get(response.status_code)
140
+ if cls is None:
141
+ cls = InternalServerError if response.status_code >= 500 else APIStatusError
142
+ return cls(_error_message(response, body), response=response, body=body)
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
efficientai_sdk/cli.py ADDED
@@ -0,0 +1,99 @@
1
+ """Command line: ``efficientai simulate --suite ... --fail-under 0.8``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Sequence
8
+ from typing import Optional
9
+
10
+ from efficientai_sdk import EfficientAI, EfficientAIError
11
+ from efficientai_sdk.simulations.api import ResultBatch
12
+
13
+
14
+ def main(argv: Optional[Sequence[str]] = None) -> int:
15
+ """Run a suite and return a process exit code.
16
+
17
+ ``0`` when the pass rate is at least ``--fail-under`` and no result errored.
18
+ ``1`` when the suite finishes below that bar.
19
+ ``2`` when the arguments or the API call fail.
20
+ """
21
+ parser = argparse.ArgumentParser(prog="efficientai")
22
+ sub = parser.add_subparsers(dest="command", required=True)
23
+ simulate = sub.add_parser("simulate", help="Run a suite and fail under a pass rate")
24
+ simulate.add_argument("--suite", required=True, help="Evaluator suite id")
25
+ simulate.add_argument(
26
+ "--fail-under",
27
+ required=True,
28
+ type=float,
29
+ help="Exit 1 when the pass rate is below this value (0 to 1)",
30
+ )
31
+ simulate.add_argument(
32
+ "--runs-per-combination",
33
+ type=int,
34
+ default=None,
35
+ help="Repeat each scenario/persona pair this many times (default: the suite's saved count)",
36
+ )
37
+ simulate.add_argument(
38
+ "--to-number",
39
+ default=None,
40
+ help="Recipient number for phone or messaging suites",
41
+ )
42
+ simulate.add_argument(
43
+ "--from-number",
44
+ default=None,
45
+ help="Caller number when the suite places an outbound call",
46
+ )
47
+ simulate.add_argument(
48
+ "--timeout", type=float, default=1800, help="Seconds to wait (default 1800)"
49
+ )
50
+ simulate.add_argument("--interval", type=float, default=2.0, help="Seconds between polls")
51
+
52
+ try:
53
+ args = parser.parse_args(list(argv) if argv is not None else None)
54
+ except SystemExit as exc:
55
+ code = exc.code
56
+ return code if isinstance(code, int) else 2
57
+
58
+ if args.command != "simulate":
59
+ parser.print_help(sys.stderr)
60
+ return 2
61
+ if not 0.0 <= args.fail_under <= 1.0:
62
+ print("--fail-under must be between 0 and 1", file=sys.stderr)
63
+ return 2
64
+ if args.timeout <= 0:
65
+ print("--timeout must be greater than 0", file=sys.stderr)
66
+ return 2
67
+
68
+ try:
69
+ with EfficientAI() as client:
70
+ batch = client.suites.run(
71
+ args.suite,
72
+ runs_per_combination=args.runs_per_combination,
73
+ to_number=args.to_number,
74
+ from_number=args.from_number,
75
+ )
76
+ finished = batch.wait(timeout=args.timeout, interval=args.interval)
77
+ except EfficientAIError as exc:
78
+ print(str(exc), file=sys.stderr)
79
+ return 2
80
+
81
+ _print_summary(finished)
82
+ if finished.meets(args.fail_under):
83
+ return 0
84
+ return 1
85
+
86
+
87
+ def _print_summary(batch: ResultBatch) -> None:
88
+ total = len(batch.results)
89
+ ok = sum(1 for result in batch.results if result.succeeded)
90
+ print(f"pass rate {batch.pass_rate:.0%} ({ok}/{total})")
91
+
92
+
93
+ def entry() -> None:
94
+ """Setuptools entry point. ``main`` returns the code so tests can call it."""
95
+ raise SystemExit(main())
96
+
97
+
98
+ if __name__ == "__main__":
99
+ entry()
@@ -0,0 +1,4 @@
1
+ """Framework integrations.
2
+
3
+ Import the submodule you need, for example ``efficientai_sdk.integrations.pipecat`` or ``livekit``.
4
+ """
@@ -0,0 +1,134 @@
1
+ """LiveKit Agents helpers.
2
+
3
+ Does not import LiveKit — pass your job's ``JobContext`` and open a trace session
4
+ before ``AgentSession.start``.
5
+
6
+ Recommended::
7
+
8
+ client = AsyncEfficientAI()
9
+
10
+ async def entrypoint(ctx, session):
11
+ async with livekit.trace_session(client, ctx) as call:
12
+ await session.start(room=ctx.room, agent=MyAgent())
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from collections.abc import Mapping
19
+ from contextlib import AbstractAsyncContextManager
20
+ from types import TracebackType
21
+ from typing import TYPE_CHECKING, Any, Optional
22
+
23
+ from efficientai_sdk.tracing.handshake import parse_trace_handshake
24
+
25
+ if TYPE_CHECKING:
26
+ from efficientai_sdk import AsyncEfficientAI
27
+ from efficientai_sdk.tracing.api import CallTrace
28
+
29
+ __all__ = [
30
+ "job_handshake",
31
+ "trace_session",
32
+ ]
33
+
34
+
35
+ def _job_metadata(job_ctx: Any) -> Optional[Mapping[str, Any]]:
36
+ job = getattr(job_ctx, "job", None)
37
+ if job is None:
38
+ return None
39
+ raw = getattr(job, "metadata", None)
40
+ if raw is None:
41
+ return None
42
+ if isinstance(raw, str):
43
+ text = raw.strip()
44
+ if not text:
45
+ return None
46
+ try:
47
+ parsed = json.loads(text)
48
+ except json.JSONDecodeError:
49
+ return None
50
+ return parsed if isinstance(parsed, Mapping) else None
51
+ if isinstance(raw, Mapping):
52
+ return raw
53
+ return None
54
+
55
+
56
+ def job_handshake(job_ctx: Any) -> Optional[dict[str, Any]]:
57
+ """Read an EfficientAI handshake from LiveKit job metadata when present."""
58
+ meta = _job_metadata(job_ctx)
59
+ if not meta:
60
+ return None
61
+
62
+ direct = parse_trace_handshake(meta)
63
+ if direct:
64
+ return direct
65
+
66
+ for key in ("efficientai_trace_handshake", "handshake", "efficientai"):
67
+ nested = meta.get(key)
68
+ if isinstance(nested, Mapping):
69
+ parsed = parse_trace_handshake(nested)
70
+ if parsed:
71
+ return parsed
72
+ return None
73
+
74
+
75
+ class _LiveKitTraceSession:
76
+ def __init__(
77
+ self,
78
+ client: AsyncEfficientAI,
79
+ session_cm: AbstractAsyncContextManager[CallTrace],
80
+ *,
81
+ instrument: bool,
82
+ ) -> None:
83
+ self._client = client
84
+ self._session_cm = session_cm
85
+ self._instrument = instrument
86
+
87
+ async def __aenter__(self) -> CallTrace:
88
+ call = await self._session_cm.__aenter__()
89
+ if self._instrument and call.enabled:
90
+ self._client.trace.instrument()
91
+ return call
92
+
93
+ async def __aexit__(
94
+ self,
95
+ exc_type: type[BaseException] | None,
96
+ exc_val: BaseException | None,
97
+ exc_tb: TracebackType | None,
98
+ ) -> bool | None:
99
+ return await self._session_cm.__aexit__(exc_type, exc_val, exc_tb)
100
+
101
+
102
+ def trace_session(
103
+ client: AsyncEfficientAI,
104
+ job_ctx: Any = None,
105
+ *,
106
+ transport: str = "webrtc",
107
+ handshake: Optional[Mapping[str, Any]] = None,
108
+ headers: Optional[Mapping[str, Any]] = None,
109
+ agent_id: Optional[str] = None,
110
+ instrument: bool = True,
111
+ **kwargs: Any,
112
+ ) -> _LiveKitTraceSession:
113
+ """Async context manager: open a call trace, optionally wire LiveKit OTLP spans.
114
+
115
+ Correlation order: explicit ``handshake``, then :func:`job_handshake` on
116
+ ``job_ctx``, then HTTP-style ``headers``.
117
+ """
118
+ resolved = handshake
119
+ if resolved is None and job_ctx is not None:
120
+ resolved = job_handshake(job_ctx)
121
+
122
+ session_kw: dict[str, Any] = {"transport": transport, **kwargs}
123
+ if resolved is not None:
124
+ session_kw["handshake"] = resolved
125
+ elif headers is not None:
126
+ session_kw["headers"] = headers
127
+ if agent_id is not None:
128
+ session_kw["agent_id"] = agent_id
129
+
130
+ return _LiveKitTraceSession(
131
+ client,
132
+ client.trace.session(**session_kw),
133
+ instrument=instrument,
134
+ )
@@ -0,0 +1,126 @@
1
+ """Pipecat helpers. These return keyword arguments for ``PipelineTask`` and don't import
2
+ Pipecat themselves, so they work with any Pipecat version that supports
3
+ ``enable_tracing`` and ``additional_span_attributes``.
4
+
5
+ Recommended (one session per call, safe with concurrent calls)::
6
+
7
+ client = AsyncEfficientAI()
8
+
9
+ async def run_bot(transport, first_message=None):
10
+ async with client.trace.session(transport="webrtc", handshake=first_message) as call:
11
+ task = PipelineTask(pipeline, **task_kwargs(call))
12
+ await PipelineRunner().run(task)
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from collections.abc import Mapping
19
+ from typing import Any, Optional
20
+
21
+ from efficientai_sdk.tracing.api import CallTrace
22
+ from efficientai_sdk.tracing.correlation import span_correlation_attributes
23
+ from efficientai_sdk.tracing.handshake import parse_trace_handshake
24
+ from efficientai_sdk.tracing.otel import _resolve_call_short_id, setup_efficientai_tracing
25
+ from efficientai_sdk.tracing.session import setup_worker_tracing
26
+
27
+ __all__ = [
28
+ "configure_pipecat_tracing",
29
+ "configure_pipecat_tracing_from_handshake",
30
+ "setup_pipecat_worker_tracing",
31
+ "task_kwargs",
32
+ ]
33
+
34
+
35
+ def _env(name: str) -> Optional[str]:
36
+ value = os.environ.get(name)
37
+ if value is None or not value.strip():
38
+ return None
39
+ return value.strip()
40
+
41
+
42
+ def configure_pipecat_tracing(
43
+ *,
44
+ call_short_id: Optional[str] = None,
45
+ agent_id: Optional[str] = None,
46
+ workspace_id: Optional[str] = None,
47
+ otlp_endpoint: Optional[str] = None,
48
+ api_key: Optional[str] = None,
49
+ sip_headers: Optional[Mapping[str, Any]] = None,
50
+ webhook_params: Optional[Mapping[str, Any]] = None,
51
+ handshake: Optional[Mapping[str, Any]] = None,
52
+ additional_span_attributes: Optional[dict[str, str]] = None,
53
+ service_name: str = "pipecat-agent",
54
+ ) -> dict[str, Any]:
55
+ """Configure OTLP export for this call and return ``PipelineTask`` keyword arguments."""
56
+ if handshake is not None:
57
+ return configure_pipecat_tracing_from_handshake(
58
+ handshake, api_key=api_key, service_name=service_name
59
+ )
60
+
61
+ if not setup_efficientai_tracing(
62
+ service_name=service_name,
63
+ call_short_id=call_short_id,
64
+ agent_id=agent_id,
65
+ workspace_id=workspace_id,
66
+ otlp_endpoint=otlp_endpoint,
67
+ api_key=api_key,
68
+ sip_headers=sip_headers,
69
+ webhook_params=webhook_params,
70
+ ):
71
+ return {
72
+ "enable_tracing": False,
73
+ "additional_span_attributes": {},
74
+ }
75
+ attrs = span_correlation_attributes(
76
+ call_short_id=_resolve_call_short_id(
77
+ call_short_id=call_short_id, sip_headers=sip_headers, webhook_params=webhook_params
78
+ ),
79
+ evaluator_result_id=_env("EFFICIENTAI_RUN_ID"),
80
+ agent_id=agent_id or _env("EFFICIENTAI_AGENT_ID"),
81
+ workspace_id=workspace_id or _env("EFFICIENTAI_WORKSPACE_ID"),
82
+ )
83
+ if additional_span_attributes:
84
+ attrs.update(additional_span_attributes)
85
+ return {"enable_tracing": True, "additional_span_attributes": attrs}
86
+
87
+
88
+ def configure_pipecat_tracing_from_handshake(
89
+ message: Mapping[str, Any],
90
+ *,
91
+ api_key: Optional[str] = None,
92
+ service_name: str = "pipecat-agent",
93
+ ) -> dict[str, Any]:
94
+ """Like :func:`configure_pipecat_tracing`, using an EfficientAI handshake message.
95
+
96
+ Only ``EFFICIENTAI_API_KEY`` has to be set on the agent; the call id, agent,
97
+ workspace and OTLP endpoint come from the handshake.
98
+ """
99
+ handshake = parse_trace_handshake(message)
100
+ if not handshake:
101
+ raise ValueError("Message is not an EfficientAI trace handshake")
102
+
103
+ otel = handshake.get("otel_correlation") or {}
104
+ return configure_pipecat_tracing(
105
+ call_short_id=handshake["call_short_id"],
106
+ agent_id=str(handshake["agent_id"]) if handshake.get("agent_id") else None,
107
+ workspace_id=str(handshake["workspace_id"]) if handshake.get("workspace_id") else None,
108
+ otlp_endpoint=otel.get("otlp_endpoint"),
109
+ api_key=api_key,
110
+ service_name=service_name,
111
+ )
112
+
113
+
114
+ setup_pipecat_worker_tracing = setup_worker_tracing
115
+
116
+
117
+ def task_kwargs(call: CallTrace, **extra_attributes: str) -> dict[str, Any]:
118
+ """``PipelineTask`` keyword arguments that trace the pipeline into ``call``.
119
+
120
+ Returns ``{}`` when the call is disabled, so the pipeline runs untraced.
121
+ """
122
+ if not call.enabled:
123
+ return {}
124
+ attrs = call.attributes
125
+ attrs.update(extra_attributes)
126
+ return {"enable_tracing": True, "additional_span_attributes": attrs}
File without changes
@@ -0,0 +1,25 @@
1
+ """Start simulations and read evaluation results."""
2
+
3
+ from efficientai_sdk.simulations.api import (
4
+ AsyncResultBatch,
5
+ AsyncSimulationRun,
6
+ ResultBatch,
7
+ SimulationRun,
8
+ )
9
+ from efficientai_sdk.simulations.models import (
10
+ EvaluatorResult,
11
+ EvaluatorResultPage,
12
+ FailureAnalysis,
13
+ SimulationTrial,
14
+ )
15
+
16
+ __all__ = [
17
+ "AsyncResultBatch",
18
+ "AsyncSimulationRun",
19
+ "EvaluatorResult",
20
+ "EvaluatorResultPage",
21
+ "FailureAnalysis",
22
+ "ResultBatch",
23
+ "SimulationRun",
24
+ "SimulationTrial",
25
+ ]