Skip to content

Commit f320aed

Browse files
committed
fix(workflows): drop assistant function calls orphaned by role filtering
Role-only filtering kept assistant(function_call) while dropping its tool(function_result), producing an invalid call-without-result transcript that providers reject on replay when the response is persisted through a session. Assistant messages whose contents are entirely function-call envelopes are now dropped alongside the non-assistant messages, so the public response carries only user-facing assistant output with no dangling calls. Regression test covers call → tool result → final. Signed-off-by: Manohar Paturi <[email protected]>
1 parent cf2a1c0 commit f320aed

2 files changed

Lines changed: 81 additions & 14 deletions

File tree

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

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,19 @@
33
from __future__ import annotations
44

55
import logging
6-
import sys
76
import uuid
87
from collections.abc import AsyncIterable, Awaitable, Callable, Mapping, Sequence
98
from dataclasses import dataclass
109
from datetime import datetime, timezone
11-
from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast, overload
10+
from typing import (
11+
TYPE_CHECKING,
12+
Any,
13+
ClassVar,
14+
Literal,
15+
TypedDict, # pragma: no cover
16+
cast,
17+
overload,
18+
)
1219

1320
from .._agents import BaseAgent
1421
from .._sessions import (
@@ -41,17 +48,30 @@
4148
from ._message_utils import normalize_messages_input
4249
from ._typing_utils import is_instance_of, is_type_compatible
4350

44-
if sys.version_info >= (3, 11):
45-
from typing import TypedDict # pragma: no cover
46-
else:
47-
from typing_extensions import TypedDict # pragma: no cover
48-
4951
if TYPE_CHECKING:
5052
from ._workflow import Workflow, WorkflowInvocationKwargs
5153

5254
logger = logging.getLogger(__name__)
5355

5456

57+
def _is_orphaned_function_call(message: Message) -> bool:
58+
"""Drop a call whose result cannot follow it.
59+
60+
True when an assistant message is only a function call whose tool result
61+
is not assistant-role, so keeping the call alone would produce an invalid
62+
(unpaired) transcript for providers that validate call/result history.
63+
"""
64+
if message.role != "assistant":
65+
return False
66+
contents = list(getattr(message, "contents", []) or [])
67+
if not contents:
68+
return False
69+
# Orphaned only when every content is a function-call envelope
70+
return all(
71+
getattr(content, "type", None) in ("function_call", "function_approval_response") for content in contents
72+
)
73+
74+
5575
class WorkflowAgent(BaseAgent):
5676
"""An `Agent` subclass that wraps a workflow and exposes it as an agent."""
5777

@@ -591,7 +611,13 @@ def _convert_workflow_events_to_agent_response(
591611
# are intentionally excluded. System prompts and tool results are
592612
# internal workflow artifacts; user messages would be re-emitted
593613
# (e.g., from GroupChat orchestrators that include full conversation history).
594-
assistant_messages = [msg for msg in data.messages if msg.role == "assistant"]
614+
# Assistant messages that are bare function calls are also dropped
615+
# when their tool result is not assistant-role: a call without its
616+
# result is an invalid transcript for providers that validate
617+
# call/result pairing on replay.
618+
assistant_messages = [
619+
msg for msg in data.messages if msg.role == "assistant" and not _is_orphaned_function_call(msg)
620+
]
595621
if assistant_messages:
596622
messages.extend(assistant_messages)
597623
raw_representations.append(data.raw_representation)
@@ -609,17 +635,19 @@ def _convert_workflow_events_to_agent_response(
609635
raw_representations.append(data.raw_representation)
610636
elif is_instance_of(data, list[Message]):
611637
chat_messages = cast(list[Message], data)
612-
assistant_messages = [msg for msg in chat_messages if msg.role == "assistant"]
638+
# Keep tool results that pair with surviving assistant calls so the
639+
# transcript stays valid; drop user/system and orphaned calls.
640+
assistant_messages = [
641+
msg for msg in chat_messages if msg.role == "assistant" and not _is_orphaned_function_call(msg)
642+
]
613643
if assistant_messages:
614644
messages.extend(assistant_messages)
615645
# raw_representation of a filtered list must not leak the
616646
# non-assistant entries the public messages list dropped.
617647
if len(assistant_messages) == len(chat_messages):
618648
raw_representations.append(data)
619649
else:
620-
raw_representations.extend(
621-
msg.raw_representation for msg in assistant_messages
622-
)
650+
raw_representations.extend(msg.raw_representation for msg in assistant_messages)
623651
else:
624652
contents = self._extract_contents(data)
625653
if not contents:

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

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,9 @@
33
import uuid
44
from collections.abc import Awaitable, Sequence
55
from dataclasses import dataclass
6-
from typing import Any, Literal, cast, overload
6+
from typing import Any, Literal, Never, assert_type, cast, overload
77

88
import pytest
9-
from typing_extensions import Never, assert_type
109

1110
from agent_framework import (
1211
AgentExecutorRequest,
@@ -2682,6 +2681,46 @@ async def mixed_list_executor(
26822681
for rep in result.raw_representation or []:
26832682
assert rep is None or (isinstance(rep, Message) and rep.role == "assistant")
26842683

2684+
async def test_workflow_as_agent_drops_orphaned_function_calls(self) -> None:
2685+
"""assistant(function_call) whose tool result is tool-role must not survive filtering.
2686+
2687+
Keeping the call without its result would produce an invalid transcript for
2688+
providers that validate call/result pairing on replay (eavanvalkenburg's review).
2689+
"""
2690+
2691+
@executor
2692+
async def tool_transcript_executor(
2693+
messages: list[Message],
2694+
ctx: WorkflowContext[Never, list[Message]], # type: ignore[valid-type]
2695+
) -> None:
2696+
await ctx.yield_output([
2697+
Message(
2698+
role="assistant",
2699+
contents=[
2700+
Content.from_function_call(call_id="call-1", name="get_weather", arguments={"city": "Paris"}),
2701+
],
2702+
),
2703+
Message(
2704+
role="tool",
2705+
contents=[
2706+
Content.from_function_result(call_id="call-1", result="18C"),
2707+
],
2708+
),
2709+
Message(role="assistant", contents=[Content.from_text("It is 18C in Paris.")]),
2710+
])
2711+
2712+
workflow = WorkflowBuilder(start_executor=tool_transcript_executor).build()
2713+
agent = workflow.as_agent("tool-transcript-agent")
2714+
2715+
result = await agent.run("weather")
2716+
2717+
# The orphaned call is dropped; the final user-facing answer survives.
2718+
assert all(msg.role == "assistant" for msg in result.messages)
2719+
assert not any(
2720+
getattr(content, "type", None) == "function_call" for msg in result.messages for content in msg.contents
2721+
)
2722+
assert any("18C" in (getattr(content, "text", "") or "") for msg in result.messages for content in msg.contents)
2723+
26852724
async def test_workflow_as_agent_filters_single_non_assistant_message(self) -> None:
26862725
"""Verify WorkflowAgent filters a single Message when role is not assistant."""
26872726

0 commit comments

Comments
 (0)