Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def __init__(
channel_service_client_factory: ChannelServiceClientFactoryBase | None = None,
channel_service_client_factory_options: dict | None = None,
host_validator: OutboundHostValidator | None = None,
emit_stack_trace: bool = False,
):
"""
Initializes a new instance of the CloudAdapter class.
Expand All @@ -37,12 +38,14 @@ def __init__(
:param channel_service_client_factory: Factory for creating channel service clients.
:param channel_service_client_factory_options: Optional dictionary of options to pass to the channel service client factory
This is only used if channel_service_client_factory is not provided and connection_manager is provided.
:param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent.
"""
super().__init__(
connection_manager=connection_manager,
channel_service_client_factory=channel_service_client_factory,
channel_service_client_factory_options=channel_service_client_factory_options,
host_validator=host_validator,
emit_stack_trace=emit_stack_trace,
)

async def process(self, request: Request, agent: Agent) -> Optional[Response]:
Expand Down
20 changes: 19 additions & 1 deletion libraries/microsoft-agents-hosting-aiohttp/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,4 +286,22 @@ async def on_error(context: TurnContext, error: Exception):
|Semantic Kernel Integration|A weather agent built with Semantic Kernel|[semantic-kernel-multiturn](https://github.com/microsoft/Agents/blob/main/samples/python/semantic-kernel-multiturn/README.md)|
|Streaming Agent|Streams OpenAI responses|[azure-ai-streaming](https://github.com/microsoft/Agents/blob/main/samples/python/azureai-streaming/README.md)|
|Copilot Studio Client|Console app to consume a Copilot Studio Agent|[copilotstudio-client](https://github.com/microsoft/Agents/blob/main/samples/python/copilotstudio-client/README.md)|
|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)|
|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)|

## Default turn error handling

The HTTP adapter logs the original exception through Python logging and sends
`Sorry, something went wrong.` to the user. Configure logging to collect server
diagnostics; traceback output is no longer printed directly to stdout.

Pass `emit_stack_trace=True` to `CloudAdapter` during development to include
traceback frames in diagnostic trace activities. The default is `False`; this
setting does not affect server logging or the generic user response. Traces still
contain exception messages, so disabling stacks is not complete redaction. Normal
connector delivery filters traces outside the emulator channel, but `expectReplies`
responses can buffer them on other channels.

Assign an async `(context, error)` callback to `adapter.on_turn_error` to replace
the adapter default, including its logging and responses. The stack option does
not modify custom handlers. `@app.error` handles application errors in registration
order after application logging; a successful handler prevents adapter fallback.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from abc import ABC
from uuid import uuid4
from http import HTTPStatus
from traceback import format_exc
from traceback import format_exception

import logging

Expand Down Expand Up @@ -42,30 +42,19 @@ def __init__(
channel_service_client_factory: ChannelServiceClientFactoryBase | None = None,
channel_service_client_factory_options: dict | None = None,
host_validator: OutboundHostValidator | None = None,
emit_stack_trace: bool = False,
):
"""Initialize the HTTP adapter.

:param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent.
:param connection_manager: Optional connection manager for OAuth.
:param channel_service_client_factory: Factory for creating channel service clients.
:param channel_service_client_factory_options: Optional dictionary of options to pass to the channel service client factory
This is only used if channel_service_client_factory is not provided and connection_manager is provided.
"""

async def on_turn_error(context: TurnContext, error: Exception):
error_message = f"Exception caught : {error}"
print(format_exc())

await context.send_activity(MessageFactory.text(error_message))

# Send a trace activity
await context.send_trace_activity(
"OnTurnError Trace",
error_message,
"https://www.botframework.com/schemas/error",
"TurnError",
)

self.on_turn_error = on_turn_error
self._emit_stack_trace = emit_stack_trace
self.on_turn_error = self._handle_turn_error

factory: ChannelServiceClientFactoryBase

Expand All @@ -84,6 +73,26 @@ async def on_turn_error(context: TurnContext, error: Exception):

super().__init__(factory)

async def _handle_turn_error(self, context: TurnContext, error: Exception):
logger.error(
"Unhandled exception during turn processing",
exc_info=(type(error), error, error.__traceback__),
)

trace_message = f"Exception caught : {error}"
if self._emit_stack_trace:
trace_message = "".join(
format_exception(type(error), error, error.__traceback__)
)

await context.send_activity(MessageFactory.text("Sorry, something went wrong."))
await context.send_trace_activity(
"OnTurnError Trace",
trace_message,
"https://www.botframework.com/schemas/error",
"TurnError",
)

async def process_request(
self, request: HttpRequestProtocol, agent: Agent
) -> HttpResponse:
Expand Down
20 changes: 19 additions & 1 deletion libraries/microsoft-agents-hosting-core/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,22 @@ async def on_error(context: TurnContext, error: Exception):
|Semantic Kernel Integration|A weather agent built with Semantic Kernel|[semantic-kernel-multiturn](https://github.com/microsoft/Agents/blob/main/samples/python/semantic-kernel-multiturn/README.md)|
|Streaming Agent|Streams OpenAI responses|[azure-ai-streaming](https://github.com/microsoft/Agents/blob/main/samples/python/azureai-streaming/README.md)|
|Copilot Studio Client|Console app to consume a Copilot Studio Agent|[copilotstudio-client](https://github.com/microsoft/Agents/blob/main/samples/python/copilotstudio-client/README.md)|
|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)|
|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)|

## Default turn error handling

The HTTP adapter logs the original exception through Python logging and sends
`Sorry, something went wrong.` to the user. Configure logging to collect server
diagnostics; traceback output is no longer printed directly to stdout.

Pass `emit_stack_trace=True` to `CloudAdapter` during development to include
traceback frames in diagnostic trace activities. The default is `False`; this
setting does not affect server logging or the generic user response. Traces still
contain exception messages, so disabling stacks is not complete redaction. Normal
connector delivery filters traces outside the emulator channel, but `expectReplies`
responses can buffer them on other channels.

Assign an async `(context, error)` callback to `adapter.on_turn_error` to replace
the adapter default, including its logging and responses. The stack option does
not modify custom handlers. `@app.error` handles application errors in registration
order after application logging; a successful handler prevents adapter fallback.
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@ def __init__(
channel_service_client_factory: ChannelServiceClientFactoryBase | None = None,
channel_service_client_factory_options: dict | None = None,
host_validator: OutboundHostValidator | None = None,
emit_stack_trace: bool = False,
):
"""
Initializes a new instance of the CloudAdapter class.

:param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent.
:param connection_manager: Optional connection manager for OAuth.
:param channel_service_client_factory: Factory for creating channel service clients.
:param channel_service_client_factory_options: Optional dictionary of options to pass to the channel service client factory
Expand All @@ -44,6 +46,7 @@ def __init__(
channel_service_client_factory=channel_service_client_factory,
channel_service_client_factory_options=channel_service_client_factory_options,
host_validator=host_validator,
emit_stack_trace=emit_stack_trace,
)

async def process(self, request: Request, agent: Agent) -> Optional[Response]:
Expand Down
20 changes: 19 additions & 1 deletion libraries/microsoft-agents-hosting-fastapi/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,4 +217,22 @@ agent_app = AgentApplication(
@jwt_authorization_decorator
async def messages(request: Request):
return await start_agent_process(request, agent_app, adapter)
```
```

## Default turn error handling

The HTTP adapter logs the original exception through Python logging and sends
`Sorry, something went wrong.` to the user. Configure logging to collect server
diagnostics; traceback output is no longer printed directly to stdout.

Pass `emit_stack_trace=True` to `CloudAdapter` during development to include
traceback frames in diagnostic trace activities. The default is `False`; this
setting does not affect server logging or the generic user response. Traces still
contain exception messages, so disabling stacks is not complete redaction. Normal
connector delivery filters traces outside the emulator channel, but `expectReplies`
responses can buffer them on other channels.

Assign an async `(context, error)` callback to `adapter.on_turn_error` to replace
the adapter default, including its logging and responses. The stack option does
not modify custom handlers. `@app.error` handles application errors in registration
order after application logging; a successful handler prevents adapter fallback.
90 changes: 90 additions & 0 deletions tests/hosting_core/test_http_adapter_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import logging
from unittest.mock import AsyncMock, MagicMock

import pytest

from microsoft_agents.hosting.aiohttp import CloudAdapter as AiohttpAdapter
from microsoft_agents.hosting.fastapi import CloudAdapter as FastapiAdapter


@pytest.mark.asyncio
@pytest.mark.parametrize("adapter_type", [AiohttpAdapter, FastapiAdapter])
@pytest.mark.parametrize("emit_stack_trace", [False, True])
async def test_default_error_diagnostics(adapter_type, emit_stack_trace, caplog):
adapter = adapter_type(
channel_service_client_factory=MagicMock(),
emit_stack_trace=emit_stack_trace,
)
context = MagicMock()
context.send_activity = AsyncMock()
context.send_trace_activity = AsyncMock()
try:
raise RuntimeError("private diagnostic detail")
except RuntimeError as caught:
error = caught

with caplog.at_level(logging.ERROR):
await adapter.on_turn_error(context, error)

response = context.send_activity.call_args.args[0]
assert response.text == "Sorry, something went wrong."
trace = context.send_trace_activity.call_args.args
assert trace[0] == "OnTurnError Trace"
assert "private diagnostic detail" in trace[1]
assert ("Traceback (most recent call last)" in trace[1]) == emit_stack_trace
assert caplog.records[-1].exc_info[1] is error
assert "test_default_error_diagnostics" in caplog.text


@pytest.mark.asyncio
async def test_error_without_traceback():
adapter = AiohttpAdapter(
channel_service_client_factory=MagicMock(), emit_stack_trace=True
)
context = MagicMock(send_activity=AsyncMock(), send_trace_activity=AsyncMock())
await adapter.on_turn_error(context, ValueError("never raised"))
assert context.send_trace_activity.call_args.args[1] == "ValueError: never raised\n"


@pytest.mark.asyncio
async def test_response_failure_propagates_before_trace():
adapter = AiohttpAdapter(channel_service_client_factory=MagicMock())
failure = RuntimeError("send failed")
context = MagicMock(
send_activity=AsyncMock(side_effect=failure), send_trace_activity=AsyncMock()
)
with pytest.raises(RuntimeError) as caught:
await adapter.on_turn_error(context, ValueError("turn failed"))
assert caught.value is failure
context.send_trace_activity.assert_not_called()


@pytest.mark.asyncio
async def test_pipeline_uses_replacement_and_propagates_its_failure():
adapter = AiohttpAdapter(channel_service_client_factory=MagicMock())
context = MagicMock(send_activity=AsyncMock(), send_trace_activity=AsyncMock())
original = ValueError("turn failed")
replacement_failure = RuntimeError("handler failed")
handler = AsyncMock(side_effect=replacement_failure)
adapter.on_turn_error = handler
adapter.middleware_set.receive_activity_with_status = AsyncMock(
side_effect=original
)

with pytest.raises(RuntimeError) as caught:
await adapter.run_pipeline(context)

assert caught.value is replacement_failure
handler.assert_awaited_once_with(context, original)
context.send_activity.assert_not_called()
context.send_trace_activity.assert_not_called()


@pytest.mark.asyncio
async def test_omitted_option_omits_traceback():
adapter = AiohttpAdapter(channel_service_client_factory=MagicMock())
context = MagicMock(send_activity=AsyncMock(), send_trace_activity=AsyncMock())
await adapter.on_turn_error(context, ValueError("diagnostic"))
assert (
context.send_trace_activity.call_args.args[1] == "Exception caught : diagnostic"
)