Python: [BREAKING] Standardize orchestration terminal outputs as AgentResponse (#5301)

* Fix orchestration outputs so as_agent() returns the final answer only. Align other orchestration outputs

* Fix orchestration output issues from review comments

1. Sample cleanup: Remove commented-out FoundryChatClient block and update
   prerequisites to reference OPENAI_CHAT_MODEL_ID instead of FOUNDRY_* vars.

2. Sequential approval output: Change _EndWithConversation.end_with_agent_executor_response
   from a no-op sink to yield response.agent_response. When the last participant is
   AgentApprovalExecutor (via with_request_info), _EndWithConversation is the output
   executor so the yield produces the terminal answer. When the last participant is a
   regular AgentExecutor, _EndWithConversation is not in output_executors so the yield
   is silently filtered out.

3. Forward data events through WorkflowExecutor: _process_workflow_result now also
   forwards 'data' events from sub-workflows so that emit_intermediate_data=True on
   AgentExecutor works correctly when wrapped in AgentApprovalExecutor.

4. Concurrent docstring: Update _AggregateAgentConversations docstring to say
   'deterministic participant order' instead of 'completion order'.

5. Add test_concurrent_intermediate_outputs_emits_data_events verifying that
   ConcurrentBuilder(intermediate_outputs=True) emits per-participant data events
   alongside the single aggregated output event.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Add tests for sequential workflow with_request_info and intermediate_outputs (#5301)

Address PR review comments 2, 3, and 5:

- Add test_sequential_request_info_last_participant_emits_output:
  Verifies that when the last participant is wrapped via with_request_info()
  (AgentApprovalExecutor), the workflow still emits a terminal output after
  approval, exercising the _EndWithConversation.end_with_agent_executor_response
  fallback path.

- Add test_sequential_request_info_with_intermediate_outputs_emits_data_events:
  Verifies that emit_intermediate_data=True works correctly through
  AgentApprovalExecutor wrapping—WorkflowExecutor._process_result already
  forwards data events from sub-workflows, so intermediate agent responses
  surface as data events in the parent workflow.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix pyright type errors from AgentResponse output refactor (#5301)

Update cast() calls in _group_chat.py and _magentic.py to use
WorkflowContext[Never, AgentResponse] instead of the old
WorkflowContext[Never, list[Message]], matching the updated method
signatures in _base_group_chat_orchestrator.py.

Fix _sequential.py _EndWithConversation.end_with_agent_executor_response
to declare WorkflowContext[Any, AgentResponse] so yield_output accepts
AgentResponse[None].

Fix _workflow_executor.py data event forwarding to handle nullable
executor_id.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix pyright reportUnknownVariableType in _agent.py (#5301)

Extract event.data into a typed local variable before the isinstance
check to avoid pyright narrowing it to AgentResponse[Unknown].

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix pyright reportMissingImports for orjson in file history samples (#5301)

Add pyright: ignore[reportMissingImports] to orjson imports that are
already guarded by try/except ImportError, matching the existing pattern
used elsewhere in the samples.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Address review feedback for #5301: review comment fixes

* Address review feedback for #5301: review comment fixes

* Revert sequential_workflow_as_agent sample to FoundryChatClient

Reverts the mistaken switch from FoundryChatClient to OpenAIChatClient
in the sequential workflow as agent sample.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Address ultrareview feedback: emit_data_events rename + WorkflowAgent reasoning conversion

Layered on top of the prior review-feedback work in this branch.

Renames:
- AgentExecutor.emit_intermediate_data -> emit_data_events (mechanical
  rename; orchestration semantics live at the orchestration layer, not
  the general-purpose executor). Forwarded through MagenticAgentExecutor,
  AgentApprovalExecutor, and all orchestration call sites.
- HandoffAgentExecutor._check_terminate_and_yield -> _should_terminate
  (pure predicate; no longer yields anything). HandoffBuilder docstring
  rewritten to describe the new per-agent AgentResponse output contract.

WorkflowAgent reasoning-content conversion:
- Add _rewrite_text_to_reasoning(contents) and _msg_as_reasoning(msg)
  helpers; the as_agent() path now reframes text content from data events
  as text_reasoning Content blocks before merging into the AgentResponse.
- Consumers iterate msg.contents and branch on content.type — same path
  they already use for Claude thinking and OpenAI reasoning. No new
  field on Message/AgentResponse/WorkflowEvent.
- Streaming branch constructs fresh AgentResponseUpdate instances instead
  of mutating shared payloads (regression test added).
- Helper _msg_maybe_reasoning consolidates the conditional rewrite at
  three call sites in the non-streaming conversion.

Tests:
- TestWorkflowAgentReasoningHelpers + TestWorkflowAgentDataEventReasoningConversion
  add 9 new tests covering helpers, non-streaming, streaming, mixed content,
  already-reasoning passthrough, and mutation-safety regression.
- Updated test_sequential_as_agent_with_intermediate_outputs_includes_chain
  to assert text_reasoning content for intermediate agents.

* Fix pyright: widen event.data to Any to avoid partial-unknown narrowing

The streaming conversion path narrowed event.data via isinstance against
generic AgentResponse, producing AgentResponse[Unknown] and tripping
reportUnknownVariableType/reportUnknownMemberType. Binding data: Any
before the check keeps runtime behavior identical while restoring a fully
known type for downstream access.

* Clean up design

* Scope to agent output semantics only

* yield AgentResponseUpdate streaming, AgentResponse non-streaming

* Fix mypy/pyright: widen cast types at GroupChat callsites

Eight callsites in _group_chat.py still cast to WorkflowContext[Never,
AgentResponse] but the base orchestrator methods now accept the wider
WorkflowContext[Never, AgentResponse | AgentResponseUpdate] (mode-aware
yields). W_OutT is invariant, so the narrower cast is not assignable.
Magentic was widened in the same commit; this catches the GroupChat
callsites that were missed.

* Python: skip flaky Foundry / Foundry Hosting integration tests (#5553)

These two integration tests have been failing in the merge queue across
multiple unrelated PRs (5301, 5531). Both are marked `@pytest.mark.flaky`
with 3 retries, but all attempts fail back-to-back. Skipping both with a
reason pointing to #5553 so they can be fixed properly without continuing
to block unrelated merges.

- packages/foundry_hosting/tests/test_responses_int.py::TestOptions::test_temperature_and_max_tokens
- packages/foundry/tests/foundry/test_foundry_embedding_client.py::TestFoundryEmbeddingIntegration::test_text_embedding_live

Also includes a one-line uv.lock specifier-ordering normalization
auto-applied by the poe-check pre-commit hook.

---------

Co-authored-by: Copilot <copilot@github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Evan Mattson
2026-04-29 00:35:36 +00:00
committed by GitHub
co-authored by Copilot Copilot
parent 40e90c96c3
commit 866a325b48
22 changed files with 785 additions and 490 deletions
@@ -238,18 +238,16 @@ async def test_group_chat_builder_basic_flow() -> None:
orchestrator_name="manager",
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("coordinate task", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert len(outputs) == 1
assert len(outputs[0]) >= 1
# Check that both agents contributed
authors = {msg.author_name for msg in outputs[0] if msg.author_name in ["alpha", "beta"]}
assert len(authors) == 2
# Exactly one terminal `output` event = the orchestrator's completion AgentResponseUpdate
# (mode-aware: streaming yields a single update chunk for the synthesized message).
assert len(updates) == 1
# The completion message is authored by the orchestrator.
assert updates[0].author_name == "manager"
async def test_group_chat_as_agent_accepts_conversation() -> None:
@@ -283,18 +281,16 @@ async def test_agent_manager_handles_concatenated_json_output() -> None:
orchestrator_agent=manager,
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("coordinate task", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert outputs
conversation = outputs[-1]
assert any(msg.author_name == "agent" and msg.text == "worker response" for msg in conversation)
assert conversation[-1].author_name == manager.name
assert conversation[-1].text == "concatenated manager final"
assert updates
final_update = updates[-1]
# Terminal update is the orchestrator's completion message.
assert final_update.author_name == manager.name
assert final_update.text == "concatenated manager final"
# Comprehensive tests for group chat functionality
@@ -400,20 +396,14 @@ class TestGroupChatWorkflow:
selection_func=selector,
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("test task", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
# Should have terminated due to max_rounds, expect at least one output
assert len(outputs) >= 1
# The final message in the conversation should be about round limit
conversation = outputs[-1]
assert len(conversation) >= 1
final_output = conversation[-1]
assert "maximum number of rounds" in final_output.text.lower()
# Exactly one terminal output event = orchestrator's max-rounds completion update.
assert len(updates) == 1
assert "maximum number of rounds" in (updates[0].text or "").lower()
async def test_termination_condition_halts_conversation(self) -> None:
"""Test that a custom termination condition stops the workflow."""
@@ -433,20 +423,89 @@ class TestGroupChatWorkflow:
selection_func=selector,
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("test task", stream=True):
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert updates, "Expected termination to yield output"
# Terminal update is the orchestrator's completion message only.
assert "termination condition" in (updates[-1].text or "").lower()
async def test_termination_yields_update_in_streaming(self) -> None:
"""In streaming mode, the orchestrator's terminal completion surfaces as `AgentResponseUpdate`.
Mirrors AgentExecutor's mode-aware behavior: streaming workflows produce per-chunk
`AgentResponseUpdate` events; the synthesized termination message is logically a
single chunk, so it should be a single `AgentResponseUpdate`.
"""
def selector(state: GroupChatState) -> str:
return "agent"
def termination_condition(conversation: list[Message]) -> bool:
replies = [msg for msg in conversation if msg.role == "assistant" and msg.author_name == "agent"]
return len(replies) >= 2
workflow = GroupChatBuilder(
participants=[StubAgent("agent", "response")],
termination_condition=termination_condition,
selection_func=selector,
).build()
terminal: AgentResponseUpdate | None = None
async for event in workflow.run("test task", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
terminal = event.data # last output event wins
assert outputs, "Expected termination to yield output"
conversation = outputs[-1]
agent_replies = [msg for msg in conversation if msg.author_name == "agent" and msg.role == "assistant"]
assert len(agent_replies) == 2
final_output = conversation[-1]
# The orchestrator uses its ID as author_name by default
assert "termination condition" in final_output.text.lower()
assert isinstance(terminal, AgentResponseUpdate), (
f"Expected AgentResponseUpdate in streaming mode, got {type(terminal).__name__}"
)
assert "termination condition" in (terminal.text or "").lower()
async def test_termination_yields_response_in_non_streaming(self) -> None:
"""In non-streaming mode, the orchestrator's terminal completion surfaces as `AgentResponse`."""
def selector(state: GroupChatState) -> str:
return "agent"
def termination_condition(conversation: list[Message]) -> bool:
replies = [msg for msg in conversation if msg.role == "assistant" and msg.author_name == "agent"]
return len(replies) >= 2
workflow = GroupChatBuilder(
participants=[StubAgent("agent", "response")],
termination_condition=termination_condition,
selection_func=selector,
).build()
events = await workflow.run("test task")
outputs = [ev for ev in events if ev.type == "output"]
assert len(outputs) == 1
assert isinstance(outputs[0].data, AgentResponse)
assert "termination condition" in outputs[0].data.messages[-1].text.lower()
async def test_max_rounds_yields_update_in_streaming(self) -> None:
"""Max-rounds completion in streaming mode surfaces as `AgentResponseUpdate`."""
def selector(state: GroupChatState) -> str:
return "agent"
workflow = GroupChatBuilder(
participants=[StubAgent("agent", "response")],
max_rounds=2,
selection_func=selector,
).build()
terminal: AgentResponseUpdate | None = None
async for event in workflow.run("test task", stream=True):
if event.type == "output":
terminal = event.data
assert isinstance(terminal, AgentResponseUpdate), (
f"Expected AgentResponseUpdate in streaming mode, got {type(terminal).__name__}"
)
assert "maximum number of rounds" in (terminal.text or "").lower()
async def test_termination_condition_agent_manager_finalizes(self) -> None:
"""Test that termination condition with agent orchestrator produces default termination message."""
@@ -459,17 +518,15 @@ class TestGroupChatWorkflow:
orchestrator_agent=manager,
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("test task", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert outputs, "Expected termination to yield output"
conversation = outputs[-1]
assert conversation[-1].text == BaseGroupChatOrchestrator.TERMINATION_CONDITION_MET_MESSAGE
assert conversation[-1].author_name == manager.name
assert updates, "Expected termination to yield output"
final_update = updates[-1]
assert final_update.text == BaseGroupChatOrchestrator.TERMINATION_CONDITION_MET_MESSAGE
assert final_update.author_name == manager.name
async def test_unknown_participant_error(self) -> None:
"""Test that unknown participant selection raises error."""
@@ -505,14 +562,12 @@ class TestCheckpointing:
selection_func=selector,
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("test task", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert len(outputs) == 1 # Should complete normally
assert len(updates) == 1 # Should complete normally
class TestConversationHandling:
@@ -546,14 +601,12 @@ class TestConversationHandling:
workflow = GroupChatBuilder(participants=[agent], max_rounds=1, selection_func=selector).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("test string", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert len(outputs) == 1
assert len(updates) == 1
async def test_handle_chat_message_input(self) -> None:
"""Test handling Message input directly."""
@@ -569,14 +622,12 @@ class TestConversationHandling:
workflow = GroupChatBuilder(participants=[agent], max_rounds=1, selection_func=selector).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run(task_message, stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert len(outputs) == 1
assert len(updates) == 1
async def test_handle_conversation_list_input(self) -> None:
"""Test handling conversation list preserves context."""
@@ -595,14 +646,12 @@ class TestConversationHandling:
workflow = GroupChatBuilder(participants=[agent], max_rounds=1, selection_func=selector).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run(conversation, stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
assert len(outputs) == 1
assert len(updates) == 1
class TestRoundLimitEnforcement:
@@ -625,20 +674,14 @@ class TestRoundLimitEnforcement:
selection_func=selector,
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("test", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
# Should have at least one output (the round limit message)
assert len(outputs) >= 1
# The last message in the conversation should be about round limit
conversation = outputs[-1]
assert len(conversation) >= 1
final_output = conversation[-1]
assert "maximum number of rounds" in final_output.text.lower()
# Exactly one terminal output event = orchestrator's max-rounds completion update.
assert len(updates) == 1
assert "maximum number of rounds" in (updates[0].text or "").lower()
async def test_round_limit_in_ingest_participant_message(self) -> None:
"""Test round limit enforcement after participant response."""
@@ -658,20 +701,14 @@ class TestRoundLimitEnforcement:
selection_func=selector,
).build()
outputs: list[list[Message]] = []
updates: list[AgentResponseUpdate] = []
async for event in workflow.run("test", stream=True):
if event.type == "output":
data = event.data
if isinstance(data, list):
outputs.append(cast(list[Message], data))
if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
updates.append(event.data)
# Should have at least one output (the round limit message)
assert len(outputs) >= 1
# The last message in the conversation should be about round limit
conversation = outputs[-1]
assert len(conversation) >= 1
final_output = conversation[-1]
assert "maximum number of rounds" in final_output.text.lower()
# Exactly one terminal output event = orchestrator's max-rounds completion update.
assert len(updates) == 1
assert "maximum number of rounds" in (updates[0].text or "").lower()
async def test_group_chat_checkpoint_runtime_only() -> None:
@@ -684,17 +721,17 @@ async def test_group_chat_checkpoint_runtime_only() -> None:
wf = GroupChatBuilder(participants=[agent_a, agent_b], max_rounds=2, selection_func=selector).build()
baseline_output: list[Message] | None = None
baseline_update: AgentResponseUpdate | None = None
async for ev in wf.run("runtime checkpoint test", checkpoint_storage=storage, stream=True):
if ev.type == "output":
baseline_output = cast(list[Message], ev.data) if isinstance(ev.data, list) else None # type: ignore
if ev.type == "output" and isinstance(ev.data, AgentResponseUpdate):
baseline_update = ev.data
if ev.type == "status" and ev.state in (
WorkflowRunState.IDLE,
WorkflowRunState.IDLE_WITH_PENDING_REQUESTS,
):
break
assert baseline_output is not None
assert baseline_update is not None
checkpoints = await storage.list_checkpoints(workflow_name=wf.name)
assert len(checkpoints) > 0, "Runtime-only checkpointing should have created checkpoints"
@@ -720,17 +757,17 @@ async def test_group_chat_checkpoint_runtime_overrides_buildtime() -> None:
checkpoint_storage=buildtime_storage,
selection_func=selector,
).build()
baseline_output: list[Message] | None = None
baseline_update: AgentResponseUpdate | None = None
async for ev in wf.run("override test", checkpoint_storage=runtime_storage, stream=True):
if ev.type == "output":
baseline_output = cast(list[Message], ev.data) if isinstance(ev.data, list) else None # type: ignore
if ev.type == "output" and isinstance(ev.data, AgentResponseUpdate):
baseline_update = ev.data
if ev.type == "status" and ev.state in (
WorkflowRunState.IDLE,
WorkflowRunState.IDLE_WITH_PENDING_REQUESTS,
):
break
assert baseline_output is not None
assert baseline_update is not None
buildtime_checkpoints = await buildtime_storage.list_checkpoints(workflow_name=wf.name)
runtime_checkpoints = await runtime_storage.list_checkpoints(workflow_name=wf.name)
@@ -974,14 +1011,11 @@ async def test_group_chat_with_orchestrator_factory_returning_chat_agent():
outputs.append(event)
assert len(outputs) == 1
# The DynamicManagerAgent terminates after second call with final_message
final_messages = outputs[0].data
assert isinstance(final_messages, list)
assert any(
msg.text == "dynamic manager final"
for msg in cast(list[Message], final_messages)
if msg.author_name == "dynamic_manager"
)
# Streaming mode: terminal yield is AgentResponseUpdate. The DynamicManagerAgent
# terminates after second call with final_message.
final_update = outputs[0].data
assert isinstance(final_update, AgentResponseUpdate)
assert final_update.text == "dynamic manager final"
def test_group_chat_with_orchestrator_factory_returning_base_orchestrator():