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:
@@ -1,6 +1,6 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
from agent_framework._types import ChatMessage, Content, Role
|
||||
from agent_framework._types import ChatMessage, Content
|
||||
from loguru import logger
|
||||
|
||||
|
||||
@@ -18,25 +18,25 @@ def flip_messages(messages: list[ChatMessage]) -> list[ChatMessage]:
|
||||
|
||||
flipped_messages = []
|
||||
for msg in messages:
|
||||
if msg.role == Role.ASSISTANT:
|
||||
if msg.role == "assistant":
|
||||
# Flip assistant to user
|
||||
contents = filter_out_function_calls(msg.contents)
|
||||
if contents:
|
||||
flipped_msg = ChatMessage(
|
||||
role=Role.USER,
|
||||
role="user",
|
||||
# The function calls will cause 400 when role is user
|
||||
contents=contents,
|
||||
author_name=msg.author_name,
|
||||
message_id=msg.message_id,
|
||||
)
|
||||
flipped_messages.append(flipped_msg)
|
||||
elif msg.role == Role.USER:
|
||||
elif msg.role == "user":
|
||||
# Flip user to assistant
|
||||
flipped_msg = ChatMessage(
|
||||
role=Role.ASSISTANT, contents=msg.contents, author_name=msg.author_name, message_id=msg.message_id
|
||||
role="assistant", contents=msg.contents, author_name=msg.author_name, message_id=msg.message_id
|
||||
)
|
||||
flipped_messages.append(flipped_msg)
|
||||
elif msg.role == Role.TOOL:
|
||||
elif msg.role == "tool":
|
||||
# Skip tool messages
|
||||
pass
|
||||
else:
|
||||
@@ -59,16 +59,16 @@ def log_messages(messages: list[ChatMessage]) -> None:
|
||||
if hasattr(content, "type"):
|
||||
if content.type == "text":
|
||||
escape_text = content.text.replace("<", r"\<") # type: ignore[union-attr]
|
||||
if msg.role == Role.SYSTEM:
|
||||
if msg.role == "system":
|
||||
logger_.info(f"<cyan>[SYSTEM]</cyan> {escape_text}")
|
||||
elif msg.role == Role.USER:
|
||||
elif msg.role == "user":
|
||||
logger_.info(f"<green>[USER]</green> {escape_text}")
|
||||
elif msg.role == Role.ASSISTANT:
|
||||
elif msg.role == "assistant":
|
||||
logger_.info(f"<blue>[ASSISTANT]</blue> {escape_text}")
|
||||
elif msg.role == Role.TOOL:
|
||||
elif msg.role == "tool":
|
||||
logger_.info(f"<yellow>[TOOL]</yellow> {escape_text}")
|
||||
else:
|
||||
logger_.info(f"<magenta>[{msg.role.value.upper()}]</magenta> {escape_text}")
|
||||
logger_.info(f"<magenta>[{msg.role.upper()}]</magenta> {escape_text}")
|
||||
elif content.type == "function_call":
|
||||
function_call_text = f"{content.name}({content.arguments})"
|
||||
function_call_text = function_call_text.replace("<", r"\<")
|
||||
@@ -79,34 +79,34 @@ def log_messages(messages: list[ChatMessage]) -> None:
|
||||
logger_.info(f"<yellow>[TOOL_RESULT]</yellow> 🔨 {function_result_text}")
|
||||
else:
|
||||
content_text = str(content).replace("<", r"\<")
|
||||
logger_.info(f"<magenta>[{msg.role.value.upper()}] ({content.type})</magenta> {content_text}")
|
||||
logger_.info(f"<magenta>[{msg.role.upper()}] ({content.type})</magenta> {content_text}")
|
||||
else:
|
||||
# Fallback for content without type
|
||||
text_content = str(content).replace("<", r"\<")
|
||||
if msg.role == Role.SYSTEM:
|
||||
if msg.role == "system":
|
||||
logger_.info(f"<cyan>[SYSTEM]</cyan> {text_content}")
|
||||
elif msg.role == Role.USER:
|
||||
elif msg.role == "user":
|
||||
logger_.info(f"<green>[USER]</green> {text_content}")
|
||||
elif msg.role == Role.ASSISTANT:
|
||||
elif msg.role == "assistant":
|
||||
logger_.info(f"<blue>[ASSISTANT]</blue> {text_content}")
|
||||
elif msg.role == Role.TOOL:
|
||||
elif msg.role == "tool":
|
||||
logger_.info(f"<yellow>[TOOL]</yellow> {text_content}")
|
||||
else:
|
||||
logger_.info(f"<magenta>[{msg.role.value.upper()}]</magenta> {text_content}")
|
||||
logger_.info(f"<magenta>[{msg.role.upper()}]</magenta> {text_content}")
|
||||
elif hasattr(msg, "text") and msg.text:
|
||||
# Handle simple text messages
|
||||
text_content = msg.text.replace("<", r"\<")
|
||||
if msg.role == Role.SYSTEM:
|
||||
if msg.role == "system":
|
||||
logger_.info(f"<cyan>[SYSTEM]</cyan> {text_content}")
|
||||
elif msg.role == Role.USER:
|
||||
elif msg.role == "user":
|
||||
logger_.info(f"<green>[USER]</green> {text_content}")
|
||||
elif msg.role == Role.ASSISTANT:
|
||||
elif msg.role == "assistant":
|
||||
logger_.info(f"<blue>[ASSISTANT]</blue> {text_content}")
|
||||
elif msg.role == Role.TOOL:
|
||||
elif msg.role == "tool":
|
||||
logger_.info(f"<yellow>[TOOL]</yellow> {text_content}")
|
||||
else:
|
||||
logger_.info(f"<magenta>[{msg.role.value.upper()}]</magenta> {text_content}")
|
||||
logger_.info(f"<magenta>[{msg.role.upper()}]</magenta> {text_content}")
|
||||
else:
|
||||
# Fallback for other message formats
|
||||
text_content = str(msg).replace("<", r"\<")
|
||||
logger_.info(f"<magenta>[{msg.role.value.upper()}]</magenta> {text_content}")
|
||||
logger_.info(f"<magenta>[{msg.role.upper()}]</magenta> {text_content}")
|
||||
|
||||
@@ -5,7 +5,7 @@ from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
import tiktoken
|
||||
from agent_framework import ChatMessage, ChatMessageStore, Role
|
||||
from agent_framework import ChatMessage, ChatMessageStore
|
||||
from loguru import logger
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class SlidingWindowChatMessageStore(ChatMessageStore):
|
||||
logger.warning("Messages exceed max tokens. Truncating oldest message.")
|
||||
self.truncated_messages.pop(0)
|
||||
# Remove leading tool messages
|
||||
while len(self.truncated_messages) > 0 and self.truncated_messages[0].role == Role.TOOL:
|
||||
while len(self.truncated_messages) > 0 and self.truncated_messages[0].role == "tool":
|
||||
logger.warning("Removing leading tool message because tool result cannot be the first message.")
|
||||
self.truncated_messages.pop(0)
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from agent_framework import (
|
||||
ChatClientProtocol,
|
||||
ChatMessage,
|
||||
FunctionExecutor,
|
||||
Role,
|
||||
Workflow,
|
||||
WorkflowBuilder,
|
||||
WorkflowContext,
|
||||
@@ -339,11 +338,11 @@ class TaskRunner:
|
||||
# Matches tau2's expected conversation start pattern
|
||||
logger.info(f"Starting workflow with hardcoded greeting: '{DEFAULT_FIRST_AGENT_MESSAGE}'")
|
||||
|
||||
first_message = ChatMessage(Role.ASSISTANT, text=DEFAULT_FIRST_AGENT_MESSAGE)
|
||||
first_message = ChatMessage("assistant", text=DEFAULT_FIRST_AGENT_MESSAGE)
|
||||
initial_greeting = AgentExecutorResponse(
|
||||
executor_id=ASSISTANT_AGENT_ID,
|
||||
agent_response=AgentResponse(messages=[first_message]),
|
||||
full_conversation=[ChatMessage(Role.ASSISTANT, text=DEFAULT_FIRST_AGENT_MESSAGE)],
|
||||
full_conversation=[ChatMessage("assistant", text=DEFAULT_FIRST_AGENT_MESSAGE)],
|
||||
)
|
||||
|
||||
# STEP 4: Execute the workflow and collect results
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from agent_framework._types import ChatMessage, Content, Role
|
||||
from agent_framework._types import ChatMessage, Content
|
||||
from agent_framework_lab_tau2._message_utils import flip_messages, log_messages
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ def test_flip_messages_user_to_assistant():
|
||||
"""Test flipping user message to assistant."""
|
||||
messages = [
|
||||
ChatMessage(
|
||||
role=Role.USER,
|
||||
role="user",
|
||||
contents=[Content.from_text(text="Hello assistant")],
|
||||
author_name="User1",
|
||||
message_id="msg_001",
|
||||
@@ -20,7 +20,7 @@ def test_flip_messages_user_to_assistant():
|
||||
flipped = flip_messages(messages)
|
||||
|
||||
assert len(flipped) == 1
|
||||
assert flipped[0].role == Role.ASSISTANT
|
||||
assert flipped[0].role == "assistant"
|
||||
assert flipped[0].text == "Hello assistant"
|
||||
assert flipped[0].author_name == "User1"
|
||||
assert flipped[0].message_id == "msg_001"
|
||||
@@ -30,7 +30,7 @@ def test_flip_messages_assistant_to_user():
|
||||
"""Test flipping assistant message to user."""
|
||||
messages = [
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=[Content.from_text(text="Hello user")],
|
||||
author_name="Assistant1",
|
||||
message_id="msg_002",
|
||||
@@ -40,7 +40,7 @@ def test_flip_messages_assistant_to_user():
|
||||
flipped = flip_messages(messages)
|
||||
|
||||
assert len(flipped) == 1
|
||||
assert flipped[0].role == Role.USER
|
||||
assert flipped[0].role == "user"
|
||||
assert flipped[0].text == "Hello user"
|
||||
assert flipped[0].author_name == "Assistant1"
|
||||
assert flipped[0].message_id == "msg_002"
|
||||
@@ -52,7 +52,7 @@ def test_flip_messages_assistant_with_function_calls_filtered():
|
||||
|
||||
messages = [
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=[
|
||||
Content.from_text(text="I'll call a function"),
|
||||
function_call,
|
||||
@@ -65,7 +65,7 @@ def test_flip_messages_assistant_with_function_calls_filtered():
|
||||
flipped = flip_messages(messages)
|
||||
|
||||
assert len(flipped) == 1
|
||||
assert flipped[0].role == Role.USER
|
||||
assert flipped[0].role == "user"
|
||||
# Function call should be filtered out
|
||||
assert len(flipped[0].contents) == 2
|
||||
assert all(content.type == "text" for content in flipped[0].contents)
|
||||
@@ -78,7 +78,7 @@ def test_flip_messages_assistant_with_only_function_calls_skipped():
|
||||
function_call = Content.from_function_call(call_id="call_456", name="another_function", arguments={"key": "value"})
|
||||
|
||||
messages = [
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[function_call], message_id="msg_004") # Only function call, no text
|
||||
ChatMessage("assistant", [function_call], message_id="msg_004") # Only function call, no text
|
||||
]
|
||||
|
||||
flipped = flip_messages(messages)
|
||||
@@ -91,7 +91,7 @@ def test_flip_messages_tool_messages_skipped():
|
||||
"""Test that tool messages are skipped."""
|
||||
function_result = Content.from_function_result(call_id="call_789", result={"success": True})
|
||||
|
||||
messages = [ChatMessage(role=Role.TOOL, contents=[function_result])]
|
||||
messages = [ChatMessage("tool", [function_result])]
|
||||
|
||||
flipped = flip_messages(messages)
|
||||
|
||||
@@ -101,14 +101,12 @@ def test_flip_messages_tool_messages_skipped():
|
||||
|
||||
def test_flip_messages_system_messages_preserved():
|
||||
"""Test that system messages are preserved as-is."""
|
||||
messages = [
|
||||
ChatMessage(role=Role.SYSTEM, contents=[Content.from_text(text="System instruction")], message_id="sys_001")
|
||||
]
|
||||
messages = [ChatMessage("system", [Content.from_text(text="System instruction")], message_id="sys_001")]
|
||||
|
||||
flipped = flip_messages(messages)
|
||||
|
||||
assert len(flipped) == 1
|
||||
assert flipped[0].role == Role.SYSTEM
|
||||
assert flipped[0].role == "system"
|
||||
assert flipped[0].text == "System instruction"
|
||||
assert flipped[0].message_id == "sys_001"
|
||||
|
||||
@@ -120,11 +118,11 @@ def test_flip_messages_mixed_conversation():
|
||||
function_result = Content.from_function_result(call_id="call_mixed", result="function result")
|
||||
|
||||
messages = [
|
||||
ChatMessage(role=Role.SYSTEM, contents=[Content.from_text(text="System prompt")]),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="User question")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Assistant response"), function_call]),
|
||||
ChatMessage(role=Role.TOOL, contents=[function_result]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Final response")]),
|
||||
ChatMessage("system", [Content.from_text(text="System prompt")]),
|
||||
ChatMessage("user", [Content.from_text(text="User question")]),
|
||||
ChatMessage("assistant", [Content.from_text(text="Assistant response"), function_call]),
|
||||
ChatMessage("tool", [function_result]),
|
||||
ChatMessage("assistant", [Content.from_text(text="Final response")]),
|
||||
]
|
||||
|
||||
flipped = flip_messages(messages)
|
||||
@@ -134,18 +132,18 @@ def test_flip_messages_mixed_conversation():
|
||||
assert len(flipped) == 4
|
||||
|
||||
# Check each flipped message
|
||||
assert flipped[0].role == Role.SYSTEM
|
||||
assert flipped[0].role == "system"
|
||||
assert flipped[0].text == "System prompt"
|
||||
|
||||
assert flipped[1].role == Role.ASSISTANT
|
||||
assert flipped[1].role == "assistant"
|
||||
assert flipped[1].text == "User question"
|
||||
|
||||
assert flipped[2].role == Role.USER
|
||||
assert flipped[2].role == "user"
|
||||
assert flipped[2].text == "Assistant response" # Function call filtered out
|
||||
|
||||
# Tool message skipped
|
||||
|
||||
assert flipped[3].role == Role.USER
|
||||
assert flipped[3].role == "user"
|
||||
assert flipped[3].text == "Final response"
|
||||
|
||||
|
||||
@@ -160,7 +158,7 @@ def test_flip_messages_preserves_metadata():
|
||||
"""Test that message metadata is preserved during flipping."""
|
||||
messages = [
|
||||
ChatMessage(
|
||||
role=Role.USER,
|
||||
role="user",
|
||||
contents=[Content.from_text(text="Test message")],
|
||||
author_name="TestUser",
|
||||
message_id="test_123",
|
||||
@@ -178,8 +176,8 @@ def test_flip_messages_preserves_metadata():
|
||||
def test_log_messages_text_content(mock_logger):
|
||||
"""Test logging messages with text content."""
|
||||
messages = [
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Hi there!")]),
|
||||
ChatMessage("user", [Content.from_text(text="Hello")]),
|
||||
ChatMessage("assistant", [Content.from_text(text="Hi there!")]),
|
||||
]
|
||||
|
||||
log_messages(messages)
|
||||
@@ -193,7 +191,7 @@ def test_log_messages_function_call(mock_logger):
|
||||
"""Test logging messages with function calls."""
|
||||
function_call = Content.from_function_call(call_id="call_log", name="log_function", arguments={"param": "value"})
|
||||
|
||||
messages = [ChatMessage(role=Role.ASSISTANT, contents=[function_call])]
|
||||
messages = [ChatMessage("assistant", [function_call])]
|
||||
|
||||
log_messages(messages)
|
||||
|
||||
@@ -209,7 +207,7 @@ def test_log_messages_function_result(mock_logger):
|
||||
"""Test logging messages with function results."""
|
||||
function_result = Content.from_function_result(call_id="call_result", result="success")
|
||||
|
||||
messages = [ChatMessage(role=Role.TOOL, contents=[function_result])]
|
||||
messages = [ChatMessage("tool", [function_result])]
|
||||
|
||||
log_messages(messages)
|
||||
|
||||
@@ -223,10 +221,10 @@ def test_log_messages_function_result(mock_logger):
|
||||
def test_log_messages_different_roles(mock_logger):
|
||||
"""Test logging messages with different roles get different colors."""
|
||||
messages = [
|
||||
ChatMessage(role=Role.SYSTEM, contents=[Content.from_text(text="System")]),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="User")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Assistant")]),
|
||||
ChatMessage(role=Role.TOOL, contents=[Content.from_text(text="Tool")]),
|
||||
ChatMessage("system", [Content.from_text(text="System")]),
|
||||
ChatMessage("user", [Content.from_text(text="User")]),
|
||||
ChatMessage("assistant", [Content.from_text(text="Assistant")]),
|
||||
ChatMessage("tool", [Content.from_text(text="Tool")]),
|
||||
]
|
||||
|
||||
log_messages(messages)
|
||||
@@ -250,7 +248,7 @@ def test_log_messages_different_roles(mock_logger):
|
||||
@patch("agent_framework_lab_tau2._message_utils.logger")
|
||||
def test_log_messages_escapes_html(mock_logger):
|
||||
"""Test that HTML-like characters are properly escaped in log output."""
|
||||
messages = [ChatMessage(role=Role.USER, contents=[Content.from_text(text="Message with <tag> content")])]
|
||||
messages = [ChatMessage("user", [Content.from_text(text="Message with <tag> content")])]
|
||||
|
||||
log_messages(messages)
|
||||
|
||||
@@ -267,7 +265,7 @@ def test_log_messages_mixed_content_types(mock_logger):
|
||||
|
||||
messages = [
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=[Content.from_text(text="I'll call a function"), function_call, Content.from_text(text="Done!")],
|
||||
)
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from agent_framework._types import ChatMessage, Content, Role
|
||||
from agent_framework._types import ChatMessage, Content
|
||||
from agent_framework_lab_tau2._sliding_window import SlidingWindowChatMessageStore
|
||||
|
||||
|
||||
@@ -36,8 +36,8 @@ def test_initialization_with_parameters():
|
||||
def test_initialization_with_messages():
|
||||
"""Test initializing with existing messages."""
|
||||
messages = [
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Hi there!")]),
|
||||
ChatMessage("user", [Content.from_text(text="Hello")]),
|
||||
ChatMessage("assistant", [Content.from_text(text="Hi there!")]),
|
||||
]
|
||||
|
||||
sliding_window = SlidingWindowChatMessageStore(messages=messages, max_tokens=1000)
|
||||
@@ -51,8 +51,8 @@ async def test_add_messages_simple():
|
||||
sliding_window = SlidingWindowChatMessageStore(max_tokens=10000) # Large limit
|
||||
|
||||
new_messages = [
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="What's the weather?")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="I can help with that.")]),
|
||||
ChatMessage("user", [Content.from_text(text="What's the weather?")]),
|
||||
ChatMessage("assistant", [Content.from_text(text="I can help with that.")]),
|
||||
]
|
||||
|
||||
await sliding_window.add_messages(new_messages)
|
||||
@@ -68,10 +68,7 @@ async def test_list_all_messages_vs_list_messages():
|
||||
sliding_window = SlidingWindowChatMessageStore(max_tokens=50) # Small limit to force truncation
|
||||
|
||||
# Add many messages to trigger truncation
|
||||
messages = [
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text=f"Message {i} with some content")])
|
||||
for i in range(10)
|
||||
]
|
||||
messages = [ChatMessage("user", [Content.from_text(text=f"Message {i} with some content")]) for i in range(10)]
|
||||
|
||||
await sliding_window.add_messages(messages)
|
||||
|
||||
@@ -88,7 +85,7 @@ async def test_list_all_messages_vs_list_messages():
|
||||
def test_get_token_count_basic():
|
||||
"""Test basic token counting."""
|
||||
sliding_window = SlidingWindowChatMessageStore(max_tokens=1000)
|
||||
sliding_window.truncated_messages = [ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello")])]
|
||||
sliding_window.truncated_messages = [ChatMessage("user", [Content.from_text(text="Hello")])]
|
||||
|
||||
token_count = sliding_window.get_token_count()
|
||||
|
||||
@@ -105,7 +102,7 @@ def test_get_token_count_with_system_message():
|
||||
token_count_empty = sliding_window.get_token_count()
|
||||
|
||||
# Add a message
|
||||
sliding_window.truncated_messages = [ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello")])]
|
||||
sliding_window.truncated_messages = [ChatMessage("user", [Content.from_text(text="Hello")])]
|
||||
token_count_with_message = sliding_window.get_token_count()
|
||||
|
||||
# With message should be more tokens
|
||||
@@ -118,7 +115,7 @@ def test_get_token_count_function_call():
|
||||
function_call = Content.from_function_call(call_id="call_123", name="test_function", arguments={"param": "value"})
|
||||
|
||||
sliding_window = SlidingWindowChatMessageStore(max_tokens=1000)
|
||||
sliding_window.truncated_messages = [ChatMessage(role=Role.ASSISTANT, contents=[function_call])]
|
||||
sliding_window.truncated_messages = [ChatMessage("assistant", [function_call])]
|
||||
|
||||
token_count = sliding_window.get_token_count()
|
||||
assert token_count > 0
|
||||
@@ -129,7 +126,7 @@ def test_get_token_count_function_result():
|
||||
function_result = Content.from_function_result(call_id="call_123", result={"success": True, "data": "result"})
|
||||
|
||||
sliding_window = SlidingWindowChatMessageStore(max_tokens=1000)
|
||||
sliding_window.truncated_messages = [ChatMessage(role=Role.TOOL, contents=[function_result])]
|
||||
sliding_window.truncated_messages = [ChatMessage("tool", [function_result])]
|
||||
|
||||
token_count = sliding_window.get_token_count()
|
||||
assert token_count > 0
|
||||
@@ -143,16 +140,16 @@ def test_truncate_messages_removes_old_messages(mock_logger):
|
||||
# Create messages that will exceed the limit
|
||||
messages = [
|
||||
ChatMessage(
|
||||
role=Role.USER,
|
||||
role="user",
|
||||
contents=[Content.from_text(text="This is a very long message that should exceed the token limit")],
|
||||
),
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=[
|
||||
Content.from_text(text="This is another very long message that should also exceed the token limit")
|
||||
],
|
||||
),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="Short msg")]),
|
||||
ChatMessage("user", [Content.from_text(text="Short msg")]),
|
||||
]
|
||||
|
||||
sliding_window.truncated_messages = messages.copy()
|
||||
@@ -172,16 +169,16 @@ def test_truncate_messages_removes_leading_tool_messages(mock_logger):
|
||||
|
||||
# Create messages starting with tool message
|
||||
tool_message = ChatMessage(
|
||||
role=Role.TOOL, contents=[Content.from_function_result(call_id="call_123", result="result")]
|
||||
role="tool", contents=[Content.from_function_result(call_id="call_123", result="result")]
|
||||
)
|
||||
user_message = ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello")])
|
||||
user_message = ChatMessage("user", [Content.from_text(text="Hello")])
|
||||
|
||||
sliding_window.truncated_messages = [tool_message, user_message]
|
||||
sliding_window.truncate_messages()
|
||||
|
||||
# Tool message should be removed from the beginning
|
||||
assert len(sliding_window.truncated_messages) == 1
|
||||
assert sliding_window.truncated_messages[0].role == Role.USER
|
||||
assert sliding_window.truncated_messages[0].role == "user"
|
||||
|
||||
# Should have logged warning about removing tool message
|
||||
mock_logger.warning.assert_called()
|
||||
@@ -232,14 +229,14 @@ async def test_real_world_scenario():
|
||||
|
||||
# Simulate a conversation
|
||||
conversation = [
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello, how are you?")]),
|
||||
ChatMessage("user", [Content.from_text(text="Hello, how are you?")]),
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=[Content.from_text(text="I'm doing well, thank you! How can I help you today?")],
|
||||
),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="Can you tell me about the weather?")]),
|
||||
ChatMessage("user", [Content.from_text(text="Can you tell me about the weather?")]),
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=[
|
||||
Content.from_text(
|
||||
text="I'd be happy to help with weather information, "
|
||||
@@ -247,9 +244,9 @@ async def test_real_world_scenario():
|
||||
)
|
||||
],
|
||||
),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="What about telling me a joke instead?")]),
|
||||
ChatMessage("user", [Content.from_text(text="What about telling me a joke instead?")]),
|
||||
ChatMessage(
|
||||
role=Role.ASSISTANT,
|
||||
role="assistant",
|
||||
contents=[
|
||||
Content.from_text(text="Sure! Why don't scientists trust atoms? Because they make up everything!")
|
||||
],
|
||||
|
||||
@@ -6,7 +6,7 @@ import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from agent_framework import ChatMessage, Content, FunctionTool, Role
|
||||
from agent_framework import ChatMessage, Content, FunctionTool
|
||||
from agent_framework_lab_tau2._tau2_utils import (
|
||||
convert_agent_framework_messages_to_tau2_messages,
|
||||
convert_tau2_tool_to_function_tool,
|
||||
@@ -91,7 +91,7 @@ def test_convert_tau2_tool_to_function_tool_multiple_tools(tau2_airline_environm
|
||||
|
||||
def test_convert_agent_framework_messages_to_tau2_messages_system():
|
||||
"""Test converting system message."""
|
||||
messages = [ChatMessage(role=Role.SYSTEM, contents=[Content.from_text(text="System instruction")])]
|
||||
messages = [ChatMessage("system", [Content.from_text(text="System instruction")])]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
@@ -103,7 +103,7 @@ def test_convert_agent_framework_messages_to_tau2_messages_system():
|
||||
|
||||
def test_convert_agent_framework_messages_to_tau2_messages_user():
|
||||
"""Test converting user message."""
|
||||
messages = [ChatMessage(role=Role.USER, contents=[Content.from_text(text="Hello assistant")])]
|
||||
messages = [ChatMessage("user", [Content.from_text(text="Hello assistant")])]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
@@ -116,7 +116,7 @@ def test_convert_agent_framework_messages_to_tau2_messages_user():
|
||||
|
||||
def test_convert_agent_framework_messages_to_tau2_messages_assistant():
|
||||
"""Test converting assistant message."""
|
||||
messages = [ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Hello user")])]
|
||||
messages = [ChatMessage("assistant", [Content.from_text(text="Hello user")])]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
@@ -131,9 +131,7 @@ def test_convert_agent_framework_messages_to_tau2_messages_with_function_call():
|
||||
"""Test converting message with function call."""
|
||||
function_call = Content.from_function_call(call_id="call_123", name="test_function", arguments={"param": "value"})
|
||||
|
||||
messages = [
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="I'll call a function"), function_call])
|
||||
]
|
||||
messages = [ChatMessage("assistant", [Content.from_text(text="I'll call a function"), function_call])]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
@@ -155,7 +153,7 @@ def test_convert_agent_framework_messages_to_tau2_messages_with_function_result(
|
||||
"""Test converting message with function result."""
|
||||
function_result = Content.from_function_result(call_id="call_123", result={"success": True, "data": "result data"})
|
||||
|
||||
messages = [ChatMessage(role=Role.TOOL, contents=[function_result])]
|
||||
messages = [ChatMessage("tool", [function_result])]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
@@ -175,7 +173,7 @@ def test_convert_agent_framework_messages_to_tau2_messages_with_error():
|
||||
call_id="call_456", result="Error occurred", exception=Exception("Test error")
|
||||
)
|
||||
|
||||
messages = [ChatMessage(role=Role.TOOL, contents=[function_result])]
|
||||
messages = [ChatMessage("tool", [function_result])]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
@@ -186,11 +184,7 @@ def test_convert_agent_framework_messages_to_tau2_messages_with_error():
|
||||
|
||||
def test_convert_agent_framework_messages_to_tau2_messages_multiple_text_contents():
|
||||
"""Test converting message with multiple text contents."""
|
||||
messages = [
|
||||
ChatMessage(
|
||||
role=Role.USER, contents=[Content.from_text(text="First part"), Content.from_text(text="Second part")]
|
||||
)
|
||||
]
|
||||
messages = [ChatMessage("user", [Content.from_text(text="First part"), Content.from_text(text="Second part")])]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
@@ -206,11 +200,11 @@ def test_convert_agent_framework_messages_to_tau2_messages_complex_scenario():
|
||||
function_result = Content.from_function_result(call_id="call_789", result={"output": "tool result"})
|
||||
|
||||
messages = [
|
||||
ChatMessage(role=Role.SYSTEM, contents=[Content.from_text(text="System prompt")]),
|
||||
ChatMessage(role=Role.USER, contents=[Content.from_text(text="User request")]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="I'll help you"), function_call]),
|
||||
ChatMessage(role=Role.TOOL, contents=[function_result]),
|
||||
ChatMessage(role=Role.ASSISTANT, contents=[Content.from_text(text="Based on the result...")]),
|
||||
ChatMessage("system", [Content.from_text(text="System prompt")]),
|
||||
ChatMessage("user", [Content.from_text(text="User request")]),
|
||||
ChatMessage("assistant", [Content.from_text(text="I'll help you"), function_call]),
|
||||
ChatMessage("tool", [function_result]),
|
||||
ChatMessage("assistant", [Content.from_text(text="Based on the result...")]),
|
||||
]
|
||||
|
||||
tau2_messages = convert_agent_framework_messages_to_tau2_messages(messages)
|
||||
|
||||
Reference in New Issue
Block a user