Skip to content

Commit d26fc25

Browse files
author
alliscode
committed
Filter user-role messages from WorkflowAgent response stream
When WorkflowAgent converts workflow output events to AgentResponseUpdate (streaming) or AgentResponse (non-streaming), user-role messages are now filtered out. This prevents orchestration executors (e.g. HandoffBuilder) that yield the full conversation from echoing the user's input back as part of the agent's response. The fix applies to all code paths in _convert_workflow_event_to_agent_response_updates and _convert_workflow_events_to_agent_response that process Message or list[Message] data, consistently skipping messages with role='user'. Fixes microsoft#3206
1 parent 804dbb6 commit d26fc25

3 files changed

Lines changed: 58 additions & 13 deletions

File tree

‎python/packages/core/agent_framework/_workflows/_agent.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,7 @@ def _convert_workflow_events_to_agent_response(
462462
)
463463

464464
if isinstance(data, AgentResponse):
465-
messages.extend(data.messages)
465+
messages.extend(msg for msg in data.messages if msg.role != "user")
466466
raw_representations.append(data.raw_representation)
467467
merged_usage = add_usage_details(merged_usage, data.usage_details)
468468
latest_created_at = (
@@ -473,11 +473,12 @@ def _convert_workflow_events_to_agent_response(
473473
else latest_created_at
474474
)
475475
elif isinstance(data, Message):
476-
messages.append(data)
477-
raw_representations.append(data.raw_representation)
476+
if data.role != "user":
477+
messages.append(data)
478+
raw_representations.append(data.raw_representation)
478479
elif is_instance_of(data, list[Message]):
479480
chat_messages = cast(list[Message], data)
480-
messages.extend(chat_messages)
481+
messages.extend(msg for msg in chat_messages if msg.role != "user")
481482
raw_representations.append(data)
482483
else:
483484
contents = self._extract_contents(data)
@@ -566,6 +567,8 @@ def _convert_workflow_event_to_agent_response_updates(
566567
# Convert each message in AgentResponse to an AgentResponseUpdate
567568
updates: list[AgentResponseUpdate] = []
568569
for msg in data.messages:
570+
if msg.role == "user":
571+
continue
569572
updates.append(
570573
AgentResponseUpdate(
571574
contents=list(msg.contents),
@@ -580,6 +583,8 @@ def _convert_workflow_event_to_agent_response_updates(
580583
)
581584
return updates
582585
if isinstance(data, Message):
586+
if data.role == "user":
587+
return []
583588
return [
584589
AgentResponseUpdate(
585590
contents=list(data.contents),
@@ -596,6 +601,8 @@ def _convert_workflow_event_to_agent_response_updates(
596601
chat_messages = cast(list[Message], data)
597602
updates = []
598603
for msg in chat_messages:
604+
if msg.role == "user":
605+
continue
599606
updates.append(
600607
AgentResponseUpdate(
601608
contents=list(msg.contents),

‎python/packages/core/tests/workflow/test_workflow_agent.py‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -469,10 +469,11 @@ async def raw_yielding_executor(
469469
assert updates[2].raw_representation.value == 42
470470

471471
async def test_workflow_as_agent_yield_output_with_list_of_chat_messages(self) -> None:
472-
"""Test that yield_output with list[Message] extracts contents from all messages.
472+
"""Test that yield_output with list[Message] extracts contents from non-user messages.
473473
474-
Note: Content items are coalesced by _finalize_response, so multiple text contents
475-
become a single merged Content in the final response.
474+
User-role messages are filtered out since agent responses should only contain
475+
assistant/tool output. Content items are coalesced by _finalize_response, so
476+
multiple text contents become a single merged Content in the final response.
476477
"""
477478

478479
@executor
@@ -491,25 +492,25 @@ async def list_yielding_executor(messages: list[Message], ctx: WorkflowContext[N
491492
workflow = WorkflowBuilder(start_executor=list_yielding_executor).build()
492493
agent = workflow.as_agent("list-msg-agent")
493494

494-
# Verify streaming returns the update with all 4 contents before coalescing
495+
# Verify streaming returns updates for non-user messages only
495496
updates: list[AgentResponseUpdate] = []
496497
async for update in agent.run("test", stream=True):
497498
updates.append(update)
498499

499-
assert len(updates) == 3
500+
assert len(updates) == 2
500501
full_response = AgentResponse.from_updates(updates)
501-
assert len(full_response.messages) == 3
502+
assert len(full_response.messages) == 2
502503
texts = [message.text for message in full_response.messages]
503504
# Note: `from_agent_run_response_updates` coalesces multiple text contents into one content
504-
assert texts == ["first message", "second message", "thirdfourth"]
505+
assert texts == ["second message", "thirdfourth"]
505506

506507
# Verify run()
507508
result = await agent.run("test")
508509

509510
assert isinstance(result, AgentResponse)
510-
assert len(result.messages) == 3
511+
assert len(result.messages) == 2
511512
texts = [message.text for message in result.messages]
512-
assert texts == ["first message", "second message", "third fourth"]
513+
assert texts == ["second message", "third fourth"]
513514

514515
async def test_session_conversation_history_included_in_workflow_run(self) -> None:
515516
"""Test that messages provided to agent.run() are passed through to the workflow."""

‎python/packages/orchestrations/tests/test_handoff.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import pytest
99
from agent_framework import (
1010
Agent,
11+
AgentResponseUpdate,
1112
BaseContextProvider,
1213
ChatResponse,
1314
ChatResponseUpdate,
@@ -1091,3 +1092,39 @@ def regular_tool() -> str:
10911092

10921093
call_next.assert_awaited_once()
10931094
assert context.result is None
1095+
1096+
1097+
async def test_handoff_as_agent_run_stream_does_not_echo_user_input() -> None:
1098+
"""WorkflowAgent wrapping a handoff workflow must not echo user input in streamed updates.
1099+
1100+
When HandoffAgentExecutor emits the full conversation via ctx.yield_output() on
1101+
termination, user-role messages from that list should not appear as
1102+
AgentResponseUpdate items in the stream returned by WorkflowAgent.run_stream().
1103+
"""
1104+
agent = MockHandoffAgent(name="single_agent")
1105+
1106+
workflow = (
1107+
HandoffBuilder(
1108+
participants=[agent],
1109+
# Terminate immediately after the agent responds (user msg + assistant msg = 2).
1110+
termination_condition=lambda conv: len(conv) >= 2,
1111+
)
1112+
.with_start_agent(agent)
1113+
.build()
1114+
)
1115+
1116+
workflow_agent = workflow.as_agent(name="test_workflow_agent")
1117+
1118+
user_input = "Hi! Can you help me with something?"
1119+
updates: list[AgentResponseUpdate] = []
1120+
async for update in workflow_agent.run(user_input, stream=True):
1121+
updates.append(update)
1122+
1123+
assert updates, "Expected at least one streaming update"
1124+
1125+
# The core assertion: no update should carry the user role.
1126+
user_role_updates = [u for u in updates if u.role == "user"]
1127+
assert not user_role_updates, (
1128+
f"User input was echoed back in the stream as {len(user_role_updates)} update(s). "
1129+
"Expected only assistant-role updates."
1130+
)

0 commit comments

Comments
 (0)