Skip to content

Commit 00b9423

Browse files
giles17Copilot
andcommitted
Python: Fix as_tool() swallowing user_input_request events (microsoft#4499)
When a sub-agent wrapped with as_tool() emits user_input_request content (e.g. oauth_consent_request), the event was silently dropped because as_tool() only returns .text. This fix propagates user_input_request Content through the tool invocation pipeline to the parent response. Changes: - Add UserInputRequiredException to bridge the str-return boundary - Check response.user_input_requests in as_tool() before returning .text - Add re-raise guards in _auto_invoke_function to prevent the generic except Exception from swallowing the exception - Catch in invoke_with_termination_handling to extract Content items - Expand _handle_function_call_results to detect user_input_request Content Co-authored-by: Copilot <[email protected]>
1 parent f74bda5 commit 00b9423

6 files changed

Lines changed: 188 additions & 5 deletions

File tree

‎python/packages/core/agent_framework/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@
181181
)
182182
from .exceptions import (
183183
MiddlewareException,
184+
UserInputRequiredException,
184185
WorkflowCheckpointException,
185186
WorkflowConvergenceException,
186187
WorkflowException,
@@ -291,6 +292,7 @@
291292
"TypeCompatibilityError",
292293
"UpdateT",
293294
"UsageDetails",
295+
"UserInputRequiredException",
294296
"ValidationTypeEnum",
295297
"Workflow",
296298
"WorkflowAgent",

‎python/packages/core/agent_framework/_agents.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
map_chat_to_agent_update,
5252
normalize_messages,
5353
)
54-
from .exceptions import AgentInvalidResponseException
54+
from .exceptions import AgentInvalidResponseException, UserInputRequiredException
5555
from .observability import AgentTelemetryLayer
5656

5757
if sys.version_info >= (3, 13):
@@ -532,7 +532,10 @@ async def agent_wrapper(**kwargs: Any) -> str:
532532

533533
if stream_callback is None:
534534
# Use non-streaming mode
535-
return (await self.run(input_text, stream=False, session=parent_session, **forwarded_kwargs)).text
535+
response = await self.run(input_text, stream=False, session=parent_session, **forwarded_kwargs)
536+
if response.user_input_requests:
537+
raise UserInputRequiredException(contents=response.user_input_requests)
538+
return response.text
536539

537540
# Use streaming mode - accumulate updates and create final response
538541
response_updates: list[AgentResponseUpdate] = []
@@ -544,7 +547,10 @@ async def agent_wrapper(**kwargs: Any) -> str:
544547
stream_callback(update)
545548

546549
# Create final text from accumulated updates
547-
return AgentResponse.from_updates(response_updates).text
550+
final_response = AgentResponse.from_updates(response_updates)
551+
if final_response.user_input_requests:
552+
raise UserInputRequiredException(contents=final_response.user_input_requests)
553+
return final_response.text
548554

549555
agent_tool: FunctionTool = FunctionTool(
550556
name=tool_name,

‎python/packages/core/agent_framework/_tools.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
from pydantic import BaseModel, Field, ValidationError, create_model
3838

3939
from ._serialization import SerializationMixin
40-
from .exceptions import ToolException
40+
from .exceptions import ToolException, UserInputRequiredException
4141
from .observability import (
4242
OPERATION_DURATION_BUCKET_BOUNDARIES,
4343
OtelAttr,
@@ -1228,6 +1228,8 @@ async def _auto_invoke_function(
12281228
result=function_result,
12291229
additional_properties=function_call_content.additional_properties,
12301230
)
1231+
except UserInputRequiredException:
1232+
raise
12311233
except Exception as exc:
12321234
message = "Error: Function failed."
12331235
if config.get("include_detailed_errors", False):
@@ -1274,6 +1276,8 @@ async def final_function_handler(context_obj: Any) -> Any:
12741276
additional_properties=function_call_content.additional_properties,
12751277
)
12761278
raise
1279+
except UserInputRequiredException:
1280+
raise
12771281
except Exception as exc:
12781282
message = "Error: Function failed."
12791283
if config.get("include_detailed_errors", False):
@@ -1407,6 +1411,21 @@ async def invoke_with_termination_handling(
14071411
result=exc.result,
14081412
)
14091413
return (result_content, True)
1414+
except UserInputRequiredException as exc:
1415+
# Sub-agent requires user input — propagate the Content items so
1416+
# _handle_function_call_results can surface them to the parent response.
1417+
if exc.contents:
1418+
content = exc.contents[0]
1419+
content.call_id = function_call.call_id # type: ignore[attr-defined]
1420+
return (content, False)
1421+
return (
1422+
Content.from_function_result(
1423+
call_id=function_call.call_id, # type: ignore[arg-type]
1424+
result="Tool requires user input but no request details were provided.",
1425+
exception="UserInputRequiredException",
1426+
),
1427+
False,
1428+
)
14101429

14111430
execution_results = await asyncio.gather(*[
14121431
invoke_with_termination_handling(function_call, seq_idx) for seq_idx, function_call in enumerate(function_calls)
@@ -1645,7 +1664,10 @@ def _handle_function_call_results(
16451664
) -> FunctionRequestResult:
16461665
from ._types import Message
16471666

1648-
if any(fccr.type in {"function_approval_request", "function_call"} for fccr in function_call_results):
1667+
if any(
1668+
fccr.type in {"function_approval_request", "function_call"} or fccr.user_input_request
1669+
for fccr in function_call_results
1670+
):
16491671
# Only add items that aren't already in the message (e.g. function_approval_request wrappers).
16501672
# Declaration-only function_call items are already present from the LLM response.
16511673
new_items = [fccr for fccr in function_call_results if fccr.type != "function_call"]

‎python/packages/core/agent_framework/exceptions.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,34 @@ class ToolExecutionException(ToolException):
180180
pass
181181

182182

183+
class UserInputRequiredException(ToolException):
184+
"""Raised when a tool wrapping a sub-agent requires user input to proceed.
185+
186+
This exception carries the ``user_input_request`` Content items emitted by
187+
the sub-agent (e.g., ``oauth_consent_request``, ``function_approval_request``)
188+
so the tool invocation layer can propagate them to the parent agent's response
189+
instead of swallowing them as a generic tool error.
190+
191+
Args:
192+
contents: The user-input-request Content items from the sub-agent response.
193+
message: Human-readable description of why user input is needed.
194+
"""
195+
196+
def __init__(
197+
self,
198+
contents: list[Any],
199+
message: str = "Tool requires user input to proceed.",
200+
) -> None:
201+
"""Create a UserInputRequiredException.
202+
203+
Args:
204+
contents: The user-input-request Content items from the sub-agent response.
205+
message: Human-readable description of why user input is needed.
206+
"""
207+
super().__init__(message, log_level=10)
208+
self.contents = contents
209+
210+
183211
# endregion
184212

185213
# region Middleware Exceptions

‎python/packages/core/tests/core/test_agents.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1452,4 +1452,72 @@ async def test_stores_by_default_with_store_false_injects_inmemory(client: Suppo
14521452
# endregion
14531453

14541454

1455+
# region as_tool user_input_request propagation
1456+
1457+
1458+
async def test_as_tool_raises_on_user_input_request_non_streaming(client: SupportsChatGetResponse) -> None:
1459+
"""Test that as_tool raises UserInputRequiredException when the sub-agent response has user_input_requests."""
1460+
from agent_framework.exceptions import UserInputRequiredException
1461+
1462+
# Configure mock client to return a response with oauth_consent_request content
1463+
consent_content = Content.from_oauth_consent_request(
1464+
consent_link="https://login.microsoftonline.com/consent",
1465+
)
1466+
client.responses = [ # type: ignore[attr-defined]
1467+
ChatResponse(messages=Message(role="assistant", contents=[consent_content])),
1468+
]
1469+
1470+
agent = Agent(client=client, name="OAuthAgent", description="Agent requiring consent")
1471+
agent_tool = agent.as_tool()
1472+
1473+
with raises(UserInputRequiredException) as exc_info:
1474+
await agent_tool.invoke(arguments=agent_tool.input_model(task="Do something"))
1475+
1476+
assert len(exc_info.value.contents) == 1
1477+
assert exc_info.value.contents[0].type == "oauth_consent_request"
1478+
assert exc_info.value.contents[0].consent_link == "https://login.microsoftonline.com/consent"
1479+
1480+
1481+
async def test_as_tool_raises_on_user_input_request_streaming(client: SupportsChatGetResponse) -> None:
1482+
"""Test that as_tool raises UserInputRequiredException in streaming mode."""
1483+
from agent_framework.exceptions import UserInputRequiredException
1484+
1485+
consent_content = Content.from_oauth_consent_request(
1486+
consent_link="https://login.microsoftonline.com/consent",
1487+
)
1488+
client.streaming_responses = [ # type: ignore[attr-defined]
1489+
[ChatResponseUpdate(contents=[consent_content], role="assistant")],
1490+
]
1491+
1492+
collected_updates: list[AgentResponseUpdate] = []
1493+
1494+
def stream_callback(update: AgentResponseUpdate) -> None:
1495+
collected_updates.append(update)
1496+
1497+
agent = Agent(client=client, name="OAuthAgent", description="Agent requiring consent")
1498+
agent_tool = agent.as_tool(stream_callback=stream_callback)
1499+
1500+
with raises(UserInputRequiredException) as exc_info:
1501+
await agent_tool.invoke(arguments=agent_tool.input_model(task="Do something"))
1502+
1503+
assert len(exc_info.value.contents) == 1
1504+
assert exc_info.value.contents[0].type == "oauth_consent_request"
1505+
# Stream callback should still have received the update before the exception
1506+
assert len(collected_updates) > 0
1507+
1508+
1509+
async def test_as_tool_returns_text_when_no_user_input_request(client: SupportsChatGetResponse) -> None:
1510+
"""Test that as_tool returns text normally when there are no user_input_requests."""
1511+
client.responses = [ # type: ignore[attr-defined]
1512+
ChatResponse(messages=Message(role="assistant", text="Here is the result")),
1513+
]
1514+
1515+
agent = Agent(client=client, name="NormalAgent", description="Normal agent")
1516+
agent_tool = agent.as_tool()
1517+
1518+
result = await agent_tool.invoke(arguments=agent_tool.input_model(task="Do something"))
1519+
1520+
assert result == "Here is the result"
1521+
1522+
14551523
# endregion

‎python/packages/core/tests/core/test_function_invocation_logic.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3511,4 +3511,61 @@ def test_dict_overwrites_existing_conversation_id(self):
35113511
assert kwargs["chat_options"]["conversation_id"] == "new_id"
35123512

35133513

3514+
# region UserInputRequiredException propagation through tool invocation
3515+
3516+
3517+
async def test_user_input_request_propagates_through_as_tool(chat_client_base: SupportsChatGetResponse):
3518+
"""Test that user_input_request content from a sub-agent wrapped as a tool propagates to the parent response.
3519+
3520+
This is an end-to-end test: sub-agent returns oauth_consent_request →
3521+
as_tool raises UserInputRequiredException → invoke_with_termination_handling catches it →
3522+
_handle_function_call_results returns "action": "return" → Content ends up in parent response.
3523+
"""
3524+
from agent_framework.exceptions import UserInputRequiredException
3525+
3526+
# Create a mock tool that simulates what as_tool does when the sub-agent
3527+
# returns user_input_request content
3528+
@tool(name="delegate_agent", approval_mode="never_require")
3529+
def delegate_tool(task: str) -> str:
3530+
raise UserInputRequiredException(
3531+
contents=[
3532+
Content.from_oauth_consent_request(
3533+
consent_link="https://login.microsoftonline.com/consent",
3534+
)
3535+
]
3536+
)
3537+
3538+
# Parent agent calls the tool, which raises UserInputRequiredException
3539+
chat_client_base.run_responses = [
3540+
ChatResponse(
3541+
messages=Message(
3542+
role="assistant",
3543+
contents=[
3544+
Content.from_function_call(call_id="1", name="delegate_agent", arguments='{"task": "do it"}'),
3545+
],
3546+
)
3547+
),
3548+
]
3549+
3550+
response = await chat_client_base.get_response(
3551+
[Message(role="user", text="delegate this")],
3552+
options={"tool_choice": "auto", "tools": [delegate_tool]},
3553+
)
3554+
3555+
# The oauth_consent_request Content should be in the parent response's assistant message
3556+
user_requests = [
3557+
content
3558+
for msg in response.messages
3559+
for content in msg.contents
3560+
if isinstance(content, Content) and content.user_input_request
3561+
]
3562+
assert len(user_requests) == 1
3563+
assert user_requests[0].type == "oauth_consent_request"
3564+
assert user_requests[0].consent_link == "https://login.microsoftonline.com/consent"
3565+
assert user_requests[0].user_input_request is True
3566+
3567+
3568+
# endregion
3569+
3570+
35143571
# endregion

0 commit comments

Comments
 (0)