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,186 @@
1
+ """Response models for simulations, suite runs and evaluator results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
8
+
9
+ TERMINAL_RUN_STATUSES = frozenset({"completed", "failed", "cancelled"})
10
+ TERMINAL_RESULT_STATUSES = frozenset({"completed", "failed"})
11
+
12
+
13
+ def _stringify(value: object) -> object:
14
+ if value is None:
15
+ return None
16
+ return str(value)
17
+
18
+
19
+ class APIModel(BaseModel):
20
+ """Server payload. Unknown fields are kept."""
21
+
22
+ model_config = ConfigDict(extra="allow")
23
+
24
+
25
+ class SimulationRunData(APIModel):
26
+ id: str
27
+ status: str
28
+ run_id: Optional[str] = None
29
+ agent_id: Optional[str] = None
30
+ pass_threshold: float = 0.7
31
+ summary: Optional[dict[str, Any]] = None
32
+ error_message: Optional[str] = None
33
+ expected_trials: Optional[int] = None
34
+ completed_trials: Optional[int] = None
35
+ failed_trials: Optional[int] = None
36
+
37
+ @field_validator("id", "run_id", "agent_id", mode="before")
38
+ @classmethod
39
+ def _ids(cls, value: object) -> object:
40
+ return _stringify(value)
41
+
42
+ @field_validator("status", mode="before")
43
+ @classmethod
44
+ def _status(cls, value: object) -> object:
45
+ if isinstance(value, str):
46
+ return value.strip().lower()
47
+ return value
48
+
49
+ @property
50
+ def passed(self) -> bool:
51
+ """True when the run completed and its pass rate meets ``pass_threshold``."""
52
+ if self.status != "completed" or not isinstance(self.summary, dict):
53
+ return False
54
+ rate = self.summary.get("pass_rate")
55
+ if rate is None:
56
+ return False
57
+ try:
58
+ return float(rate) >= float(self.pass_threshold)
59
+ except (TypeError, ValueError):
60
+ return False
61
+
62
+
63
+ class SimulationTrial(APIModel):
64
+ id: str
65
+ status: str
66
+ result_id: Optional[str] = None
67
+ scenario_id: Optional[str] = None
68
+ persona_id: Optional[str] = None
69
+ attempt_index: Optional[int] = None
70
+ reward: Optional[float] = None
71
+ passed: Optional[bool] = None
72
+ error_message: Optional[str] = None
73
+
74
+ @field_validator("id", "result_id", "scenario_id", "persona_id", mode="before")
75
+ @classmethod
76
+ def _ids(cls, value: object) -> object:
77
+ return _stringify(value)
78
+
79
+ @field_validator("status", mode="before")
80
+ @classmethod
81
+ def _status(cls, value: object) -> object:
82
+ if isinstance(value, str):
83
+ return value.strip().lower()
84
+ return value
85
+
86
+
87
+ class FailureAnalysis(APIModel):
88
+ failed_trials: int = 0
89
+ success_rules: dict[str, str] = Field(default_factory=dict)
90
+
91
+
92
+ class EvaluatorResult(APIModel):
93
+ id: str
94
+ status: str
95
+ result_id: Optional[str] = None
96
+ passed: Optional[bool] = None
97
+ error_message: Optional[str] = None
98
+ metric_scores: Optional[dict[str, Any]] = None
99
+ call_data: Optional[dict[str, Any]] = None
100
+
101
+ @field_validator("id", "result_id", mode="before")
102
+ @classmethod
103
+ def _ids(cls, value: object) -> object:
104
+ return _stringify(value)
105
+
106
+ @field_validator("status", mode="before")
107
+ @classmethod
108
+ def _status(cls, value: object) -> object:
109
+ if isinstance(value, str):
110
+ return value.strip().lower()
111
+ return value
112
+
113
+ def _quality_passed(self) -> Optional[bool]:
114
+ """Explicit pass flag, else the successful metric or call analysis."""
115
+ if self.passed is not None:
116
+ return bool(self.passed)
117
+ scores = self.metric_scores if isinstance(self.metric_scores, dict) else {}
118
+ successful = scores.get("successful")
119
+ if isinstance(successful, dict) and "value" in successful:
120
+ return bool(successful["value"])
121
+ data = self.call_data if isinstance(self.call_data, dict) else {}
122
+ analysis = data.get("call_analysis")
123
+ if isinstance(analysis, dict) and analysis.get("call_successful") is not None:
124
+ return bool(analysis["call_successful"])
125
+ return None
126
+
127
+ @property
128
+ def succeeded(self) -> bool:
129
+ """Completed and marked passed by a score, not merely finished."""
130
+ return self.status == "completed" and self._quality_passed() is True
131
+
132
+
133
+ class ResultBatchData(APIModel):
134
+ """A suite or evaluator run: one row per queued result, polled until each finishes."""
135
+
136
+ total_runs: int = 0
137
+ task_ids: list[str] = Field(default_factory=list)
138
+ phone_call_refs: list[str] = Field(default_factory=list)
139
+ results: list[EvaluatorResult] = Field(default_factory=list)
140
+
141
+ @model_validator(mode="before")
142
+ @classmethod
143
+ def _accept_server_shape(cls, data: Any) -> Any:
144
+ if not isinstance(data, dict):
145
+ return data
146
+ if "results" not in data and "evaluator_results" in data:
147
+ data = dict(data)
148
+ data["results"] = data.get("evaluator_results") or []
149
+ return data
150
+
151
+ def _planned_run_count(self) -> int:
152
+ return max(len(self.results), self.total_runs, len(self.task_ids))
153
+
154
+ @property
155
+ def pass_rate(self) -> float:
156
+ planned = self._planned_run_count()
157
+ if planned == 0:
158
+ return 0.0
159
+ return sum(1 for result in self.results if result.succeeded) / planned
160
+
161
+ @property
162
+ def passed(self) -> bool:
163
+ """True when every planned result finished successfully."""
164
+ planned = self._planned_run_count()
165
+ if planned == 0:
166
+ return False
167
+ return len(self.results) >= planned and all(result.succeeded for result in self.results)
168
+
169
+ def meets(self, threshold: float) -> bool:
170
+ """True when every planned run finished and the pass rate meets the threshold."""
171
+ planned = self._planned_run_count()
172
+ if planned == 0:
173
+ return False
174
+ if len(self.results) < planned:
175
+ return False
176
+ if any(result.status not in TERMINAL_RESULT_STATUSES for result in self.results):
177
+ return False
178
+ if any(result.status == "failed" for result in self.results):
179
+ return False
180
+ return self.pass_rate >= threshold
181
+
182
+
183
+ class EvaluatorResultPage(APIModel):
184
+ items: list[EvaluatorResult] = Field(default_factory=list)
185
+ total: int = 0
186
+ usage_cost_usd: Optional[float] = None
@@ -0,0 +1,62 @@
1
+ """Poll a run until it reaches a terminal status."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from collections.abc import Awaitable, Callable
8
+ from typing import TypeVar
9
+
10
+ from efficientai_sdk._exceptions import APITimeoutError
11
+
12
+ T = TypeVar("T")
13
+
14
+
15
+ def _timeout(timeout: float) -> APITimeoutError:
16
+ return APITimeoutError(f"Timed out after {timeout:g}s waiting for the run to finish.")
17
+
18
+
19
+ def poll_sync(
20
+ current: T,
21
+ fetch: Callable[[float], T],
22
+ done: Callable[[T], bool],
23
+ *,
24
+ timeout: float,
25
+ interval: float,
26
+ ) -> T:
27
+ deadline = time.monotonic() + timeout
28
+ while not done(current):
29
+ remaining = deadline - time.monotonic()
30
+ if remaining <= 0:
31
+ raise _timeout(timeout)
32
+ time.sleep(min(interval, remaining) if interval > 0 else 0)
33
+ remaining = deadline - time.monotonic()
34
+ if remaining <= 0:
35
+ raise _timeout(timeout)
36
+ current = fetch(remaining)
37
+ if not done(current) and time.monotonic() >= deadline:
38
+ raise _timeout(timeout)
39
+ return current
40
+
41
+
42
+ async def poll_async(
43
+ current: T,
44
+ fetch: Callable[[float], Awaitable[T]],
45
+ done: Callable[[T], bool],
46
+ *,
47
+ timeout: float,
48
+ interval: float,
49
+ ) -> T:
50
+ deadline = time.monotonic() + timeout
51
+ while not done(current):
52
+ remaining = deadline - time.monotonic()
53
+ if remaining <= 0:
54
+ raise _timeout(timeout)
55
+ await asyncio.sleep(min(interval, remaining) if interval > 0 else 0)
56
+ remaining = deadline - time.monotonic()
57
+ if remaining <= 0:
58
+ raise _timeout(timeout)
59
+ current = await fetch(remaining)
60
+ if not done(current) and time.monotonic() >= deadline:
61
+ raise _timeout(timeout)
62
+ return current
@@ -0,0 +1,110 @@
1
+ """Live call tracing: send OpenTelemetry spans from your agent to EfficientAI.
2
+
3
+ Install with the ``otel`` extra to export spans::
4
+
5
+ pip install "efficientai-sdk[otel]"
6
+
7
+ Correlation and handshake helpers work without it.
8
+ """
9
+
10
+ from efficientai_sdk.tracing.api import (
11
+ AsyncTraceResource,
12
+ CallTrace,
13
+ ComponentSpan,
14
+ RetrievalSpan,
15
+ ToolSpan,
16
+ TraceResource,
17
+ TurnSpan,
18
+ )
19
+ from efficientai_sdk.tracing.context import call_attributes, get_call_attributes
20
+ from efficientai_sdk.tracing.correlation import (
21
+ ATTR_AGENT_ID,
22
+ ATTR_CALL_SHORT_ID,
23
+ ATTR_ENVIRONMENT,
24
+ ATTR_ORGANIZATION_ID,
25
+ ATTR_RUN_ID,
26
+ ATTR_TRANSPORT,
27
+ ATTR_WORKSPACE_ID,
28
+ OTLP_HEADER_API_KEY,
29
+ OTLP_HEADER_CALL_SHORT_ID,
30
+ OTLP_HEADER_RUN_ID,
31
+ OTLP_HEADER_WORKSPACE_ID,
32
+ build_outbound_sip_headers,
33
+ extract_call_short_id,
34
+ format_plivo_sip_headers,
35
+ otlp_export_headers,
36
+ span_correlation_attributes,
37
+ )
38
+ from efficientai_sdk.tracing.handshake import HANDSHAKE_TYPE, parse_trace_handshake
39
+ from efficientai_sdk.tracing.otel import (
40
+ OTEL_AVAILABLE,
41
+ create_otlp_exporter,
42
+ ensure_export_pipeline,
43
+ flush_efficientai_tracing,
44
+ is_tracing_available,
45
+ setup_efficientai_tracing,
46
+ setup_tracer_provider,
47
+ )
48
+ from efficientai_sdk.tracing.session import (
49
+ DEFAULT_OTLP_PATH,
50
+ TraceSessionError,
51
+ close_trace_session,
52
+ ensure_trace_session,
53
+ mint_trace_session,
54
+ missing_deployment_trace_env,
55
+ require_deployment_trace_env,
56
+ resolve_otlp_endpoint,
57
+ resolve_trace_transport,
58
+ setup_worker_tracing,
59
+ trace_session_enabled,
60
+ warn_deployment_trace_env,
61
+ )
62
+
63
+ __all__ = [
64
+ "ATTR_AGENT_ID",
65
+ "ATTR_CALL_SHORT_ID",
66
+ "ATTR_ENVIRONMENT",
67
+ "ATTR_ORGANIZATION_ID",
68
+ "ATTR_RUN_ID",
69
+ "ATTR_TRANSPORT",
70
+ "ATTR_WORKSPACE_ID",
71
+ "DEFAULT_OTLP_PATH",
72
+ "HANDSHAKE_TYPE",
73
+ "OTEL_AVAILABLE",
74
+ "OTLP_HEADER_API_KEY",
75
+ "OTLP_HEADER_CALL_SHORT_ID",
76
+ "OTLP_HEADER_RUN_ID",
77
+ "OTLP_HEADER_WORKSPACE_ID",
78
+ "AsyncTraceResource",
79
+ "CallTrace",
80
+ "ComponentSpan",
81
+ "RetrievalSpan",
82
+ "ToolSpan",
83
+ "TraceResource",
84
+ "TraceSessionError",
85
+ "TurnSpan",
86
+ "build_outbound_sip_headers",
87
+ "call_attributes",
88
+ "close_trace_session",
89
+ "create_otlp_exporter",
90
+ "ensure_export_pipeline",
91
+ "ensure_trace_session",
92
+ "extract_call_short_id",
93
+ "flush_efficientai_tracing",
94
+ "format_plivo_sip_headers",
95
+ "get_call_attributes",
96
+ "is_tracing_available",
97
+ "mint_trace_session",
98
+ "missing_deployment_trace_env",
99
+ "otlp_export_headers",
100
+ "parse_trace_handshake",
101
+ "require_deployment_trace_env",
102
+ "resolve_otlp_endpoint",
103
+ "resolve_trace_transport",
104
+ "setup_efficientai_tracing",
105
+ "setup_tracer_provider",
106
+ "setup_worker_tracing",
107
+ "span_correlation_attributes",
108
+ "trace_session_enabled",
109
+ "warn_deployment_trace_env",
110
+ ]