Skip to content

Commit 97fedac

Browse files
authored
Implement message filtering in agent workflow to stop emitting existing messages in response
Add a method to filter messages and update message handling. This helps remove the user messages being duplicated/emitted in the response This fixes the microsoft#4261 for both streaming and non streaming functions
1 parent 6138487 commit 97fedac

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

  • python/packages/core/agent_framework/_workflows

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,14 @@ def run(
213213
)
214214
return self._run_impl(messages, response_id, session, checkpoint_id, checkpoint_storage, **kwargs)
215215

216+
def _filter_messages(self, chat_messages: list[Message]) -> list[Message] | None:
217+
"""From a list[Message] output, return only the last meaningful assistant message."""
218+
for msg in reversed(chat_messages):
219+
if msg.role != "user" and msg.text and msg.text.strip():
220+
return [msg]
221+
# fallback: last non-user message
222+
return [m for m in reversed(chat_messages) if m.role != "user"][:1]
223+
216224
async def _run_impl(
217225
self,
218226
messages: AgentRunInputs,
@@ -476,7 +484,7 @@ def _convert_workflow_events_to_agent_response(
476484
messages.append(data)
477485
raw_representations.append(data.raw_representation)
478486
elif is_instance_of(data, list[Message]):
479-
chat_messages = cast(list[Message], data)
487+
chat_messages = self._filter_messages(cast(list[Message], data))
480488
messages.extend(chat_messages)
481489
raw_representations.append(data)
482490
else:
@@ -593,7 +601,7 @@ def _convert_workflow_event_to_agent_response_updates(
593601
]
594602
if is_instance_of(data, list[Message]):
595603
# Convert each Message to an AgentResponseUpdate
596-
chat_messages = cast(list[Message], data)
604+
chat_messages = self._filter_messages(cast(list[Message], data))
597605
updates = []
598606
for msg in chat_messages:
599607
updates.append(

0 commit comments

Comments
 (0)