Python: [BREAKING] Moved to a single get_response and run API (#3379)

* WIP

* big update to new ResponseStream model

* fixed tests and typing

* fixed tests and typing

* fixed tools typevar import

* fix

* mypy fix

* mypy fixes and some cleanup

* fix missing quoted names

* and client

* fix  imports agui

* fix anthropic override

* fix agui

* fix ag ui

* fix import

* fix anthropic types

* fix mypy

* refactoring

* updated typing

* fix 3.11

* fixes

* redid layering of chat clients and agents

* redid layering of chat clients and agents

* Fix lint, type, and test issues after rebase

- Add @overload decorators to AgentProtocol.run() for type compatibility
- Add missing docstring params (middleware, function_invocation_configuration)
- Fix TODO format (TD002) by adding author tags
- Fix broken observability tests from upstream:
  - Replace non-existent use_instrumentation with direct instantiation
  - Replace non-existent use_agent_instrumentation with AgentTelemetryLayer mixin
  - Fix get_streaming_response to use get_response(stream=True)
  - Add AgentInitializationError import
  - Update streaming exception tests to match actual behavior

* Fix AgentExecutionException import error in test_agents.py

- Replace non-existent AgentExecutionException with AgentRunException

* Fix test import and asyncio deprecation issues

- Add 'tests' to pythonpath in ag-ui pyproject.toml for utils_test_ag_ui import
- Replace deprecated asyncio.get_event_loop().run_until_complete with asyncio.run

* Fix azure-ai test failures

- Update _prepare_options patching to use correct class path
- Fix test_to_azure_ai_agent_tools_web_search_missing_connection to clear env vars

* Convert ag-ui utils_test_ag_ui.py to conftest.py

- Move test utilities to conftest.py for proper pytest discovery
- Update all test imports to use conftest instead of utils_test_ag_ui
- Remove old utils_test_ag_ui.py file
- Revert pythonpath change in pyproject.toml

* fix: use relative imports for ag-ui test utilities

* fix agui

* Rename Bare*Client to Raw*Client and BaseChatClient

- Renamed BareChatClient to BaseChatClient (abstract base class)
- Renamed BareOpenAIChatClient to RawOpenAIChatClient
- Renamed BareOpenAIResponsesClient to RawOpenAIResponsesClient
- Renamed BareAzureAIClient to RawAzureAIClient
- Added warning docstrings to Raw* classes about layer ordering
- Updated README in samples/getting_started/agents/custom with layer docs
- Added test for span ordering with function calling

* Fix layer ordering: FunctionInvocationLayer before ChatTelemetryLayer

This ensures each inner LLM call gets its own telemetry span, resulting in
the correct span sequence: chat -> execute_tool -> chat

Updated all production clients and test mocks to use correct ordering:
- ChatMiddlewareLayer (first)
- FunctionInvocationLayer (second)
- ChatTelemetryLayer (third)
- BaseChatClient/Raw...Client (fourth)

* Remove run_stream usage

* Fix conversation_id propagation

* Python: Add BaseAgent implementation for Claude Agent SDK (#3509)

* Added ClaudeAgent implementation

* Updated streaming logic

* Small updates

* Small update

* Fixes

* Small fix

* Naming improvements

* Updated imports

* Addressed comments

* Updated package versions

* Update Claude agent connector layering

* fix test and plugin

* Store function middleware in invocation layer

* Fix telemetry streaming and ag-ui tests

* Remove legacy ag-ui tests folder

* updates

* Remove terminate flag from FunctionInvocationContext, use MiddlewareTermination instead

- Remove terminate attribute from FunctionInvocationContext
- Add result attribute to MiddlewareTermination to carry function results
- FunctionMiddlewarePipeline.execute() now lets MiddlewareTermination propagate
- _auto_invoke_function captures context.result in exception before re-raising
- _try_execute_function_calls catches MiddlewareTermination and sets should_terminate
- Fix handoff middleware to append to chat_client.function_middleware directly
- Update tests to use raise MiddlewareTermination instead of context.terminate
- Add middleware flow documentation in samples/concepts/tools/README.md
- Fix ag-ui to use FunctionMiddlewarePipeline instead of removed create_function_middleware_pipeline

* fix: remove references to removed terminate flag in purview tests, add type ignore

* fix: move _test_utils.py from package to test folder

* fix: call get_final_response() to trigger context provider notification in streaming test

* fix: correct broken links in tools README

* docs: clarify default middleware behavior in summary table

* fix: ensure inner stream result hooks are called when using map()/from_awaitable()

* Fix mypy type errors

* Address PR review comments on observability.py

- Remove TODO comment about unconsumed streams, add explanatory note instead
- Remove redundant _close_span cleanup hook (already called in _finalize_stream)
- Clarify behavior: cleanup hooks run after stream iteration, if stream is not
  consumed the span remains open until garbage collected

* Remove gen_ai.client.operation.duration from span attributes

Duration is a metrics-only attribute per OpenTelemetry semantic conventions.
It should be recorded to the histogram but not set as a span attribute.

* Remove duration from _get_response_attributes, pass directly to _capture_response

Duration is a metrics-only attribute. It's now passed directly to _capture_response
instead of being included in the attributes dict that gets set on the span.

* Remove redundant _close_span cleanup hook in AgentTelemetryLayer

_finalize_stream already calls _close_span() in its finally block,
so adding it as a separate cleanup hook is redundant.

* Use weakref.finalize to close span when stream is garbage collected

If a user creates a streaming response but never consumes it, the cleanup
hooks won't run. Now we register a weak reference finalizer that will close
the span when the stream object is garbage collected, ensuring spans don't
leak in this scenario.

* Fix _get_finalizers_from_stream to use _result_hooks attribute

Renamed function to _get_result_hooks_from_stream and fixed it to
look for the _result_hooks attribute which is the correct name in
ResponseStream class.

* Add missing asyncio import in test_request_info_mixin.py

* Fix leftover merge conflict marker in image_generation sample

* Update integration tests

* Fix integration tests: increase max_iterations from 1 to 2

Tests with tool_choice options require at least 2 iterations:
1. First iteration to get function call and execute the tool
2. Second iteration to get the final text response

With max_iterations=1, streaming tests would return early with only
the function call/result but no final text content.

* Fix duplicate function call error in conversation-based APIs

When using conversation_id (for Responses/Assistants APIs), the server
already has the function call message from the previous response. We
should only send the new function result message, not all messages
including the function call which would cause a duplicate ID error.

Fix: When conversation_id is set, only send the last message (the tool
result) instead of all response.messages.

* Add regression test for conversation_id propagation between tool iterations

Port test from PR #3664 with updates for new streaming API pattern.
Tests that conversation_id is properly updated in options dict during
function invocation loop iterations.

* Fix tool_choice=required to return after tool execution

When tool_choice is 'required', the user's intent is to force exactly one
tool call. After the tool executes, return immediately with the function
call and result - don't continue to call the model again.

This fixes integration tests that were failing with empty text responses
because with tool_choice=required, the model would keep returning function
calls instead of text.

Also adds regression tests for:
- conversation_id propagation between tool iterations (from PR #3664)
- tool_choice=required returns after tool execution

* Document tool_choice behavior in tools README

- Add table explaining tool_choice values (auto, none, required)
- Explain why tool_choice=required returns immediately after tool execution
- Add code example showing the difference between required and auto
- Update flow diagram to show the early return path for tool_choice=required

* Fix tool_choice=None behavior - don't default to 'auto'

Remove the hardcoded default of 'auto' for tool_choice in ChatAgent init.
When tool_choice is not specified (None), it will now not be sent to the
API, allowing the API's default behavior to be used.

Users who want tool_choice='auto' can still explicitly set it either in
default_options or at runtime.

Fixes #3585

* Fix tool_choice=none should not remove tools

In OpenAI Assistants client, tools were not being sent when
tool_choice='none'. This was incorrect - tool_choice='none' means
the model won't call tools, but tools should still be available
in the request (they may be used later in the conversation).

Fixes #3585

* Add test for tool_choice=none preserving tools

Adds a regression test to ensure that when tool_choice='none' is set but
tools are provided, the tools are still sent to the API. This verifies
the fix for #3585.

* Fix tool_choice=none should not remove tools in all clients

Apply the same fix to OpenAI Responses client and Azure AI client:
- OpenAI Responses: Remove else block that popped tool_choice/parallel_tool_calls
- Azure AI: Remove tool_choice != 'none' check when adding tools

When tool_choice='none', the model won't call tools, but tools should
still be sent to the API so they're available for future turns.

Also update README to clarify tool_choice=required supports multiple tools.

Fixes #3585

* Keep tool_choice even when tools is None

Move tool_choice processing outside of the 'if tools' block in OpenAI
Responses client so tool_choice is sent to the API even when no tools
are provided.

* Update test to match new parallel_tool_calls behavior

Changed test_prepare_options_removes_parallel_tool_calls_when_no_tools to
test_prepare_options_preserves_parallel_tool_calls_when_no_tools to reflect
that parallel_tool_calls is now preserved even when no tools are present,
consistent with the tool_choice behavior.

* Fix ChatMessage API and Role enum usage after rebase

- Update ChatMessage instantiation to use keyword args (role=, text=, contents=)
- Fix Role enum comparisons to use .value for string comparison
- Add created_at to AgentResponse in error handling
- Fix AgentResponse.from_updates -> from_agent_run_response_updates
- Fix DurableAgentStateMessage.from_chat_message to convert Role enum to string
- Add Role import where needed

* Fix additional ChatMessage API and method name changes

- Fix ChatMessage usage in workflow files (use text= instead of contents= for strings)
- Fix AgentResponse.from_updates -> from_agent_run_response_updates in workflow files
- Fix test files for ChatMessage and Role enum usage

* Fix remaining ChatMessage API usage in test files

* Fix more ChatMessage and Role API changes in source and test files

- Fix ChatMessage in _magentic.py replan method
- Fix Role enum comparison in test assertions
- Fix remaining test files with old ChatMessage syntax

* Fix ChatMessage and Role API changes across packages

- Add Role import where missing
- Fix ChatMessage signature: positional args to keyword args (role=, text=, contents=)
- Fix Role enum comparisons: .role.value instead of .role string
- Fix FinishReason enum usage in ag-ui event converters
- Rename AgentResponse.from_updates to from_agent_run_response_updates in ag-ui

Fixes API compatibility after Types API Review improvements merge

* Fix ChatMessage and Role API changes in github_copilot tests

* Fix ChatMessage and Role API changes in redis and github_copilot packages

- Fix redis provider: Role enum comparison using .value
- Fix redis tests: ChatMessage signature and Role comparisons
- Fix github_copilot tests: ChatMessage signature and Role comparisons
- Update docstring examples in redis chat message store

* Fix ChatMessage and Role API changes in devui package

- Fix executor: ChatMessage signature change
- Fix conversations: Role enum to string conversion in two places
- Fix tests: ChatMessage signatures and Role comparisons

* Fix ChatMessage and Role API changes in a2a and lab packages

- Fix a2a tests: Role comparisons and ChatMessage signatures
- Fix lab tau2 source: Role enum comparison in flip_messages, log_messages, sliding_window
- Fix lab tau2 tests: ChatMessage signatures and Role comparisons

* Remove duplicate test files from ag-ui/tests (tests are in ag_ui_tests)

* Fix ChatMessage and Role API changes across packages

After rebasing on upstream/main which merged PR #3647 (Types API Review
improvements), fix all packages to use the new API:

- ChatMessage: Use keyword args (role=, text=, contents=) instead of
  positional args
- Role: Compare using .value attribute since it's now an enum

Packages fixed:
- ag-ui: Fixed Role value extraction bugs in _message_adapters.py
- anthropic: Fixed ChatMessage and Role comparisons in tests
- azure-ai: Fixed Role comparison in _client.py
- azure-ai-search: Fixed ChatMessage and Role in source/tests
- bedrock: Fixed ChatMessage signatures in tests
- chatkit: Fixed ChatMessage and Role in source/tests
- copilotstudio: Fixed ChatMessage and Role in tests
- declarative: Fixed ChatMessage in _executors_agents.py
- mem0: Fixed ChatMessage and Role in source/tests
- purview: Fixed ChatMessage in source/tests

* Fix mypy errors for ChatMessage and Role API changes

- durabletask: Use str() fallback in role value extraction
- core: Fix ChatMessage in _orchestrator_helpers.py to use keyword args
- core: Add type ignore for _conversation_state.py contents deserialization
- ag-ui: Fix type ignore comments (call-overload instead of arg-type)
- azure-ai-search: Fix get_role_value type hint to accept Any
- lab: Move get_role_value to module level with Any type hint

* Improve CI test timeout configuration

- Increase job timeout from 10 to 15 minutes
- Reduce per-test timeout to 60s (was 900s/300s)
- Add --timeout_method thread for better timeout handling
- Add --timeout-verbose to see which tests are slow
- Reduce retries from 3 to 2 and delay from 10s to 5s

This ensures individual test timeouts are shorter than the job
timeout, providing better visibility when tests hang.

With 60s timeout and 2 retries, worst case per test is ~180s.

* Fix ChatMessage API usage in docstrings and source

- Fix ChatMessage positional args in docstrings: _serialization.py, _threads.py, _middleware.py
- Fix ChatMessage in tau2 runner.py
- Fix role comparison in _orchestrator_helpers.py to use .value
- Fix role comparison in _group_chat.py docstring example
- Fix role assertions in test_durable_entities.py to use .value

* Revert tool_choice/parallel_tool_calls changes - must be removed when no tools

OpenAI API requires tool_choice and parallel_tool_calls to only be
present when tools are specified. Restored the logic that removes
these options when there are no tools.

- Restored check in _chat_client.py to remove tool_choice and
  parallel_tool_calls when no tools present
- Restored same logic in _responses_client.py
- Reverted test to expect the correct behavior

* fixed issue in tests

* fix: resolve merge conflict markers in ag-ui tests

* fix: restructure ag-ui tests and fix Role/FinishReason to use string types

* fix: streaming function invocation and middleware termination

- Refactor streaming function invocation to use get_final_response() on inner streams
- Fix MiddlewareTermination to accept result parameter for passing results
- Fix _AutoHandoffMiddleware to use MiddlewareTermination instead of context.terminate
- Fix AgentMiddlewareLayer.run() to properly forward function/chat middleware
- Remove duplicate middleware registration in AgentMiddlewareLayer.__init__
- Fix exception handling in _auto_invoke_function to properly capture termination
- Fix mypy errors in core package
- Update tests to use stream=True parameter for unified run API

* fix all tests command

* Refactor integration tests to use pytest fixtures

- Merge testutils.py into conftest.py for azurefunctions integration tests
- Merge dt_testutils.py into conftest.py for durabletask integration tests
- Convert all integration tests to use fixtures instead of direct imports
  (fixes ModuleNotFoundError with --import-mode=importlib)
- Add sample_helper fixture for azurefunctions tests
- Add agent_client_factory and orchestration_helper fixtures for durabletask
- Integration tests now skip with descriptive messages when services unavailable
- Restructure devui tests into tests/devui/ with proper conftest.py
- Add test organization guidelines to CODING_STANDARD.md
- Remove __init__.py from test directories per pytest best practices

* Fix pytest_collection_modifyitems to only skip integration tests

The hook was skipping all tests in the test session, not just
integration tests. Now it only skips items in the integration_tests
directory.

* Fix mem0 tests failing on Python 3.13

Use patch.object on the imported module instead of @patch with string
path to ensure the mock takes effect regardless of import timing.

* fix mem0

* another attempt for mem0

* fix for mem0

* fix mem0

* Increase worker initialization wait time in durabletask tests

Increase from 2 to 8 seconds to allow time for:
- Python startup and module imports
- Azure OpenAI client creation
- Agent registration with DTS worker
- Worker connection to DTS

This helps prevent test failures in CI where the first tests may run
before the worker is fully ready to process requests.

* Fix streaming test to use ResponseStream with finalizer

The _consume_stream method now expects a ResponseStream that can provide
a final AgentResponse via get_final_response(). Update the test to use
ResponseStream with AgentResponse.from_updates as the finalizer.

* Fix MockToolCallingAgent to use new ResponseStream API and update samples

* small updates to run_stream to run

* fix sub workflow

* temp fix for az func test

---------

Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
This commit is contained in:
Eduard van Valkenburg
2026-02-05 21:09:58 +01:00
committed by GitHub
Unverified
parent d1205896a1
commit 3dc59c83b5
372 changed files with 11583 additions and 9465 deletions
@@ -0,0 +1,785 @@
# Copyright (c) Microsoft. All rights reserved.
"""Focused tests for execution flow functionality.
Tests include:
- Entity discovery and info retrieval
- Agent execution (sync and streaming) using real ChatAgent with mock LLM
- Workflow execution using real WorkflowBuilder with FunctionExecutor
- Edge cases like non-streaming agents
"""
import asyncio
import tempfile
from pathlib import Path
from typing import Any
import pytest
from agent_framework import AgentExecutor, ChatAgent, FunctionExecutor, WorkflowBuilder
# Import mock classes from conftest for direct use in some tests
from conftest import MockBaseChatClient
from agent_framework_devui._discovery import EntityDiscovery
from agent_framework_devui._executor import AgentFrameworkExecutor, EntityNotFoundError
from agent_framework_devui._mapper import MessageMapper
from agent_framework_devui.models._openai_custom import AgentFrameworkRequest
# =============================================================================
# Local Fixtures (module-specific)
# =============================================================================
@pytest.fixture
async def executor(test_entities_dir):
"""Create configured executor."""
discovery = EntityDiscovery(test_entities_dir)
mapper = MessageMapper()
executor = AgentFrameworkExecutor(discovery, mapper)
# Discover entities
await executor.discover_entities()
return executor
async def test_executor_entity_discovery(executor):
"""Test executor entity discovery."""
entities = await executor.discover_entities()
# Should find entities from samples directory
assert len(entities) > 0, "Should discover at least one entity"
entity_types = [e.type for e in entities]
assert "agent" in entity_types, "Should find at least one agent"
assert "workflow" in entity_types, "Should find at least one workflow"
# Test entity structure
for entity in entities:
assert entity.id, "Entity should have an ID"
assert entity.name, "Entity should have a name"
# Entities with only an `__init__.py` file cannot have their type determined
# until the module is imported during lazy loading. This is why 'unknown' type exists.
assert entity.type in ["agent", "workflow", "unknown"], (
"Entity should have valid type (unknown allowed during discovery phase)"
)
async def test_executor_get_entity_info(executor):
"""Test getting entity info by ID."""
entities = await executor.discover_entities()
entity_id = entities[0].id
entity_info = executor.get_entity_info(entity_id)
assert entity_info is not None
assert entity_info.id == entity_id
assert entity_info.type in ["agent", "workflow", "unknown"]
# =============================================================================
# Agent Execution Tests (using real ChatAgent with mock LLM)
# =============================================================================
async def test_agent_sync_execution(executor_with_real_agent):
"""Test synchronous agent execution with REAL ChatAgent (mock LLM).
This tests the full execution pipeline without needing an API key:
- Real ChatAgent class with middleware
- Real message normalization
- Mock chat client for LLM calls
"""
executor, entity_id, mock_client = executor_with_real_agent
request = AgentFrameworkRequest(
metadata={"entity_id": entity_id},
input="test data",
stream=False,
)
response = await executor.execute_sync(request)
# Response model should be 'devui' when not specified
assert response.model == "devui"
assert response.object == "response"
assert len(response.output) > 0
# Verify mock client was called
assert mock_client.call_count == 1
async def test_agent_sync_execution_respects_model_field(executor_with_real_agent):
"""Test synchronous execution respects the model field in the response."""
executor, entity_id, mock_client = executor_with_real_agent
request = AgentFrameworkRequest(
metadata={"entity_id": entity_id},
model="custom-model-name",
input="test data",
stream=False,
)
response = await executor.execute_sync(request)
# Response model should reflect the specified model
assert response.model == "custom-model-name"
assert response.object == "response"
assert len(response.output) > 0
async def test_chat_client_receives_correct_messages(executor_with_real_agent):
"""Verify the mock chat client receives properly formatted messages.
This tests that the REAL ChatAgent properly:
- Normalizes input messages
- Formats messages for the chat client
"""
executor, entity_id, mock_client = executor_with_real_agent
request = AgentFrameworkRequest(
metadata={"entity_id": entity_id},
input="What is 2+2?",
stream=False,
)
await executor.execute_sync(request)
# Verify chat client was called
assert mock_client.call_count == 1
# Verify messages were received
assert len(mock_client.received_messages) == 1
messages = mock_client.received_messages[0]
# Should have at least one message
assert len(messages) >= 1, f"Expected messages, got: {messages}"
# Verify the input text is present in the messages
all_text = " ".join(m.text or "" for m in messages)
assert "2+2" in all_text, f"Expected '2+2' in messages, got text: '{all_text}'"
# =============================================================================
# Workflow Execution Tests (using real WorkflowBuilder with FunctionExecutor)
# =============================================================================
async def test_workflow_streaming_execution():
"""Test workflow streaming execution with REAL WorkflowBuilder and FunctionExecutor.
This tests the full workflow execution pipeline without needing an API key.
Uses a simple function-based workflow that processes input.
"""
# Create a simple workflow using real agent_framework classes
def process_input(input_data: str) -> str:
return f"Processed: {input_data}"
builder = WorkflowBuilder(name="Test Workflow", description="Test workflow for execution")
start_executor = FunctionExecutor(id="process", func=process_input)
builder.set_start_executor(start_executor)
workflow = builder.build()
# Create executor and register workflow
discovery = EntityDiscovery(None)
mapper = MessageMapper()
executor = AgentFrameworkExecutor(discovery, mapper)
entity_info = await discovery.create_entity_info_from_object(workflow, entity_type="workflow", source="test")
discovery.register_entity(entity_info.id, entity_info, workflow)
# Execute workflow
request = AgentFrameworkRequest(
metadata={"entity_id": entity_info.id},
input="hello workflow",
stream=True,
)
events = []
async for event in executor.execute_streaming(request):
events.append(event)
# Should get events from workflow execution
assert len(events) > 0, "Should receive events from workflow"
# Check for workflow-specific events or completion
event_types = [getattr(e, "type", None) for e in events]
assert any(t is not None for t in event_types), f"Should have typed events, got: {event_types}"
async def test_workflow_sync_execution():
"""Test synchronous workflow execution."""
def echo(text: str) -> str:
return f"Echo: {text}"
builder = WorkflowBuilder(name="Echo Workflow", description="Simple echo workflow")
start_executor = FunctionExecutor(id="echo", func=echo)
builder.set_start_executor(start_executor)
workflow = builder.build()
# Create executor and register workflow
discovery = EntityDiscovery(None)
mapper = MessageMapper()
executor = AgentFrameworkExecutor(discovery, mapper)
entity_info = await discovery.create_entity_info_from_object(workflow, entity_type="workflow", source="test")
discovery.register_entity(entity_info.id, entity_info, workflow)
# Execute workflow synchronously
request = AgentFrameworkRequest(
metadata={"entity_id": entity_info.id},
input="test input",
stream=False,
)
response = await executor.execute_sync(request)
# Should get a valid response
assert response.object == "response"
assert len(response.output) > 0
# =============================================================================
# Full Pipeline Serialization Tests (Run + Map + JSON)
# =============================================================================
async def test_full_pipeline_agent_events_are_json_serializable(executor_with_real_agent):
"""CRITICAL TEST: Verify ALL events from agent execution can be JSON serialized.
This tests the exact code path that the server uses:
1. Execute agent via executor.execute_streaming()
2. Each event is converted by the mapper
3. Server calls model_dump_json() on each event for SSE
If any event contains non-serializable objects (like AgentResponse),
this test will fail - catching the bug before it hits production.
"""
executor, entity_id, mock_client = executor_with_real_agent
request = AgentFrameworkRequest(
metadata={"entity_id": entity_id},
input="Test message for serialization",
stream=True,
)
events = []
serialization_errors = []
async for event in executor.execute_streaming(request):
events.append(event)
# This is EXACTLY what the server does before sending SSE
try:
if hasattr(event, "model_dump_json"):
json_str = event.model_dump_json()
assert json_str is not None
assert len(json_str) > 0
except Exception as e:
serialization_errors.append(f"Event type={getattr(event, 'type', 'unknown')}: {e}")
# Should have received events
assert len(events) > 0, "Should receive events from agent execution"
# NO serialization errors allowed
assert len(serialization_errors) == 0, f"Found {len(serialization_errors)} serialization errors:\n" + "\n".join(
serialization_errors
)
async def test_full_pipeline_workflow_events_are_json_serializable():
"""CRITICAL TEST: Verify ALL events from workflow execution can be JSON serialized.
This is particularly important for workflows with AgentExecutor because:
- AgentExecutor produces ExecutorCompletedEvent with AgentExecutorResponse
- AgentExecutorResponse contains AgentResponse and ChatMessage objects
- These are SerializationMixin objects, not Pydantic, which caused the original bug
This test ensures the ENTIRE streaming pipeline works end-to-end.
"""
# Create a workflow with AgentExecutor (the problematic case)
mock_client = MockBaseChatClient()
agent = ChatAgent(
id="serialization_test_agent",
name="Serialization Test Agent",
description="Agent for testing serialization",
chat_client=mock_client,
system_message="You are a test assistant.",
)
builder = WorkflowBuilder(name="Serialization Test Workflow", description="Test workflow")
agent_executor = AgentExecutor(id="agent_node", agent=agent)
builder.set_start_executor(agent_executor)
workflow = builder.build()
# Create executor and register
discovery = EntityDiscovery(None)
mapper = MessageMapper()
executor = AgentFrameworkExecutor(discovery, mapper)
entity_info = await discovery.create_entity_info_from_object(workflow, entity_type="workflow", source="test")
discovery.register_entity(entity_info.id, entity_info, workflow)
request = AgentFrameworkRequest(
metadata={"entity_id": entity_info.id},
input="Test workflow serialization",
stream=True,
)
events = []
serialization_errors = []
event_types_seen = []
async for event in executor.execute_streaming(request):
events.append(event)
event_type = getattr(event, "type", "unknown")
event_types_seen.append(event_type)
# This is EXACTLY what the server does before sending SSE
try:
if hasattr(event, "model_dump_json"):
json_str = event.model_dump_json()
assert json_str is not None
assert len(json_str) > 0
except Exception as e:
serialization_errors.append(f"Event type={event_type}: {e}")
# Should have received events
assert len(events) > 0, "Should receive events from workflow execution"
# Verify we got workflow events (not just generic ones)
assert any("output_item" in str(t) for t in event_types_seen), (
f"Should see output_item events, got: {event_types_seen}"
)
# NO serialization errors allowed - this is the critical assertion
assert len(serialization_errors) == 0, (
f"Found {len(serialization_errors)} serialization errors:\n"
+ "\n".join(serialization_errors)
+ f"\n\nEvent types seen: {event_types_seen}"
)
# Also verify aggregate_to_response works (server calls this after streaming)
final_response = await mapper.aggregate_to_response(events, request)
assert final_response is not None
async def test_get_entity_info_raises_for_invalid_id(executor):
"""Test that get_entity_info raises EntityNotFoundError for invalid ID."""
with pytest.raises(EntityNotFoundError):
executor.get_entity_info("nonexistent_agent")
async def test_request_extracts_entity_id_from_metadata(executor):
"""Test that AgentFrameworkRequest extracts entity_id from metadata."""
request = AgentFrameworkRequest(
metadata={"entity_id": "my_agent"},
input="test",
stream=False,
)
# entity_id is extracted from metadata
entity_id = request.get_entity_id()
assert entity_id == "my_agent"
@pytest.mark.asyncio
async def test_executor_get_start_executor_message_types(sequential_workflow):
"""Test _get_start_executor_message_types with real workflow."""
executor, _entity_id, _mock_client, workflow = sequential_workflow
start_exec, message_types = executor._get_start_executor_message_types(workflow)
assert start_exec is not None
assert len(message_types) > 0
# Real sequential workflows accept str input
assert str in message_types
def test_executor_select_primary_input_prefers_string():
"""Select string input even when discovered after other handlers."""
from agent_framework_devui._utils import select_primary_input_type
placeholder_type = type("Placeholder", (), {})
chosen = select_primary_input_type([placeholder_type, str])
assert chosen is str
@pytest.mark.asyncio
async def test_executor_parse_structured_extracts_input_for_string_workflow():
"""Structured payloads extract 'input' field when workflow expects str."""
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler
class StringInputExecutor(Executor):
"""Executor that accepts string input directly."""
@handler
async def process(self, text: str, ctx: WorkflowContext[Any, Any]) -> None:
await ctx.yield_output(f"Got: {text}")
workflow = (
WorkflowBuilder(name="String Workflow", description="Accepts string")
.set_start_executor(StringInputExecutor(id="str_exec"))
.build()
)
executor = AgentFrameworkExecutor(EntityDiscovery(None), MessageMapper())
# When workflow expects str and receives {"input": "hello"}, extract "hello"
parsed = executor._parse_structured_workflow_input(workflow, {"input": "hello"})
assert parsed == "hello"
@pytest.mark.asyncio
async def test_executor_parse_raw_string_for_string_workflow():
"""Raw string inputs pass through for string-accepting workflows."""
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler
class StringInputExecutor(Executor):
"""Executor that accepts string input directly."""
@handler
async def process(self, text: str, ctx: WorkflowContext[Any, Any]) -> None:
await ctx.yield_output(f"Got: {text}")
workflow = (
WorkflowBuilder(name="String Workflow", description="Accepts string")
.set_start_executor(StringInputExecutor(id="str_exec"))
.build()
)
executor = AgentFrameworkExecutor(EntityDiscovery(None), MessageMapper())
# Raw string should pass through unchanged
parsed = executor._parse_raw_workflow_input(workflow, "hi there")
assert parsed == "hi there"
@pytest.mark.asyncio
async def test_executor_parse_converts_to_chat_message_for_sequential_workflow(sequential_workflow):
"""Sequential workflows convert string input to ChatMessage."""
from agent_framework import ChatMessage
executor, _entity_id, _mock_client, workflow = sequential_workflow
# Sequential workflows expect ChatMessage, so raw string becomes ChatMessage
parsed = executor._parse_raw_workflow_input(workflow, "hello")
assert isinstance(parsed, ChatMessage)
assert parsed.text == "hello"
@pytest.mark.asyncio
async def test_executor_parse_stringified_json_workflow_input():
"""Stringified JSON workflow input is parsed when workflow expects Pydantic model."""
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler
from pydantic import BaseModel
class WorkflowInput(BaseModel):
input: str
metadata: dict | None = None
class PydanticInputExecutor(Executor):
"""Executor that accepts a Pydantic model input."""
@handler
async def process(self, data: WorkflowInput, ctx: WorkflowContext[Any, Any]) -> None:
await ctx.yield_output(f"Got: {data.input}")
# Build workflow with Pydantic input type
workflow = (
WorkflowBuilder(name="Pydantic Workflow", description="Accepts Pydantic input")
.set_start_executor(PydanticInputExecutor(id="pydantic_exec"))
.build()
)
executor = AgentFrameworkExecutor(EntityDiscovery(None), MessageMapper())
# Simulate frontend sending JSON.stringify({"input": "testing!", "metadata": {"key": "value"}})
stringified_json = '{"input": "testing!", "metadata": {"key": "value"}}'
parsed = executor._parse_raw_workflow_input(workflow, stringified_json)
# Should parse into WorkflowInput object
assert isinstance(parsed, WorkflowInput)
assert parsed.input == "testing!"
assert parsed.metadata == {"key": "value"}
def test_extract_workflow_hil_responses_handles_stringified_json():
"""Test HIL response extraction handles both stringified and parsed JSON (regression test)."""
from agent_framework_devui._discovery import EntityDiscovery
from agent_framework_devui._executor import AgentFrameworkExecutor
from agent_framework_devui._mapper import MessageMapper
executor = AgentFrameworkExecutor(EntityDiscovery(None), MessageMapper())
# Regression test: Frontend sends stringified JSON via streamWorkflowExecutionOpenAI
stringified = '[{"type":"message","content":[{"type":"workflow_hil_response","responses":{"req_1":"spam"}}]}]'
assert executor._extract_workflow_hil_responses(stringified) == {"req_1": "spam"}
# Ensure parsed format still works
parsed = [{"type": "message", "content": [{"type": "workflow_hil_response", "responses": {"req_2": "ham"}}]}]
assert executor._extract_workflow_hil_responses(parsed) == {"req_2": "ham"}
# Non-HIL inputs should return None
assert executor._extract_workflow_hil_responses("plain text") is None
assert executor._extract_workflow_hil_responses({"email": "test"}) is None
async def test_executor_handles_streaming_agent():
"""Test executor handles agents with run(stream=True) method."""
from agent_framework import AgentResponse, AgentResponseUpdate, AgentThread, ChatMessage, Content
class StreamingAgent:
"""Agent with run() method supporting stream parameter."""
id = "streaming_test"
name = "Streaming Test Agent"
description = "Test agent with run(stream=True)"
def run(self, messages=None, *, stream=False, thread=None, **kwargs):
if stream:
# Return an async generator for streaming
return self._stream_impl(messages)
# Return awaitable for non-streaming
return self._run_impl(messages)
async def _run_impl(self, messages):
return AgentResponse(
messages=[ChatMessage(role="assistant", contents=[Content.from_text(text=f"Processed: {messages}")])],
response_id="test_123",
)
async def _stream_impl(self, messages):
yield AgentResponseUpdate(
contents=[Content.from_text(text=f"Processed: {messages}")],
role="assistant",
)
def get_new_thread(self, **kwargs):
return AgentThread()
# Create executor and register agent
discovery = EntityDiscovery(None)
mapper = MessageMapper()
executor = AgentFrameworkExecutor(discovery, mapper)
agent = StreamingAgent()
entity_info = await discovery.create_entity_info_from_object(agent, source="test")
discovery.register_entity(entity_info.id, entity_info, agent)
# Execute streaming agent (use metadata.entity_id for routing)
request = AgentFrameworkRequest(
metadata={"entity_id": entity_info.id},
input="hello",
stream=True, # DevUI always streams
)
events = []
async for event in executor.execute_streaming(request):
events.append(event)
# Should get events from streaming agent
assert len(events) > 0
text_events = [e for e in events if hasattr(e, "type") and e.type == "response.output_text.delta"]
assert len(text_events) > 0
assert "Processed: hello" in text_events[0].delta
# =============================================================================
# Full Pipeline Tests for SequentialBuilder
# =============================================================================
@pytest.mark.asyncio
async def test_full_pipeline_sequential_workflow(sequential_workflow):
"""Test SequentialBuilder workflow full pipeline with JSON serialization.
Uses the shared sequential_workflow fixture (Writer → Reviewer) from conftest.
Tests that all events can be JSON serialized for SSE streaming.
"""
executor, entity_id, mock_client, _workflow = sequential_workflow
request = AgentFrameworkRequest(
metadata={"entity_id": entity_id},
input="Write about testing best practices",
stream=True,
)
events = []
serialization_errors = []
async for event in executor.execute_streaming(request):
events.append(event)
event_type = getattr(event, "type", "unknown")
# Verify JSON serialization (exactly what server does for SSE)
try:
if hasattr(event, "model_dump_json"):
json_str = event.model_dump_json()
assert json_str is not None
except Exception as e:
serialization_errors.append(f"Event type={event_type}: {e}")
assert len(events) > 0, "Should receive events from sequential workflow"
assert len(serialization_errors) == 0, f"Serialization errors: {serialization_errors}"
assert mock_client.call_count >= 2, f"Expected both agents called, got {mock_client.call_count}"
@pytest.mark.asyncio
async def test_full_pipeline_concurrent_workflow(concurrent_workflow):
"""Test ConcurrentBuilder workflow full pipeline with JSON serialization.
Uses the shared concurrent_workflow fixture (Researcher | Analyst | Summarizer) from conftest.
Tests fan-out/fan-in pattern with parallel agent execution.
"""
executor, entity_id, mock_client, _workflow = concurrent_workflow
request = AgentFrameworkRequest(
metadata={"entity_id": entity_id},
input="Analyze market trends for Q4",
stream=True,
)
events = []
serialization_errors = []
async for event in executor.execute_streaming(request):
events.append(event)
event_type = getattr(event, "type", "unknown")
# Verify JSON serialization
try:
if hasattr(event, "model_dump_json"):
json_str = event.model_dump_json()
assert json_str is not None
except Exception as e:
serialization_errors.append(f"Event type={event_type}: {e}")
assert len(events) > 0, "Should receive events from concurrent workflow"
assert len(serialization_errors) == 0, f"Serialization errors: {serialization_errors}"
assert mock_client.call_count >= 3, f"Expected all 3 agents called, got {mock_client.call_count}"
# =============================================================================
# Full Pipeline Test for Workflow with Output Events
# =============================================================================
@pytest.mark.asyncio
async def test_full_pipeline_workflow_output_event_serialization():
"""Test that WorkflowOutputEvent from ctx.yield_output() serializes correctly.
This tests the pattern where executors yield output via ctx.yield_output(),
which emits WorkflowOutputEvent that DevUI must serialize for SSE.
"""
from agent_framework import Executor, WorkflowBuilder, WorkflowContext, handler
class OutputtingExecutor(Executor):
"""Executor that yields multiple outputs."""
@handler
async def process(self, input_text: str, ctx: WorkflowContext[Any, Any]) -> None:
await ctx.yield_output(f"First output: {input_text}")
await ctx.yield_output("Second output: processed")
await ctx.yield_output({"final": "result", "data": [1, 2, 3]})
# Build workflow
workflow = (
WorkflowBuilder(name="Output Workflow", description="Tests yield_output")
.set_start_executor(OutputtingExecutor(id="outputter"))
.build()
)
# Create DevUI executor and register workflow
discovery = EntityDiscovery(None)
mapper = MessageMapper()
executor = AgentFrameworkExecutor(discovery, mapper)
entity_info = await discovery.create_entity_info_from_object(workflow, entity_type="workflow", source="test")
discovery.register_entity(entity_info.id, entity_info, workflow)
# Execute with streaming
request = AgentFrameworkRequest(
metadata={"entity_id": entity_info.id},
input="Test output events",
stream=True,
)
events = []
output_events = []
serialization_errors = []
async for event in executor.execute_streaming(request):
events.append(event)
event_type = getattr(event, "type", "")
# Track output item events
if "output_item" in event_type:
output_events.append(event)
try:
if hasattr(event, "model_dump_json"):
event.model_dump_json()
except Exception as e:
serialization_errors.append(f"Event type={event_type}: {e}")
assert len(events) > 0, "Should receive events"
assert len(serialization_errors) == 0, f"Serialization errors: {serialization_errors}"
# Should have received output events for the yield_output calls
assert len(output_events) >= 3, f"Expected 3+ output events for yield_output calls, got {len(output_events)}"
if __name__ == "__main__":
# Simple test runner
async def run_tests():
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Create test agent
agent_file = temp_path / "streaming_agent.py"
agent_file.write_text("""
class StreamingAgent:
name = "Streaming Test Agent"
description = "Test agent for streaming"
async def run(self, input_str, *, stream: bool = False, thread=None, **kwargs):
if stream:
async def _stream():
for i, word in enumerate(f"Processing {input_str}".split()):
yield f"word_{i}: {word} "
return _stream()
return f"Processing {input_str}"
""")
discovery = EntityDiscovery(str(temp_path))
mapper = MessageMapper()
executor = AgentFrameworkExecutor(discovery, mapper)
# Test discovery
entities = await executor.discover_entities()
if entities:
# Test sync execution (use metadata.entity_id for routing)
request = AgentFrameworkRequest(
metadata={"entity_id": entities[0].id},
input="test input",
stream=False,
)
await executor.execute_sync(request)
# Test streaming execution
request.stream = True
event_count = 0
async for _event in executor.execute_streaming(request):
event_count += 1
if event_count > 5: # Limit for testing
break
asyncio.run(run_tests())