File size: 8,500 Bytes
f8ba6bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
314
315
"""
DungeonMaster AI - Agent Exceptions

Exception hierarchy for agent-related errors.
"""

from __future__ import annotations


class AgentError(Exception):
    """Base exception for all agent-related errors."""

    def __init__(self, message: str, recoverable: bool = True) -> None:
        super().__init__(message)
        self.message = message
        self.recoverable = recoverable


# =============================================================================
# LLM Provider Exceptions
# =============================================================================


class LLMProviderError(AgentError):
    """Base exception for LLM provider errors."""

    def __init__(
        self,
        message: str,
        provider: str = "",
        recoverable: bool = True,
    ) -> None:
        super().__init__(message, recoverable)
        self.provider = provider


class LLMRateLimitError(LLMProviderError):
    """LLM provider rate limit exceeded."""

    def __init__(
        self,
        provider: str,
        retry_after: float | None = None,
    ) -> None:
        super().__init__(
            f"Rate limit exceeded for {provider}",
            provider=provider,
            recoverable=True,
        )
        self.retry_after = retry_after


class LLMTimeoutError(LLMProviderError):
    """LLM request timed out."""

    def __init__(
        self,
        provider: str,
        timeout_seconds: float,
    ) -> None:
        super().__init__(
            f"Request to {provider} timed out after {timeout_seconds}s",
            provider=provider,
            recoverable=True,
        )
        self.timeout_seconds = timeout_seconds


class LLMAuthenticationError(LLMProviderError):
    """LLM authentication failed (invalid API key)."""

    def __init__(self, provider: str) -> None:
        super().__init__(
            f"Authentication failed for {provider}. Check API key.",
            provider=provider,
            recoverable=False,
        )


class LLMQuotaExhaustedError(LLMProviderError):
    """LLM quota/credits exhausted."""

    def __init__(self, provider: str) -> None:
        super().__init__(
            f"Quota exhausted for {provider}",
            provider=provider,
            recoverable=False,
        )


class LLMAllProvidersFailedError(AgentError):
    """All LLM providers failed."""

    def __init__(self, errors: dict[str, str]) -> None:
        providers = ", ".join(errors.keys())
        super().__init__(
            f"All LLM providers failed: {providers}",
            recoverable=False,
        )
        self.errors = errors


class LLMCircuitBreakerOpenError(LLMProviderError):
    """Circuit breaker is open for this provider."""

    def __init__(
        self,
        provider: str,
        reset_after: float | None = None,
    ) -> None:
        super().__init__(
            f"Circuit breaker open for {provider}",
            provider=provider,
            recoverable=True,
        )
        self.reset_after = reset_after


# =============================================================================
# Agent Processing Exceptions
# =============================================================================


class AgentProcessingError(AgentError):
    """Error during agent processing."""

    def __init__(
        self,
        message: str,
        agent_name: str = "",
        recoverable: bool = True,
    ) -> None:
        super().__init__(message, recoverable)
        self.agent_name = agent_name


class DMAgentError(AgentProcessingError):
    """Error in Dungeon Master agent."""

    def __init__(self, message: str, recoverable: bool = True) -> None:
        super().__init__(message, agent_name="DungeonMaster", recoverable=recoverable)


class RulesAgentError(AgentProcessingError):
    """Error in Rules Arbiter agent."""

    def __init__(self, message: str, recoverable: bool = True) -> None:
        super().__init__(message, agent_name="RulesArbiter", recoverable=recoverable)


class VoiceNarratorError(AgentProcessingError):
    """Error in Voice Narrator agent."""

    def __init__(self, message: str, recoverable: bool = True) -> None:
        super().__init__(message, agent_name="VoiceNarrator", recoverable=recoverable)


# =============================================================================
# Tool Execution Exceptions
# =============================================================================


class ToolExecutionError(AgentError):
    """Error executing a tool."""

    def __init__(
        self,
        tool_name: str,
        message: str,
        original_error: Exception | None = None,
        recoverable: bool = True,
    ) -> None:
        super().__init__(
            f"Tool '{tool_name}' failed: {message}",
            recoverable=recoverable,
        )
        self.tool_name = tool_name
        self.original_error = original_error


class ToolTimeoutError(ToolExecutionError):
    """Tool execution timed out."""

    def __init__(
        self,
        tool_name: str,
        timeout_seconds: float,
    ) -> None:
        super().__init__(
            tool_name,
            f"Execution timed out after {timeout_seconds}s",
            recoverable=True,
        )
        self.timeout_seconds = timeout_seconds


class ToolNotFoundError(ToolExecutionError):
    """Requested tool not found."""

    def __init__(self, tool_name: str) -> None:
        super().__init__(
            tool_name,
            "Tool not found in available tools",
            recoverable=False,
        )


# =============================================================================
# Orchestration Exceptions
# =============================================================================


class OrchestratorError(AgentError):
    """Error in agent orchestration."""

    pass


class OrchestratorNotInitializedError(OrchestratorError):
    """Orchestrator not properly initialized."""

    def __init__(self) -> None:
        super().__init__(
            "Orchestrator not initialized. Call setup() first.",
            recoverable=True,
        )


class TurnProcessingError(OrchestratorError):
    """Error processing a player turn."""

    def __init__(
        self,
        message: str,
        partial_result: object | None = None,
    ) -> None:
        super().__init__(message, recoverable=True)
        self.partial_result = partial_result


# =============================================================================
# State Exceptions
# =============================================================================


class GameStateError(AgentError):
    """Error with game state."""

    pass


class StateConsistencyError(GameStateError):
    """Game state became inconsistent."""

    def __init__(
        self,
        message: str,
        state_snapshot: dict[str, object] | None = None,
    ) -> None:
        super().__init__(message, recoverable=True)
        self.state_snapshot = state_snapshot


# =============================================================================
# Graceful Error Messages
# =============================================================================


GRACEFUL_ERROR_MESSAGES: dict[str, str] = {
    "llm_timeout": (
        "The magical winds of computation blow slowly today. "
        "Please try again in a moment."
    ),
    "llm_rate_limit": (
        "The ethereal realm is experiencing heavy traffic. "
        "Take a breath and try again shortly."
    ),
    "llm_all_failed": (
        "The arcane servers are temporarily unreachable. "
        "Your adventure continues in text mode."
    ),
    "tool_failed": (
        "The mystical tools encountered interference. "
        "Let's try a different approach..."
    ),
    "voice_unavailable": (
        "The voice of the narrator is temporarily silenced. "
        "Continuing with text narration."
    ),
    "mcp_unavailable": (
        "The game mechanics server is resting. "
        "Using simplified rules for now."
    ),
    "general_error": (
        "An unexpected twist in the fabric of reality occurred. "
        "The adventure continues nonetheless."
    ),
}


def get_graceful_message(error_type: str) -> str:
    """
    Get a user-friendly error message.

    Args:
        error_type: Type of error (key in GRACEFUL_ERROR_MESSAGES)

    Returns:
        User-friendly error message
    """
    return GRACEFUL_ERROR_MESSAGES.get(
        error_type,
        GRACEFUL_ERROR_MESSAGES["general_error"],
    )