Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(tracing): support list input in `_get_agent_messages` and add tests (#1013)
zhijianmab840745eb220
diff --git a/src/agentscope/tracing/_extractor.py b/src/agentscope/tracing/_extractor.pyindex 64c85fd2d..6ca71ea87 100644--- a/src/agentscope/tracing/_extractor.py+++ b/src/agentscope/tracing/_extractor.py@@ -392,52 +392,56 @@ def _get_llm_response_attributes(def _get_agent_messages(- msg: Msg,-) -> dict[str, Any]:- """Convert AgentScope message to standardized parts format.+ msg: Msg | list[Msg],+) -> list[dict[str, Any]]:+ """Convert AgentScope message(s) to standardized parts format.Transforms Msg objects into OpenTelemetry GenAI format.Args:- msg (`Msg`):- AgentScope message object with content blocks. The message should- have a role, content blocks (text, image, tool_use, etc.), and- optionally a name.+ msg (`Msg | list[Msg]`):+ AgentScope message object or list of message objects with+ content blocks.Returns:- `dict[str, Any]`:- Formatted message dictionary with role, parts (converted content- blocks), name, and finish_reason. Returns a fallback text format- if conversion fails.+ `list[dict[str, Any]]`:+ List of formatted message dictionaries with role, parts, name,+ and finish_reason."""try:- parts = []- for block in msg.get_content_blocks():- part = _convert_block_to_part(block)- if part:- parts.append(part)-- formatted_msg = {- "role": msg.role,- "parts": parts,- "name": msg.name,- "finish_reason": "stop",- }-- return formatted_msg+ if isinstance(msg, Msg):+ msg = [msg]++ formatted_msgs = []+ for m in msg:+ parts = []+ for block in m.get_content_blocks():+ part = _convert_block_to_part(block)+ if part:+ parts.append(part)+ formatted_msg = {+ "role": m.role,+ "parts": parts,+ "name": m.name,+ "finish_reason": "stop",+ }+ formatted_msgs.append(formatted_msg)+ return formatted_msgsexcept Exception:- return {- "role": msg.role,- "parts": [- {- "type": "text",- "content": str(msg.content) if msg.content else "",- },- ],- "name": msg.name,- "finish_reason": "stop",- }+ return [+ {+ "role": msg.role,+ "parts": [+ {+ "type": "text",+ "content": str(msg.content) if msg.content else "",+ },+ ],+ "name": msg.name,+ "finish_reason": "stop",+ },+ ]def _get_agent_request_attributes(diff --git a/tests/tracing_extractor_test.py b/tests/tracing_extractor_test.pyindex 960c21fa2..d17ee07b2 100644--- a/tests/tracing_extractor_test.py+++ b/tests/tracing_extractor_test.py@@ -236,18 +236,78 @@ class ExtractorTest(TestCase):)self.assertIn(SpanAttributes.GEN_AI_OUTPUT_MESSAGES, attributes)- def test_get_agent_request_attributes(self) -> None:- """Test _get_agent_messages, request_attributes and span_name."""- # Test agent messages conversion+ def test_get_agent_messages_single_msg(self) -> None:+ """Test _get_agent_messages with single Msg input."""msg = Msg("test_user",[TextBlock(type="text", text="Hello")],"user",)result = _get_agent_messages(msg)- self.assertEqual(result["role"], "user")- self.assertEqual(result["name"], "test_user")- self.assertIn("parts", result)++ self.assertEqual(len(result), 1)+ self.assertEqual(result[0]["role"], "user")+ self.assertEqual(result[0]["name"], "test_user")+ self.assertEqual(result[0]["finish_reason"], "stop")+ self.assertIn("parts", result[0])+ self.assertEqual(len(result[0]["parts"]), 1)+ self.assertEqual(result[0]["parts"][0]["type"], "text")+ self.assertEqual(result[0]["parts"][0]["content"], "Hello")++ def test_get_agent_messages_list_of_msgs(self) -> None:+ """Test _get_agent_messages with list of Msg inputs."""+ msgs = [+ Msg(+ "user1",+ [TextBlock(type="text", text="Hello")],+ "user",+ ),+ Msg(+ "assistant1",+ [TextBlock(type="text", text="Hi there!")],+ "assistant",+ ),+ Msg(+ "user1",+ [TextBlock(type="text", text="How are you?")],+ "user",+ ),+ ]+ result = _get_agent_messages(msgs)++ # Verify correct number of messages+ self.assertEqual(len(result), 3)++ # Verify first message (user)+ self.assertEqual(result[0]["role"], "user")+ self.assertEqual(result[0]["name"], "user1")+ self.assertEqual(result[0]["finish_reason"], "stop")+ self.assertEqual(result[0]["parts"][0]["content"], "Hello")++ # Verify second message (assistant)+ self.assertEqual(result[1]["role"], "assistant")+ self.assertEqual(result[1]["name"], "assistant1")+ self.assertEqual(result[1]["finish_reason"], "stop")+ self.assertEqual(result[1]["parts"][0]["content"], "Hi there!")++ # Verify third message (user)+ self.assertEqual(result[2]["role"], "user")+ self.assertEqual(result[2]["name"], "user1")+ self.assertEqual(result[2]["parts"][0]["content"], "How are you?")++ def test_get_agent_messages_empty_list(self) -> None:+ """Test _get_agent_messages with empty list."""+ result = _get_agent_messages([])+ self.assertEqual(len(result), 0)++ def test_get_agent_request_attributes(self) -> None:+ """Test _get_agent_request_attributes and _get_agent_span_name."""+ # Test with single Msg+ msg = Msg(+ "test_user",+ [TextBlock(type="text", text="Hello")],+ "user",+ )# Test request attributesargs = (msg,)@@ -277,8 +337,48 @@ class ExtractorTest(TestCase):span_name = _get_agent_span_name(attributes)self.assertEqual(span_name, "invoke_agent TestAgent")+ def test_get_agent_request_attributes_with_list(self) -> None:+ """Test _get_agent_request_attributes with list of Msg inputs."""+ msgs = [+ Msg(+ "user1",+ [TextBlock(type="text", text="Hello")],+ "user",+ ),+ Msg(+ "assistant1",+ [TextBlock(type="text", text="Hi!")],+ "assistant",+ ),+ ]++ # Test with list in args+ args = (msgs,)+ kwargs = {}+ attributes = _get_agent_request_attributes(+ self.mock_agent,+ args,+ kwargs,+ )++ self.assertEqual(+ attributes[SpanAttributes.GEN_AI_OPERATION_NAME],+ OperationNameValues.INVOKE_AGENT,+ )+ self.assertIn(SpanAttributes.GEN_AI_INPUT_MESSAGES, attributes)++ # Test with list in kwargs+ args = ()+ kwargs = {"msg": msgs}+ attributes = _get_agent_request_attributes(+ self.mock_agent,+ args,+ kwargs,+ )+ self.assertIn(SpanAttributes.GEN_AI_INPUT_MESSAGES, attributes)+def test_get_agent_response_attributes(self) -> None:- """Test _get_agent_response_attributes."""+ """Test _get_agent_response_attributes with single Msg."""response = Msg("assistant",[TextBlock(type="text", text="Hi")],@@ -289,6 +389,25 @@ class ExtractorTest(TestCase):self.assertIn(SpanAttributes.GEN_AI_OUTPUT_MESSAGES, attributes)self.assertIn(SpanAttributes.AGENTSCOPE_FUNCTION_OUTPUT, attributes)+ def test_get_agent_response_attributes_with_list(self) -> None:+ """Test _get_agent_response_attributes with list of Msg."""+ responses = [+ Msg(+ "assistant",+ [TextBlock(type="text", text="First response")],+ "assistant",+ ),+ Msg(+ "assistant",+ [TextBlock(type="text", text="Second response")],+ "assistant",+ ),+ ]+ attributes = _get_agent_response_attributes(responses)++ self.assertIn(SpanAttributes.GEN_AI_OUTPUT_MESSAGES, attributes)+ self.assertIn(SpanAttributes.AGENTSCOPE_FUNCTION_OUTPUT, attributes)+def test_get_tool_request_attributes(self) -> None:"""Test _get_tool_request_attributes and _get_tool_span_name."""# Create a mock toolkit with tool definition