File size: 9,164 Bytes
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""
Typed execution errors and results.

Provides explicit error typing instead of plain strings,
structured results, and handling policies.
"""

import builtins
from datetime import UTC, datetime
from enum import Enum
from typing import Any

from pydantic import BaseModel, ConfigDict

__all__ = [
    "AgentNotFoundError",
    "BudgetExceededError",
    "ErrorAction",
    "ErrorPolicy",
    "ExecutionError",
    "ExecutionMetrics",
    "RetryExhaustedError",
    "StepExecutionResult",
    "TimeoutError",
    "ValidationError",
]


class ExecutionError(Exception):
    """Base execution error for a step/agent with metadata."""

    def __init__(
        self,
        message: str,
        agent_id: str | None = None,
        step_index: int | None = None,
        cause: Exception | None = None,
        recoverable: bool = True,
    ):
        super().__init__(message)
        self.message = message
        self.agent_id = agent_id
        self.step_index = step_index
        self.cause = cause
        self.recoverable = recoverable
        self.timestamp = datetime.now(UTC)

    def to_dict(self) -> dict[str, Any]:
        """Serialize the error to a dictionary for logging or response."""
        return {
            "type": self.__class__.__name__,
            "message": self.message,
            "agent_id": self.agent_id,
            "step_index": self.step_index,
            "recoverable": self.recoverable,
            "timestamp": self.timestamp.isoformat(),
            "cause": str(self.cause) if self.cause else None,
        }


class TimeoutError(ExecutionError, builtins.TimeoutError):  # noqa: A001
    """Agent timeout error."""

    def __init__(
        self,
        agent_id: str,
        timeout_seconds: float,
        step_index: int | None = None,
    ):
        super().__init__(
            f"Agent '{agent_id}' timed out after {timeout_seconds}s",
            agent_id=agent_id,
            step_index=step_index,
            recoverable=True,
        )
        self.timeout_seconds = timeout_seconds


class RetryExhaustedError(ExecutionError):
    """Error raised when all retry attempts are exhausted."""

    def __init__(
        self,
        agent_id: str,
        attempts: int,
        last_error: Exception | None = None,
        step_index: int | None = None,
    ):
        super().__init__(
            f"Agent '{agent_id}' failed after {attempts} attempts",
            agent_id=agent_id,
            step_index=step_index,
            cause=last_error,
            recoverable=False,
        )
        self.attempts = attempts
        self.last_error = last_error


class BudgetExceededError(ExecutionError):
    """Error raised when a budget limit is exceeded."""

    def __init__(
        self,
        budget_type: str,
        limit: float,
        used: float,
        agent_id: str | None = None,
    ):
        super().__init__(
            f"{budget_type.capitalize()} budget exceeded: {used}/{limit}",
            agent_id=agent_id,
            recoverable=False,
        )
        self.budget_type = budget_type
        self.limit = limit
        self.used = used


class AgentNotFoundError(ExecutionError):
    """Error raised when an agent is not found in the graph."""

    def __init__(self, agent_id: str):
        super().__init__(
            f"Agent '{agent_id}' not found in graph",
            agent_id=agent_id,
            recoverable=False,
        )


class ValidationError(ExecutionError):
    """Error raised when input data or parameters fail validation."""

    def __init__(
        self,
        message: str,
        field: str | None = None,
        value: Any = None,
    ):
        super().__init__(message, recoverable=False)
        self.field = field
        self.value = value


class ErrorAction(str, Enum):
    SKIP = "skip"
    RETRY = "retry"
    PRUNE = "prune"
    FALLBACK = "fallback"
    ROLLBACK = "rollback"
    ABORT = "abort"


class ErrorPolicy(BaseModel):
    """Policy that maps error types to handling actions."""

    on_timeout: ErrorAction = ErrorAction.RETRY
    on_retry_exhausted: ErrorAction = ErrorAction.PRUNE
    on_budget_exceeded: ErrorAction = ErrorAction.ABORT
    on_agent_not_found: ErrorAction = ErrorAction.SKIP
    on_validation_error: ErrorAction = ErrorAction.ABORT
    on_unknown_error: ErrorAction = ErrorAction.SKIP

    max_skipped_agents: int = 5
    abort_on_critical_path: bool = True

    def get_action(self, error: "ExecutionError") -> ErrorAction:
        """Return the action corresponding to the error type."""
        if isinstance(error, TimeoutError):
            return self.on_timeout
        if isinstance(error, RetryExhaustedError):
            return self.on_retry_exhausted
        if isinstance(error, BudgetExceededError):
            return self.on_budget_exceeded
        if isinstance(error, AgentNotFoundError):
            return self.on_agent_not_found
        if isinstance(error, ValidationError):
            return self.on_validation_error
        return self.on_unknown_error


class ExecutionMetrics(BaseModel):
    """Aggregated metrics for tokens, requests, agents, and timing."""

    prompt_tokens: int = 0
    completion_tokens: int = 0
    total_tokens: int = 0

    start_time: datetime | None = None
    end_time: datetime | None = None
    latency_ms: float = 0.0

    total_requests: int = 0
    successful_requests: int = 0
    failed_requests: int = 0
    retried_requests: int = 0

    total_agents: int = 0
    executed_agents: int = 0
    skipped_agents: int = 0
    failed_agents: int = 0

    @property
    def success_rate(self) -> float:
        """Fraction of successful requests."""
        if self.total_requests == 0:
            return 0.0
        return self.successful_requests / self.total_requests

    @property
    def duration_seconds(self) -> float:
        """Total execution duration in seconds."""
        if self.start_time and self.end_time:
            return (self.end_time - self.start_time).total_seconds()
        return 0.0

    def add_request(
        self,
        prompt_tokens: int,
        completion_tokens: int,
        success: bool,
        latency_ms: float,
        retried: bool = False,
    ) -> None:
        """Add metrics for a single request or step."""
        self.prompt_tokens += prompt_tokens
        self.completion_tokens += completion_tokens
        self.total_tokens += prompt_tokens + completion_tokens
        self.total_requests += 1
        self.latency_ms += latency_ms

        if success:
            self.successful_requests += 1
        else:
            self.failed_requests += 1

        if retried:
            self.retried_requests += 1

    def to_dict(self) -> dict[str, Any]:
        """Serialize metrics to a dictionary."""
        return {
            "tokens": {
                "prompt": self.prompt_tokens,
                "completion": self.completion_tokens,
                "total": self.total_tokens,
            },
            "requests": {
                "total": self.total_requests,
                "successful": self.successful_requests,
                "failed": self.failed_requests,
                "retried": self.retried_requests,
                "success_rate": self.success_rate,
            },
            "agents": {
                "total": self.total_agents,
                "executed": self.executed_agents,
                "skipped": self.skipped_agents,
                "failed": self.failed_agents,
            },
            "timing": {
                "duration_seconds": self.duration_seconds,
                "total_latency_ms": self.latency_ms,
                "avg_latency_ms": self.latency_ms / max(1, self.total_requests),
            },
        }


class StepExecutionResult(BaseModel):
    """Result of a step/agent execution with metrics and status flags."""

    model_config = ConfigDict(arbitrary_types_allowed=True)

    agent_id: str
    success: bool
    response: str | None = None
    error: "ExecutionError | None" = None

    prompt_tokens: int = 0
    completion_tokens: int = 0
    latency_ms: float = 0.0
    attempts: int = 1

    quality_score: float = 1.0

    skipped: bool = False
    fallback_used: bool = False

    @property
    def tokens_used(self) -> int:
        """Total tokens consumed by this step."""
        return self.prompt_tokens + self.completion_tokens

    def to_dict(self) -> dict[str, Any]:
        """Serialize the step result to a dictionary."""
        return {
            "agent_id": self.agent_id,
            "success": self.success,
            "response_length": len(self.response) if self.response else 0,
            "error": self.error.to_dict() if self.error else None,
            "metrics": {
                "prompt_tokens": self.prompt_tokens,
                "completion_tokens": self.completion_tokens,
                "latency_ms": self.latency_ms,
                "attempts": self.attempts,
                "quality_score": self.quality_score,
            },
            "status": {
                "skipped": self.skipped,
                "fallback_used": self.fallback_used,
            },
        }