mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: [BREAKING] Types API Review improvements (#3647)
* Replace Role and FinishReason classes with NewType + Literal
- Remove EnumLike metaclass from _types.py
- Replace Role class with NewType('Role', str) + RoleLiteral
- Replace FinishReason class with NewType('FinishReason', str) + FinishReasonLiteral
- Update all usages across codebase to use string literals
- Remove .value access patterns (direct string comparison now works)
- Add backward compatibility for legacy dict serialization format
- Update tests to reflect new string-based types
Addresses #3591, #3615
* Simplify ChatResponse and AgentResponse type hints (#3592)
- Remove overloads from ChatResponse.__init__
- Remove text parameter from ChatResponse.__init__
- Remove | dict[str, Any] from finish_reason and usage_details params
- Remove **kwargs from AgentResponse.__init__
- Both now accept ChatMessage | Sequence[ChatMessage] | None for messages
- Update docstrings and examples to reflect changes
- Fix tests that were using removed kwargs
- Fix Role type hint usage in ag-ui utils
* Remove text parameter from ChatResponseUpdate and AgentResponseUpdate (#3597)
- Remove text parameter from ChatResponseUpdate.__init__
- Remove text parameter from AgentResponseUpdate.__init__
- Remove **kwargs from both update classes
- Simplify contents parameter type to Sequence[Content] | None
- Update all usages to use contents=[Content.from_text(...)] pattern
- Fix imports in test files
- Update docstrings and examples
* Rename from_chat_response_updates to from_updates (#3593)
- ChatResponse.from_chat_response_updates → ChatResponse.from_updates
- ChatResponse.from_chat_response_generator → ChatResponse.from_update_generator
- AgentResponse.from_agent_run_response_updates → AgentResponse.from_updates
* Remove try_parse_value method from ChatResponse and AgentResponse (#3595)
- Remove try_parse_value method from ChatResponse
- Remove try_parse_value method from AgentResponse
- Remove try_parse_value calls from from_updates and from_update_generator methods
- Update samples to use try/except with response.value instead
- Update tests to use response.value pattern
- Users should now use response.value with try/except for safe parsing
* Add agent_id to AgentResponse and clarify author_name documentation (#3596)
- Add agent_id parameter to AgentResponse class
- Document that author_name is on ChatMessage objects, not responses
- Update ChatResponse docstring with author_name note
- Update AgentResponse docstring with author_name note
* Simplify ChatMessage.__init__ signature (#3618)
- Make contents a positional argument accepting Sequence[Content | str]
- Auto-convert strings in contents to TextContent
- Remove overloads, keep text kwarg for backward compatibility with serialization
- Update _parse_content_list to handle string items
- Update all usages across codebase to use new format: ChatMessage("role", ["text"])
* Allow Content as input on run and get_response
- Update prepare_messages and normalize_messages to accept Content
- Update type signatures in _agents.py and _clients.py
- Add tests for Content input handling
* Fix ChatMessage usage across packages and samples
Update all remaining ChatMessage(role=..., text=...) to use new
ChatMessage('role', ['text']) signature.
* Fix Role string usage and response format parsing
- Fix redis provider: remove .value access on string literals
- Fix durabletask ensure_response_format: set _response_format before accessing .value
* Fix ollama .value and ai_model_id issues, handle None in content list
- Fix ollama _chat_client: remove .value on string literals
- Fix ollama _chat_client: rename ai_model_id to model_id
- Fix _parse_content_list: skip None values gracefully
* Fix A2AAgent type signature to include Content
* Fix Role/FinishReason NewType dict annotations and improve test coverage to 95%
* Fix mypy errors for Role/FinishReason NewType usage
* Fix Role.TOOL and Role.ASSISTANT usage in _orchestrator_helpers.py
* Fix Role NewType usage in durabletask _models.py
This commit is contained in:
committed by
GitHub
Unverified
parent
ef798629e5
commit
838a7fd61d
@@ -32,7 +32,6 @@ from agent_framework import (
|
||||
BaseAgent,
|
||||
ChatMessage,
|
||||
Content,
|
||||
Role,
|
||||
normalize_messages,
|
||||
prepend_agent_framework_to_user_agent,
|
||||
)
|
||||
@@ -187,7 +186,7 @@ class A2AAgent(BaseAgent):
|
||||
|
||||
async def run(
|
||||
self,
|
||||
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
|
||||
messages: str | Content | ChatMessage | Sequence[str | Content | ChatMessage] | None = None,
|
||||
*,
|
||||
thread: AgentThread | None = None,
|
||||
**kwargs: Any,
|
||||
@@ -210,11 +209,11 @@ class A2AAgent(BaseAgent):
|
||||
"""
|
||||
# Collect all updates and use framework to consolidate updates into response
|
||||
updates = [update async for update in self.run_stream(messages, thread=thread, **kwargs)]
|
||||
return AgentResponse.from_agent_run_response_updates(updates)
|
||||
return AgentResponse.from_updates(updates)
|
||||
|
||||
async def run_stream(
|
||||
self,
|
||||
messages: str | ChatMessage | Sequence[str | ChatMessage] | None = None,
|
||||
messages: str | Content | ChatMessage | Sequence[str | Content | ChatMessage] | None = None,
|
||||
*,
|
||||
thread: AgentThread | None = None,
|
||||
**kwargs: Any,
|
||||
@@ -245,7 +244,7 @@ class A2AAgent(BaseAgent):
|
||||
contents = self._parse_contents_from_a2a(item.parts)
|
||||
yield AgentResponseUpdate(
|
||||
contents=contents,
|
||||
role=Role.ASSISTANT if item.role == A2ARole.agent else Role.USER,
|
||||
role="assistant" if item.role == A2ARole.agent else "user",
|
||||
response_id=str(getattr(item, "message_id", uuid.uuid4())),
|
||||
raw_representation=item,
|
||||
)
|
||||
@@ -269,7 +268,7 @@ class A2AAgent(BaseAgent):
|
||||
# Empty task
|
||||
yield AgentResponseUpdate(
|
||||
contents=[],
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
response_id=task.id,
|
||||
raw_representation=task,
|
||||
)
|
||||
@@ -421,7 +420,7 @@ class A2AAgent(BaseAgent):
|
||||
contents = self._parse_contents_from_a2a(history_item.parts)
|
||||
messages.append(
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT if history_item.role == A2ARole.agent else Role.USER,
|
||||
role="assistant" if history_item.role == A2ARole.agent else "user",
|
||||
contents=contents,
|
||||
raw_representation=history_item,
|
||||
)
|
||||
@@ -433,7 +432,7 @@ class A2AAgent(BaseAgent):
|
||||
"""Parse A2A Artifact into ChatMessage using part contents."""
|
||||
contents = self._parse_contents_from_a2a(artifact.parts)
|
||||
return ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=contents,
|
||||
raw_representation=artifact,
|
||||
)
|
||||
|
||||
@@ -25,7 +25,6 @@ from agent_framework import (
|
||||
AgentResponseUpdate,
|
||||
ChatMessage,
|
||||
Content,
|
||||
Role,
|
||||
)
|
||||
from agent_framework.a2a import A2AAgent
|
||||
from pytest import fixture, raises
|
||||
@@ -129,7 +128,7 @@ async def test_run_with_message_response(a2a_agent: A2AAgent, mock_a2a_client: M
|
||||
|
||||
assert isinstance(response, AgentResponse)
|
||||
assert len(response.messages) == 1
|
||||
assert response.messages[0].role == Role.ASSISTANT
|
||||
assert response.messages[0].role == "assistant"
|
||||
assert response.messages[0].text == "Hello from agent!"
|
||||
assert response.response_id == "msg-123"
|
||||
assert mock_a2a_client.call_count == 1
|
||||
@@ -144,7 +143,7 @@ async def test_run_with_task_response_single_artifact(a2a_agent: A2AAgent, mock_
|
||||
|
||||
assert isinstance(response, AgentResponse)
|
||||
assert len(response.messages) == 1
|
||||
assert response.messages[0].role == Role.ASSISTANT
|
||||
assert response.messages[0].role == "assistant"
|
||||
assert response.messages[0].text == "Generated report content"
|
||||
assert response.response_id == "task-456"
|
||||
assert mock_a2a_client.call_count == 1
|
||||
@@ -170,7 +169,7 @@ async def test_run_with_task_response_multiple_artifacts(a2a_agent: A2AAgent, mo
|
||||
|
||||
# All should be assistant messages
|
||||
for message in response.messages:
|
||||
assert message.role == Role.ASSISTANT
|
||||
assert message.role == "assistant"
|
||||
|
||||
assert response.response_id == "task-789"
|
||||
|
||||
@@ -233,7 +232,7 @@ def test_parse_messages_from_task_with_artifacts(a2a_agent: A2AAgent) -> None:
|
||||
assert len(result) == 2
|
||||
assert result[0].text == "Content 1"
|
||||
assert result[1].text == "Content 2"
|
||||
assert all(msg.role == Role.ASSISTANT for msg in result)
|
||||
assert all(msg.role == "assistant" for msg in result)
|
||||
|
||||
|
||||
def test_parse_message_from_artifact(a2a_agent: A2AAgent) -> None:
|
||||
@@ -252,7 +251,7 @@ def test_parse_message_from_artifact(a2a_agent: A2AAgent) -> None:
|
||||
result = a2a_agent._parse_message_from_artifact(artifact)
|
||||
|
||||
assert isinstance(result, ChatMessage)
|
||||
assert result.role == Role.ASSISTANT
|
||||
assert result.role == "assistant"
|
||||
assert result.text == "Artifact content"
|
||||
assert result.raw_representation == artifact
|
||||
|
||||
@@ -296,7 +295,7 @@ def test_prepare_message_for_a2a_with_error_content(a2a_agent: A2AAgent) -> None
|
||||
|
||||
# Create ChatMessage with ErrorContent
|
||||
error_content = Content.from_error(message="Test error message")
|
||||
message = ChatMessage(role=Role.USER, contents=[error_content])
|
||||
message = ChatMessage("user", [error_content])
|
||||
|
||||
# Convert to A2A message
|
||||
a2a_message = a2a_agent._prepare_message_for_a2a(message)
|
||||
@@ -311,7 +310,7 @@ def test_prepare_message_for_a2a_with_uri_content(a2a_agent: A2AAgent) -> None:
|
||||
|
||||
# Create ChatMessage with UriContent
|
||||
uri_content = Content.from_uri(uri="http://example.com/file.pdf", media_type="application/pdf")
|
||||
message = ChatMessage(role=Role.USER, contents=[uri_content])
|
||||
message = ChatMessage("user", [uri_content])
|
||||
|
||||
# Convert to A2A message
|
||||
a2a_message = a2a_agent._prepare_message_for_a2a(message)
|
||||
@@ -327,7 +326,7 @@ def test_prepare_message_for_a2a_with_data_content(a2a_agent: A2AAgent) -> None:
|
||||
|
||||
# Create ChatMessage with DataContent (base64 data URI)
|
||||
data_content = Content.from_uri(uri="data:text/plain;base64,SGVsbG8gV29ybGQ=", media_type="text/plain")
|
||||
message = ChatMessage(role=Role.USER, contents=[data_content])
|
||||
message = ChatMessage("user", [data_content])
|
||||
|
||||
# Convert to A2A message
|
||||
a2a_message = a2a_agent._prepare_message_for_a2a(message)
|
||||
@@ -341,7 +340,7 @@ def test_prepare_message_for_a2a_with_data_content(a2a_agent: A2AAgent) -> None:
|
||||
def test_prepare_message_for_a2a_empty_contents_raises_error(a2a_agent: A2AAgent) -> None:
|
||||
"""Test _prepare_message_for_a2a with empty contents raises ValueError."""
|
||||
# Create ChatMessage with no contents
|
||||
message = ChatMessage(role=Role.USER, contents=[])
|
||||
message = ChatMessage("user", [])
|
||||
|
||||
# Should raise ValueError for empty contents
|
||||
with raises(ValueError, match="ChatMessage.contents is empty"):
|
||||
@@ -360,7 +359,7 @@ async def test_run_stream_with_message_response(a2a_agent: A2AAgent, mock_a2a_cl
|
||||
# Verify streaming response
|
||||
assert len(updates) == 1
|
||||
assert isinstance(updates[0], AgentResponseUpdate)
|
||||
assert updates[0].role == Role.ASSISTANT
|
||||
assert updates[0].role == "assistant"
|
||||
assert len(updates[0].contents) == 1
|
||||
|
||||
content = updates[0].contents[0]
|
||||
@@ -408,7 +407,7 @@ def test_prepare_message_for_a2a_with_multiple_contents() -> None:
|
||||
|
||||
# Create message with multiple content types
|
||||
message = ChatMessage(
|
||||
role=Role.USER,
|
||||
role="user",
|
||||
contents=[
|
||||
Content.from_text(text="Here's the analysis:"),
|
||||
Content.from_data(data=b"binary data", media_type="application/octet-stream"),
|
||||
@@ -465,7 +464,7 @@ def test_prepare_message_for_a2a_with_hosted_file() -> None:
|
||||
|
||||
# Create message with hosted file content
|
||||
message = ChatMessage(
|
||||
role=Role.USER,
|
||||
role="user",
|
||||
contents=[Content.from_hosted_file(file_id="hosted://storage/document.pdf")],
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user