mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: [BREAKING] Redesign Python exception hierarchy (#4082)
* [BREAKING] Redesign Python exception hierarchy Replace the flat ServiceException family with domain-scoped branches: - AgentException (with InvalidAuth, InvalidRequest, InvalidResponse, ContentFilter) - ChatClientException (same consistent suberrors) - IntegrationException (same + InitializationError) - WorkflowException (Runner, Convergence, Checkpoint, Validation, Action, Declarative) - ContentError (AdditionItemMismatch) - ToolException / ToolExecutionException (unchanged) - MiddlewareException / MiddlewareTermination (unchanged) Key changes: - All Service* exceptions removed (ServiceException, ServiceInitializationError, etc.) - AgentExecutionException split into AgentInvalidRequest/ResponseException - AgentInvocationError removed, split into AgentInvalidRequest/ResponseException - Workflow exceptions moved from _workflows/_exceptions.py into main exceptions.py - _workflows/__init__.py emptied; main __init__.py imports directly from submodules - Purview exceptions re-parented under IntegrationException hierarchy - Init validation errors use built-in ValueError/TypeError instead of custom exceptions - CODING_STANDARD.md updated with hierarchy design and rationale Fixes microsoft/agent-framework#3410 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Clarify ToolException vs ToolExecutionException docstrings ToolException: base class for all tool-related exceptions (preconditions, connection/init failures). ToolExecutionException: runtime call failures (tool call failed, reconnect failed, MCP errors). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix remaining stale imports from agent_framework._workflows - azurefunctions: _context.py, _app.py, _serialization.py, test_func_utils.py used 'from agent_framework._workflows import X' which broke after emptying _workflows/__init__.py; changed to direct submodule imports - azure-ai-search: test still referenced ServiceInitializationError; updated to ValueError to match production code Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
7f606a2e3a
commit
5ee06853a1
@@ -26,7 +26,7 @@ from agent_framework import (
|
||||
normalize_messages,
|
||||
normalize_tools,
|
||||
)
|
||||
from agent_framework.exceptions import ServiceException
|
||||
from agent_framework.exceptions import AgentException
|
||||
from claude_agent_sdk import (
|
||||
AssistantMessage,
|
||||
ClaudeSDKClient,
|
||||
@@ -360,7 +360,7 @@ class ClaudeAgent(BaseAgent, Generic[OptionsT]):
|
||||
as an async context manager.
|
||||
|
||||
Raises:
|
||||
ServiceException: If the client fails to start.
|
||||
AgentException: If the client fails to start.
|
||||
"""
|
||||
await self._ensure_session()
|
||||
|
||||
@@ -407,7 +407,7 @@ class ClaudeAgent(BaseAgent, Generic[OptionsT]):
|
||||
self._current_session_id = session_id
|
||||
except Exception as ex:
|
||||
self._client = None
|
||||
raise ServiceException(f"Failed to start Claude SDK client: {ex}") from ex
|
||||
raise AgentException(f"Failed to start Claude SDK client: {ex}") from ex
|
||||
|
||||
def _prepare_client_options(self, resume_session_id: str | None = None) -> SDKOptions:
|
||||
"""Prepare SDK options for client initialization.
|
||||
@@ -639,7 +639,7 @@ class ClaudeAgent(BaseAgent, Generic[OptionsT]):
|
||||
await self._ensure_session(session.service_session_id)
|
||||
|
||||
if not self._client:
|
||||
raise ServiceException("Claude SDK client not initialized.")
|
||||
raise RuntimeError("Claude SDK client not initialized.")
|
||||
|
||||
prompt = self._format_prompt(normalize_messages(messages))
|
||||
|
||||
@@ -693,12 +693,12 @@ class ClaudeAgent(BaseAgent, Generic[OptionsT]):
|
||||
if isinstance(block, TextBlock):
|
||||
error_msg = f"{error_msg}: {block.text}"
|
||||
break
|
||||
raise ServiceException(error_msg)
|
||||
raise AgentException(error_msg)
|
||||
elif isinstance(message, ResultMessage):
|
||||
# Check for errors in result message
|
||||
if message.is_error:
|
||||
error_msg = message.result or "Unknown error from Claude API"
|
||||
raise ServiceException(f"Claude API error: {error_msg}")
|
||||
raise AgentException(f"Claude API error: {error_msg}")
|
||||
session_id = message.session_id
|
||||
|
||||
# Update session with session ID
|
||||
|
||||
@@ -379,8 +379,8 @@ class TestClaudeAgentRunStream:
|
||||
assert updates[1].text == "response"
|
||||
|
||||
async def test_run_stream_raises_on_assistant_message_error(self) -> None:
|
||||
"""Test run raises ServiceException when AssistantMessage has an error."""
|
||||
from agent_framework.exceptions import ServiceException
|
||||
"""Test run raises AgentException when AssistantMessage has an error."""
|
||||
from agent_framework.exceptions import AgentException
|
||||
from claude_agent_sdk import AssistantMessage, ResultMessage, TextBlock
|
||||
|
||||
messages = [
|
||||
@@ -402,15 +402,15 @@ class TestClaudeAgentRunStream:
|
||||
|
||||
with patch("agent_framework_claude._agent.ClaudeSDKClient", return_value=mock_client):
|
||||
agent = ClaudeAgent()
|
||||
with pytest.raises(ServiceException) as exc_info:
|
||||
with pytest.raises(AgentException) as exc_info:
|
||||
async for _ in agent.run("Hello", stream=True):
|
||||
pass
|
||||
assert "Invalid request to Claude API" in str(exc_info.value)
|
||||
assert "Error details from API" in str(exc_info.value)
|
||||
|
||||
async def test_run_stream_raises_on_result_message_error(self) -> None:
|
||||
"""Test run raises ServiceException when ResultMessage.is_error is True."""
|
||||
from agent_framework.exceptions import ServiceException
|
||||
"""Test run raises AgentException when ResultMessage.is_error is True."""
|
||||
from agent_framework.exceptions import AgentException
|
||||
from claude_agent_sdk import ResultMessage
|
||||
|
||||
messages = [
|
||||
@@ -428,7 +428,7 @@ class TestClaudeAgentRunStream:
|
||||
|
||||
with patch("agent_framework_claude._agent.ClaudeSDKClient", return_value=mock_client):
|
||||
agent = ClaudeAgent()
|
||||
with pytest.raises(ServiceException) as exc_info:
|
||||
with pytest.raises(AgentException) as exc_info:
|
||||
async for _ in agent.run("Hello", stream=True):
|
||||
pass
|
||||
assert "Model 'claude-sonnet-4.5' not found" in str(exc_info.value)
|
||||
|
||||
Reference in New Issue
Block a user