mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: [Breaking] Simplified Content types to a single class with classmethod constructors. (#3252)
* ported Content to a new model * fixed linting * fixes * fixed data format handling * fix for 3.10 mypy * fix * fix int test
This commit is contained in:
committed by
GitHub
Unverified
parent
73761aa4a3
commit
83e6229c11
@@ -321,7 +321,7 @@ class InMemoryConversationStore(ConversationStore):
|
||||
# Convert ChatMessage contents to OpenAI TextContent format
|
||||
message_content = []
|
||||
for content_item in msg.contents:
|
||||
if hasattr(content_item, "type") and content_item.type == "text":
|
||||
if content_item.type == "text":
|
||||
# Extract text from TextContent object
|
||||
text_value = getattr(content_item, "text", "")
|
||||
message_content.append(TextContent(type="text", text=text_value))
|
||||
|
||||
@@ -7,7 +7,7 @@ import logging
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
|
||||
from agent_framework import AgentProtocol
|
||||
from agent_framework import AgentProtocol, Content
|
||||
from agent_framework._workflows._events import RequestInfoEvent
|
||||
|
||||
from ._conversations import ConversationStore, InMemoryConversationStore
|
||||
@@ -602,7 +602,7 @@ class AgentFrameworkExecutor:
|
||||
"""
|
||||
# Import Agent Framework types
|
||||
try:
|
||||
from agent_framework import ChatMessage, DataContent, Role, TextContent
|
||||
from agent_framework import ChatMessage, Role
|
||||
except ImportError:
|
||||
# Fallback to string extraction if Agent Framework not available
|
||||
return self._extract_user_message_fallback(input_data)
|
||||
@@ -613,14 +613,12 @@ class AgentFrameworkExecutor:
|
||||
|
||||
# Handle OpenAI ResponseInputParam (List[ResponseInputItemParam])
|
||||
if isinstance(input_data, list):
|
||||
return self._convert_openai_input_to_chat_message(input_data, ChatMessage, TextContent, DataContent, Role)
|
||||
return self._convert_openai_input_to_chat_message(input_data, ChatMessage, Role)
|
||||
|
||||
# Fallback for other formats
|
||||
return self._extract_user_message_fallback(input_data)
|
||||
|
||||
def _convert_openai_input_to_chat_message(
|
||||
self, input_items: list[Any], ChatMessage: Any, TextContent: Any, DataContent: Any, Role: Any
|
||||
) -> Any:
|
||||
def _convert_openai_input_to_chat_message(self, input_items: list[Any], ChatMessage: Any, Role: Any) -> Any:
|
||||
"""Convert OpenAI ResponseInputParam to Agent Framework ChatMessage.
|
||||
|
||||
Processes text, images, files, and other content types from OpenAI format
|
||||
@@ -629,14 +627,12 @@ class AgentFrameworkExecutor:
|
||||
Args:
|
||||
input_items: List of OpenAI ResponseInputItemParam objects (dicts or objects)
|
||||
ChatMessage: ChatMessage class for creating chat messages
|
||||
TextContent: TextContent class for text content
|
||||
DataContent: DataContent class for data/media content
|
||||
Role: Role enum for message roles
|
||||
|
||||
Returns:
|
||||
ChatMessage with converted content
|
||||
"""
|
||||
contents = []
|
||||
contents: list[Content] = []
|
||||
|
||||
# Process each input item
|
||||
for item in input_items:
|
||||
@@ -649,7 +645,7 @@ class AgentFrameworkExecutor:
|
||||
|
||||
# Handle both string content and list content
|
||||
if isinstance(message_content, str):
|
||||
contents.append(TextContent(text=message_content))
|
||||
contents.append(Content.from_text(text=message_content))
|
||||
elif isinstance(message_content, list):
|
||||
for content_item in message_content:
|
||||
# Handle dict content items
|
||||
@@ -658,7 +654,7 @@ class AgentFrameworkExecutor:
|
||||
|
||||
if content_type == "input_text":
|
||||
text = content_item.get("text", "")
|
||||
contents.append(TextContent(text=text))
|
||||
contents.append(Content.from_text(text=text))
|
||||
|
||||
elif content_type == "input_image":
|
||||
image_url = content_item.get("image_url", "")
|
||||
@@ -676,7 +672,7 @@ class AgentFrameworkExecutor:
|
||||
media_type = "image/png"
|
||||
else:
|
||||
media_type = "image/png"
|
||||
contents.append(DataContent(uri=image_url, media_type=media_type))
|
||||
contents.append(Content.from_uri(uri=image_url, media_type=media_type))
|
||||
|
||||
elif content_type == "input_file":
|
||||
# Handle file input
|
||||
@@ -710,7 +706,7 @@ class AgentFrameworkExecutor:
|
||||
# Assume file_data is base64, create data URI
|
||||
data_uri = f"data:{media_type};base64,{file_data}"
|
||||
contents.append(
|
||||
DataContent(
|
||||
Content.from_uri(
|
||||
uri=data_uri,
|
||||
media_type=media_type,
|
||||
additional_properties=additional_props,
|
||||
@@ -718,7 +714,7 @@ class AgentFrameworkExecutor:
|
||||
)
|
||||
elif file_url:
|
||||
contents.append(
|
||||
DataContent(
|
||||
Content.from_uri(
|
||||
uri=file_url,
|
||||
media_type=media_type,
|
||||
additional_properties=additional_props,
|
||||
@@ -728,21 +724,19 @@ class AgentFrameworkExecutor:
|
||||
elif content_type == "function_approval_response":
|
||||
# Handle function approval response (DevUI extension)
|
||||
try:
|
||||
from agent_framework import FunctionApprovalResponseContent, FunctionCallContent
|
||||
|
||||
request_id = content_item.get("request_id", "")
|
||||
approved = content_item.get("approved", False)
|
||||
function_call_data = content_item.get("function_call", {})
|
||||
|
||||
# Create FunctionCallContent from the function_call data
|
||||
function_call = FunctionCallContent(
|
||||
function_call = Content.from_function_call(
|
||||
call_id=function_call_data.get("id", ""),
|
||||
name=function_call_data.get("name", ""),
|
||||
arguments=function_call_data.get("arguments", {}),
|
||||
)
|
||||
|
||||
# Create FunctionApprovalResponseContent with correct signature
|
||||
approval_response = FunctionApprovalResponseContent(
|
||||
approval_response = Content.from_function_approval_response(
|
||||
approved, # positional argument
|
||||
id=request_id, # keyword argument 'id', NOT 'request_id'
|
||||
function_call=function_call, # FunctionCallContent object
|
||||
@@ -764,7 +758,7 @@ class AgentFrameworkExecutor:
|
||||
|
||||
# If no contents found, create a simple text message
|
||||
if not contents:
|
||||
contents.append(TextContent(text=""))
|
||||
contents.append(Content.from_text(text=""))
|
||||
|
||||
chat_message = ChatMessage(role=Role.USER, contents=contents)
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ from datetime import datetime
|
||||
from typing import Any, Union
|
||||
from uuid import uuid4
|
||||
|
||||
from agent_framework import ChatMessage, TextContent
|
||||
from agent_framework import ChatMessage, Content
|
||||
from openai.types.responses import (
|
||||
Response,
|
||||
ResponseContentPartAddedEvent,
|
||||
@@ -92,7 +92,7 @@ def _serialize_content_recursive(value: Any) -> Any:
|
||||
if isinstance(value, (list, tuple)):
|
||||
serialized = [_serialize_content_recursive(item) for item in value]
|
||||
# For single-item lists containing text Content, extract just the text
|
||||
# This handles the MCP case where result = [TextContent(text="Hello")]
|
||||
# This handles the MCP case where result = [Content.from_text(text="Hello")]
|
||||
# and we want output = "Hello" not output = '[{"type": "text", "text": "Hello"}]'
|
||||
if len(serialized) == 1 and isinstance(serialized[0], dict) and serialized[0].get("type") == "text":
|
||||
return serialized[0].get("text", "")
|
||||
@@ -127,18 +127,18 @@ class MessageMapper:
|
||||
|
||||
# Register content type mappers for all 12 Agent Framework content types
|
||||
self.content_mappers = {
|
||||
"TextContent": self._map_text_content,
|
||||
"TextReasoningContent": self._map_reasoning_content,
|
||||
"FunctionCallContent": self._map_function_call_content,
|
||||
"FunctionResultContent": self._map_function_result_content,
|
||||
"ErrorContent": self._map_error_content,
|
||||
"UsageContent": self._map_usage_content,
|
||||
"DataContent": self._map_data_content,
|
||||
"UriContent": self._map_uri_content,
|
||||
"HostedFileContent": self._map_hosted_file_content,
|
||||
"HostedVectorStoreContent": self._map_hosted_vector_store_content,
|
||||
"FunctionApprovalRequestContent": self._map_approval_request_content,
|
||||
"FunctionApprovalResponseContent": self._map_approval_response_content,
|
||||
"text": self._map_text_content,
|
||||
"text_reasoning": self._map_reasoning_content,
|
||||
"function_call": self._map_function_call_content,
|
||||
"function_result": self._map_function_result_content,
|
||||
"error": self._map_error_content,
|
||||
"usage": self._map_usage_content,
|
||||
"data": self._map_data_content,
|
||||
"uri": self._map_uri_content,
|
||||
"hosted_file": self._map_hosted_file_content,
|
||||
"hosted_vector_store": self._map_hosted_vector_store_content,
|
||||
"function_approval_request": self._map_approval_request_content,
|
||||
"function_approval_response": self._map_approval_response_content,
|
||||
}
|
||||
|
||||
async def convert_event(self, raw_event: Any, request: AgentFrameworkRequest) -> Sequence[Any]:
|
||||
@@ -603,7 +603,7 @@ class MessageMapper:
|
||||
return events
|
||||
|
||||
# Check if we're streaming text content
|
||||
has_text_content = any(isinstance(content, TextContent) for content in update.contents)
|
||||
has_text_content = any(content.type == "text" for content in update.contents)
|
||||
|
||||
# Check if we're in an executor context with an existing item
|
||||
executor_id = context.get("current_executor_id")
|
||||
@@ -647,10 +647,8 @@ class MessageMapper:
|
||||
|
||||
# Process each content item
|
||||
for content in update.contents:
|
||||
content_type = content.__class__.__name__
|
||||
|
||||
# Special handling for TextContent to use proper delta events
|
||||
if content_type == "TextContent" and "current_message_id" in context:
|
||||
if content.type == "text" and "current_message_id" in context:
|
||||
# Stream text content via proper delta events
|
||||
events.append(
|
||||
ResponseTextDeltaEvent(
|
||||
@@ -663,9 +661,9 @@ class MessageMapper:
|
||||
sequence_number=self._next_sequence(context),
|
||||
)
|
||||
)
|
||||
elif content_type in self.content_mappers:
|
||||
elif content.type in self.content_mappers:
|
||||
# Use existing mappers for other content types
|
||||
mapped_events = await self.content_mappers[content_type](content, context)
|
||||
mapped_events = await self.content_mappers[content.type](content, context)
|
||||
if mapped_events is not None: # Handle None returns (e.g., UsageContent)
|
||||
if isinstance(mapped_events, list):
|
||||
events.extend(mapped_events)
|
||||
@@ -676,7 +674,7 @@ class MessageMapper:
|
||||
events.append(await self._create_unknown_content_event(content, context))
|
||||
|
||||
# Don't increment content_index for text deltas within the same part
|
||||
if content_type != "TextContent":
|
||||
if content.type != "text":
|
||||
context["content_index"] = context.get("content_index", 0) + 1
|
||||
|
||||
except Exception as e:
|
||||
@@ -708,10 +706,8 @@ class MessageMapper:
|
||||
for message in messages:
|
||||
if hasattr(message, "contents") and message.contents:
|
||||
for content in message.contents:
|
||||
content_type = content.__class__.__name__
|
||||
|
||||
if content_type in self.content_mappers:
|
||||
mapped_events = await self.content_mappers[content_type](content, context)
|
||||
if content.type in self.content_mappers:
|
||||
mapped_events = await self.content_mappers[content.type](content, context)
|
||||
if mapped_events is not None: # Handle None returns (e.g., UsageContent)
|
||||
if isinstance(mapped_events, list):
|
||||
events.extend(mapped_events)
|
||||
@@ -726,9 +722,7 @@ class MessageMapper:
|
||||
# Add usage information if present
|
||||
usage_details = getattr(response, "usage_details", None)
|
||||
if usage_details:
|
||||
from agent_framework import UsageContent
|
||||
|
||||
usage_content = UsageContent(details=usage_details)
|
||||
usage_content = Content.from_usage(usage_details=usage_details)
|
||||
await self._map_usage_content(usage_content, context)
|
||||
# Note: _map_usage_content returns None - it accumulates usage for final Response.usage
|
||||
|
||||
@@ -1421,11 +1415,11 @@ class MessageMapper:
|
||||
Returns:
|
||||
None - no event emitted (usage goes in final Response.usage)
|
||||
"""
|
||||
# Extract usage from UsageContent.details (UsageDetails object)
|
||||
details = getattr(content, "details", None)
|
||||
total_tokens = getattr(details, "total_token_count", 0) or 0
|
||||
prompt_tokens = getattr(details, "input_token_count", 0) or 0
|
||||
completion_tokens = getattr(details, "output_token_count", 0) or 0
|
||||
# Extract usage from UsageContent.usage_details (UsageDetails object)
|
||||
details = content.usage_details or {}
|
||||
total_tokens = details.get("total_token_count", 0)
|
||||
prompt_tokens = details.get("input_token_count", 0)
|
||||
completion_tokens = details.get("output_token_count", 0)
|
||||
|
||||
# Accumulate for final Response.usage
|
||||
request_id = context.get("request_id", "default")
|
||||
|
||||
@@ -187,7 +187,7 @@ export interface HostedVectorStoreContent extends BaseContent {
|
||||
}
|
||||
|
||||
// Union type for all content
|
||||
export type Contents =
|
||||
export type Content =
|
||||
| TextContent
|
||||
| FunctionCallContent
|
||||
| FunctionResultContent
|
||||
@@ -209,7 +209,7 @@ export interface UsageDetails {
|
||||
|
||||
// Agent run response update (streaming)
|
||||
export interface AgentResponseUpdate {
|
||||
contents: Contents[];
|
||||
contents: Content[];
|
||||
role?: Role;
|
||||
author_name?: string;
|
||||
response_id?: string;
|
||||
@@ -233,7 +233,7 @@ export interface AgentResponse {
|
||||
|
||||
// Chat message
|
||||
export interface ChatMessage {
|
||||
contents: Contents[];
|
||||
contents: Content[];
|
||||
role?: Role;
|
||||
author_name?: string;
|
||||
message_id?: string;
|
||||
@@ -244,7 +244,7 @@ export interface ChatMessage {
|
||||
|
||||
// Chat response update (model client streaming)
|
||||
export interface ChatResponseUpdate {
|
||||
contents: Contents[];
|
||||
contents: Content[];
|
||||
role?: Role;
|
||||
author_name?: string;
|
||||
response_id?: string;
|
||||
@@ -330,18 +330,18 @@ export interface TraceSpan {
|
||||
}
|
||||
|
||||
// Helper type guards for Agent Framework content types
|
||||
export function isTextContent(content: Contents): content is TextContent {
|
||||
export function isTextContent(content: Content): content is TextContent {
|
||||
return content.type === "text";
|
||||
}
|
||||
|
||||
export function isFunctionCallContent(
|
||||
content: Contents
|
||||
content: Content
|
||||
): content is FunctionCallContent {
|
||||
return content.type === "function_call";
|
||||
}
|
||||
|
||||
export function isFunctionResultContent(
|
||||
content: Contents
|
||||
content: Content
|
||||
): content is FunctionResultContent {
|
||||
return content.type === "function_result";
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ export interface MetaResponse {
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
role: "user" | "assistant" | "system" | "tool";
|
||||
contents: import("./agent-framework").Contents[];
|
||||
contents: import("./agent-framework").Content[];
|
||||
timestamp: string;
|
||||
streaming?: boolean;
|
||||
author_name?: string;
|
||||
|
||||
@@ -7,7 +7,7 @@ import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from agent_framework import AgentResponse, ChatMessage, Role, TextContent
|
||||
from agent_framework import AgentResponse, ChatMessage, Content, Role
|
||||
|
||||
from agent_framework_devui import register_cleanup
|
||||
from agent_framework_devui._discovery import EntityDiscovery
|
||||
@@ -36,7 +36,7 @@ class MockAgent:
|
||||
async def run_stream(self, messages=None, *, thread=None, **kwargs):
|
||||
"""Mock streaming run method."""
|
||||
yield AgentResponse(
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, contents=[TextContent(text="Test response")])],
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Test response")])],
|
||||
)
|
||||
|
||||
|
||||
@@ -259,7 +259,7 @@ async def test_cleanup_with_file_based_discovery():
|
||||
# Write agent module with cleanup registration
|
||||
agent_file = agent_dir / "__init__.py"
|
||||
agent_file.write_text("""
|
||||
from agent_framework import AgentResponse, ChatMessage, Role, TextContent
|
||||
from agent_framework import AgentResponse, ChatMessage, Role, Content
|
||||
from agent_framework_devui import register_cleanup
|
||||
|
||||
class MockCredential:
|
||||
@@ -279,7 +279,7 @@ class TestAgent:
|
||||
|
||||
async def run_stream(self, messages=None, *, thread=None, **kwargs):
|
||||
yield AgentResponse(
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, content=[TextContent(text="Test")])],
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, content=[Content.from_text(text="Test")])],
|
||||
inner_messages=[],
|
||||
)
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ async def test_discovery_accepts_agents_with_only_run():
|
||||
|
||||
init_file = agent_dir / "__init__.py"
|
||||
init_file.write_text("""
|
||||
from agent_framework import AgentResponse, AgentThread, ChatMessage, Role, TextContent
|
||||
from agent_framework import AgentResponse, AgentThread, ChatMessage, Role, Content
|
||||
|
||||
class NonStreamingAgent:
|
||||
id = "non_streaming"
|
||||
@@ -95,7 +95,7 @@ class NonStreamingAgent:
|
||||
return AgentResponse(
|
||||
messages=[ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
contents=[TextContent(text="response")]
|
||||
contents=[Content.from_text(text="response")]
|
||||
)],
|
||||
response_id="test"
|
||||
)
|
||||
@@ -210,7 +210,7 @@ class TestAgent:
|
||||
|
||||
async def run(self, messages=None, *, thread=None, **kwargs):
|
||||
return AgentResponse(
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, contents=[TextContent(text="test")])],
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="test")])],
|
||||
response_id="test"
|
||||
)
|
||||
|
||||
|
||||
@@ -566,7 +566,7 @@ def test_extract_workflow_hil_responses_handles_stringified_json():
|
||||
|
||||
async def test_executor_handles_non_streaming_agent():
|
||||
"""Test executor can handle agents with only run() method (no run_stream)."""
|
||||
from agent_framework import AgentResponse, AgentThread, ChatMessage, Role, TextContent
|
||||
from agent_framework import AgentResponse, AgentThread, ChatMessage, Content, Role
|
||||
|
||||
class NonStreamingAgent:
|
||||
"""Agent with only run() method - does NOT satisfy full AgentProtocol."""
|
||||
@@ -577,7 +577,9 @@ async def test_executor_handles_non_streaming_agent():
|
||||
|
||||
async def run(self, messages=None, *, thread=None, **kwargs):
|
||||
return AgentResponse(
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, contents=[TextContent(text=f"Processed: {messages}")])],
|
||||
messages=[
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text=f"Processed: {messages}")])
|
||||
],
|
||||
response_id="test_123",
|
||||
)
|
||||
|
||||
|
||||
@@ -28,11 +28,9 @@ from agent_framework import (
|
||||
ChatResponse,
|
||||
ChatResponseUpdate,
|
||||
ConcurrentBuilder,
|
||||
FunctionCallContent,
|
||||
FunctionResultContent,
|
||||
Content,
|
||||
Role,
|
||||
SequentialBuilder,
|
||||
TextContent,
|
||||
use_chat_middleware,
|
||||
)
|
||||
from agent_framework._clients import TOptions_co
|
||||
@@ -93,7 +91,7 @@ class MockChatClient:
|
||||
for update in self.streaming_responses.pop(0):
|
||||
yield update
|
||||
else:
|
||||
yield ChatResponseUpdate(text=TextContent(text="test streaming response"), role="assistant")
|
||||
yield ChatResponseUpdate(text=Content.from_text(text="test streaming response"), role="assistant")
|
||||
|
||||
|
||||
@use_chat_middleware
|
||||
@@ -141,10 +139,10 @@ class MockBaseChatClient(BaseChatClient[TOptions_co], Generic[TOptions_co]):
|
||||
yield update
|
||||
else:
|
||||
# Simulate realistic streaming chunks
|
||||
yield ChatResponseUpdate(text=TextContent(text="Mock "), role="assistant")
|
||||
yield ChatResponseUpdate(text=TextContent(text="streaming "), role="assistant")
|
||||
yield ChatResponseUpdate(text=TextContent(text="response "), role="assistant")
|
||||
yield ChatResponseUpdate(text=TextContent(text="from ChatAgent"), role="assistant")
|
||||
yield ChatResponseUpdate(text=Content.from_text(text="Mock "), role="assistant")
|
||||
yield ChatResponseUpdate(text=Content.from_text(text="streaming "), role="assistant")
|
||||
yield ChatResponseUpdate(text=Content.from_text(text="response "), role="assistant")
|
||||
yield ChatResponseUpdate(text=Content.from_text(text="from ChatAgent"), role="assistant")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
@@ -175,7 +173,7 @@ class MockAgent(BaseAgent):
|
||||
) -> AgentResponse:
|
||||
self.call_count += 1
|
||||
return AgentResponse(
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, contents=[TextContent(text=self.response_text)])]
|
||||
messages=[ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text=self.response_text)])]
|
||||
)
|
||||
|
||||
async def run_stream(
|
||||
@@ -187,7 +185,7 @@ class MockAgent(BaseAgent):
|
||||
) -> AsyncIterable[AgentResponseUpdate]:
|
||||
self.call_count += 1
|
||||
for chunk in self.streaming_chunks:
|
||||
yield AgentResponseUpdate(contents=[TextContent(text=chunk)], role=Role.ASSISTANT)
|
||||
yield AgentResponseUpdate(contents=[Content.from_text(text=chunk)], role=Role.ASSISTANT)
|
||||
|
||||
|
||||
class MockToolCallingAgent(BaseAgent):
|
||||
@@ -217,13 +215,13 @@ class MockToolCallingAgent(BaseAgent):
|
||||
self.call_count += 1
|
||||
# First: text
|
||||
yield AgentResponseUpdate(
|
||||
contents=[TextContent(text="Let me search for that...")],
|
||||
contents=[Content.from_text(text="Let me search for that...")],
|
||||
role=Role.ASSISTANT,
|
||||
)
|
||||
# Second: tool call
|
||||
yield AgentResponseUpdate(
|
||||
contents=[
|
||||
FunctionCallContent(
|
||||
Content.from_function_call(
|
||||
call_id="call_123",
|
||||
name="search",
|
||||
arguments={"query": "weather"},
|
||||
@@ -234,7 +232,7 @@ class MockToolCallingAgent(BaseAgent):
|
||||
# Third: tool result
|
||||
yield AgentResponseUpdate(
|
||||
contents=[
|
||||
FunctionResultContent(
|
||||
Content.from_function_result(
|
||||
call_id="call_123",
|
||||
result={"temperature": 72, "condition": "sunny"},
|
||||
)
|
||||
@@ -243,7 +241,7 @@ class MockToolCallingAgent(BaseAgent):
|
||||
)
|
||||
# Fourth: final text
|
||||
yield AgentResponseUpdate(
|
||||
contents=[TextContent(text="The weather is sunny, 72°F.")],
|
||||
contents=[Content.from_text(text="The weather is sunny, 72°F.")],
|
||||
role=Role.ASSISTANT,
|
||||
)
|
||||
|
||||
@@ -297,7 +295,7 @@ def create_mock_tool_agent(id: str = "tool_agent", name: str = "ToolAgent") -> M
|
||||
|
||||
def create_agent_run_response(text: str = "Test response") -> AgentResponse:
|
||||
"""Create an AgentResponse with the given text."""
|
||||
return AgentResponse(messages=[ChatMessage(role=Role.ASSISTANT, contents=[TextContent(text=text)])])
|
||||
return AgentResponse(messages=[ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text=text)])])
|
||||
|
||||
|
||||
def create_agent_executor_response(
|
||||
@@ -310,8 +308,8 @@ def create_agent_executor_response(
|
||||
executor_id=executor_id,
|
||||
agent_response=agent_response,
|
||||
full_conversation=[
|
||||
ChatMessage(role=Role.USER, contents=[TextContent(text="User input")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[TextContent(text=response_text)]),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="User input")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text=response_text)]),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -14,11 +14,8 @@ import pytest
|
||||
# Import Agent Framework types
|
||||
from agent_framework._types import (
|
||||
AgentResponseUpdate,
|
||||
ErrorContent,
|
||||
FunctionCallContent,
|
||||
FunctionResultContent,
|
||||
Content,
|
||||
Role,
|
||||
TextContent,
|
||||
)
|
||||
|
||||
# Import real workflow event classes - NOT mocks!
|
||||
@@ -71,15 +68,17 @@ def test_request() -> AgentFrameworkRequest:
|
||||
def create_test_content(content_type: str, **kwargs: Any) -> Any:
|
||||
"""Create test content objects."""
|
||||
if content_type == "text":
|
||||
return TextContent(text=kwargs.get("text", "Hello, world!"))
|
||||
return Content.from_text(text=kwargs.get("text", "Hello, world!"))
|
||||
if content_type == "function_call":
|
||||
return FunctionCallContent(
|
||||
return Content.from_function_call(
|
||||
call_id=kwargs.get("call_id", "test_call_id"),
|
||||
name=kwargs.get("name", "test_func"),
|
||||
arguments=kwargs.get("arguments", {"param": "value"}),
|
||||
)
|
||||
if content_type == "error":
|
||||
return ErrorContent(message=kwargs.get("message", "Test error"), error_code=kwargs.get("code", "test_error"))
|
||||
return Content.from_error(
|
||||
message=kwargs.get("message", "Test error"), error_code=kwargs.get("code", "test_error")
|
||||
)
|
||||
raise ValueError(f"Unknown content type: {content_type}")
|
||||
|
||||
|
||||
@@ -162,7 +161,7 @@ async def test_function_result_content_with_string_result(
|
||||
mapper: MessageMapper, test_request: AgentFrameworkRequest
|
||||
) -> None:
|
||||
"""Test FunctionResultContent with plain string result (regular tools)."""
|
||||
content = FunctionResultContent(
|
||||
content = Content.from_function_result(
|
||||
call_id="test_call_123",
|
||||
result="Hello, World!",
|
||||
)
|
||||
@@ -182,9 +181,9 @@ async def test_function_result_content_with_nested_content_objects(
|
||||
mapper: MessageMapper, test_request: AgentFrameworkRequest
|
||||
) -> None:
|
||||
"""Test FunctionResultContent with nested Content objects (MCP tools case)."""
|
||||
content = FunctionResultContent(
|
||||
content = Content.from_function_result(
|
||||
call_id="mcp_call_456",
|
||||
result=[TextContent(text="Hello from MCP!")],
|
||||
result=[Content.from_text(text="Hello from MCP!")],
|
||||
)
|
||||
update = create_test_agent_update([content])
|
||||
|
||||
@@ -451,12 +450,12 @@ async def test_magentic_agent_run_update_event_with_agent_delta_metadata(
|
||||
This tests the ACTUAL event format Magentic emits - not a fake MagenticAgentDeltaEvent class.
|
||||
Magentic uses AgentRunUpdateEvent with additional_properties containing magentic_event_type.
|
||||
"""
|
||||
from agent_framework._types import AgentResponseUpdate, Role, TextContent
|
||||
from agent_framework._types import AgentResponseUpdate, Role
|
||||
from agent_framework._workflows._events import AgentRunUpdateEvent
|
||||
|
||||
# Create the REAL event format that Magentic emits
|
||||
update = AgentResponseUpdate(
|
||||
contents=[TextContent(text="Hello from agent")],
|
||||
contents=[Content.from_text(text="Hello from agent")],
|
||||
role=Role.ASSISTANT,
|
||||
author_name="Writer",
|
||||
additional_properties={
|
||||
@@ -482,12 +481,12 @@ async def test_magentic_orchestrator_message_event(mapper: MessageMapper, test_r
|
||||
Magentic emits orchestrator planning/instruction messages using AgentRunUpdateEvent
|
||||
with additional_properties containing magentic_event_type='orchestrator_message'.
|
||||
"""
|
||||
from agent_framework._types import AgentResponseUpdate, Role, TextContent
|
||||
from agent_framework._types import AgentResponseUpdate, Role
|
||||
from agent_framework._workflows._events import AgentRunUpdateEvent
|
||||
|
||||
# Create orchestrator message event (REAL format from Magentic)
|
||||
update = AgentResponseUpdate(
|
||||
contents=[TextContent(text="Planning: First, the writer will create content...")],
|
||||
contents=[Content.from_text(text="Planning: First, the writer will create content...")],
|
||||
role=Role.ASSISTANT,
|
||||
author_name="Orchestrator",
|
||||
additional_properties={
|
||||
@@ -518,20 +517,20 @@ async def test_magentic_events_use_same_event_class_as_other_workflows(
|
||||
additional_properties. Any mapper code checking for 'MagenticAgentDeltaEvent'
|
||||
class names is dead code.
|
||||
"""
|
||||
from agent_framework._types import AgentResponseUpdate, Role, TextContent
|
||||
from agent_framework._types import AgentResponseUpdate, Role
|
||||
from agent_framework._workflows._events import AgentRunUpdateEvent
|
||||
|
||||
# Create events the way different workflows do it
|
||||
# 1. Regular workflow (no additional_properties)
|
||||
regular_update = AgentResponseUpdate(
|
||||
contents=[TextContent(text="Regular workflow response")],
|
||||
contents=[Content.from_text(text="Regular workflow response")],
|
||||
role=Role.ASSISTANT,
|
||||
)
|
||||
regular_event = AgentRunUpdateEvent(executor_id="regular_executor", data=regular_update)
|
||||
|
||||
# 2. Magentic workflow (with additional_properties)
|
||||
magentic_update = AgentResponseUpdate(
|
||||
contents=[TextContent(text="Magentic workflow response")],
|
||||
contents=[Content.from_text(text="Magentic workflow response")],
|
||||
role=Role.ASSISTANT,
|
||||
additional_properties={"magentic_event_type": "agent_delta"},
|
||||
)
|
||||
@@ -599,13 +598,13 @@ async def test_workflow_output_event(mapper: MessageMapper, test_request: AgentF
|
||||
|
||||
async def test_workflow_output_event_with_list_data(mapper: MessageMapper, test_request: AgentFrameworkRequest) -> None:
|
||||
"""Test WorkflowOutputEvent with list data (common for sequential/concurrent workflows)."""
|
||||
from agent_framework import ChatMessage, Role, TextContent
|
||||
from agent_framework import ChatMessage, Role
|
||||
from agent_framework._workflows._events import WorkflowOutputEvent
|
||||
|
||||
# Sequential/Concurrent workflows often output list[ChatMessage]
|
||||
messages = [
|
||||
ChatMessage(role=Role.USER, contents=[TextContent(text="Hello")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[TextContent(text="World")]),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="World")]),
|
||||
]
|
||||
event = WorkflowOutputEvent(data=messages, executor_id="complete")
|
||||
events = await mapper.convert_event(event, test_request)
|
||||
|
||||
@@ -49,7 +49,7 @@ class TestMultimodalWorkflowInput:
|
||||
|
||||
def test_convert_openai_input_to_chat_message_with_image(self):
|
||||
"""Test that OpenAI format with image is converted to ChatMessage with DataContent."""
|
||||
from agent_framework import ChatMessage, DataContent, Role, TextContent
|
||||
from agent_framework import ChatMessage, Role
|
||||
|
||||
discovery = MagicMock(spec=EntityDiscovery)
|
||||
mapper = MagicMock(spec=MessageMapper)
|
||||
@@ -78,11 +78,11 @@ class TestMultimodalWorkflowInput:
|
||||
assert len(result.contents) == 2, f"Expected 2 contents, got {len(result.contents)}"
|
||||
|
||||
# First content should be text
|
||||
assert isinstance(result.contents[0], TextContent)
|
||||
assert result.contents[0].type == "text"
|
||||
assert result.contents[0].text == "Describe this image"
|
||||
|
||||
# Second content should be image (DataContent)
|
||||
assert isinstance(result.contents[1], DataContent)
|
||||
assert result.contents[1].type == "data"
|
||||
assert result.contents[1].media_type == "image/png"
|
||||
assert result.contents[1].uri == TEST_IMAGE_DATA_URI
|
||||
|
||||
@@ -90,7 +90,7 @@ class TestMultimodalWorkflowInput:
|
||||
"""Test that _parse_workflow_input correctly handles JSON string with multimodal content."""
|
||||
import asyncio
|
||||
|
||||
from agent_framework import ChatMessage, DataContent, TextContent
|
||||
from agent_framework import ChatMessage
|
||||
|
||||
discovery = MagicMock(spec=EntityDiscovery)
|
||||
mapper = MagicMock(spec=MessageMapper)
|
||||
@@ -120,11 +120,11 @@ class TestMultimodalWorkflowInput:
|
||||
assert len(result.contents) == 2
|
||||
|
||||
# Verify text content
|
||||
assert isinstance(result.contents[0], TextContent)
|
||||
assert result.contents[0].type == "text"
|
||||
assert result.contents[0].text == "What is in this image?"
|
||||
|
||||
# Verify image content
|
||||
assert isinstance(result.contents[1], DataContent)
|
||||
assert result.contents[1].type == "data"
|
||||
assert result.contents[1].media_type == "image/png"
|
||||
|
||||
def test_parse_workflow_input_still_handles_simple_dict(self):
|
||||
|
||||
Reference in New Issue
Block a user