Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(formatter): make OpenAI chat message names match the API pattern (#3548)
Jiangang Kong0df44746758e
diff --git a/src/agentscope/formatter/_openai_formatter.py b/src/agentscope/formatter/_openai_formatter.pyindex a131aec75..cc58709e0 100644--- a/src/agentscope/formatter/_openai_formatter.py+++ b/src/agentscope/formatter/_openai_formatter.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""The OpenAI formatter for agentscope."""import base64+import refrom abc import ABCfrom fnmatch import fnmatchfrom typing import Any@@ -24,6 +25,33 @@ from ..message import ()+# The Chat Completions API rejects a message ``name`` containing whitespace+# or any of ``<|\/>`` with a 400 error: "string does not match pattern.+# Expected a string that matches the pattern '^[^\s<|\\/>]+$'".+_INVALID_MESSAGE_NAME_CHARS = re.compile(r"[\s<|\\/>]+")+++def _format_message_name(name: str | None) -> dict[str, str]:+ """Build the ``name`` field of an OpenAI chat message.++ Agent and user names are free text (e.g. ``"Research Assistant"``),+ while the API only accepts names without whitespace and ``<|\\/>``.+ Each run of such characters is replaced with ``_``, and the field is+ omitted for an empty name, which the API rejects as well.++ Args:+ name (`str | None`):+ The name of the message sender.++ Returns:+ `dict[str, str]`:+ ``{"name": <valid name>}``, or an empty dict.+ """+ if not name:+ return {}+ return {"name": _INVALID_MESSAGE_NAME_CHARS.sub("_", name)}++class _OpenAIFormatterBase(FormatterBase, ABC):"""Base class for OpenAI formatters, providing shared data blockformatting logic."""@@ -295,7 +323,7 @@ class OpenAIChatFormatter(_OpenAIFormatterBase):if content_blocks or tool_calls:msg_openai = {"role": msg.role,- "name": msg.name,+ **_format_message_name(msg.name),"content": content_blocks or None,}if tool_calls:@@ -347,7 +375,7 @@ class OpenAIChatFormatter(_OpenAIFormatterBase):if content_blocks or tool_calls:msg_openai_flush = {"role": msg.role,- "name": msg.name,+ **_format_message_name(msg.name),"content": content_blocks or None,}if tool_calls:@@ -407,7 +435,7 @@ class OpenAIChatFormatter(_OpenAIFormatterBase):msg_openai = {"role": msg.role,- "name": msg.name,+ **_format_message_name(msg.name),"content": content_blocks or None,}diff --git a/tests/formatter_openai_chat_test.py b/tests/formatter_openai_chat_test.pyindex 90f61b365..1d1e67f0f 100644--- a/tests/formatter_openai_chat_test.py+++ b/tests/formatter_openai_chat_test.py@@ -583,6 +583,80 @@ class TestOpenAIFormatter(IsolatedAsyncioTestCase):res,)+ async def test_chat_formatter_sanitizes_message_name(self) -> None:+ """Message names must match the API pattern ``^[^\\s<|\\\\/>]+$``:+ free-text agent and user names are made valid instead of being+ forwarded verbatim, which the API rejects with a 400 error."""+ msgs = [+ UserMsg(name="John Doe", content="Hi"),+ AssistantMsg(+ name="Research Assistant",+ content=[+ TextBlock(text="Let me check."),+ ToolCallBlock(+ id="call_1",+ name="search",+ input="{}",+ ),+ ToolResultBlock(+ id="call_1",+ name="search",+ output="result",+ state=ToolResultState.SUCCESS,+ ),+ TextBlock(text="Done."),+ ],+ ),+ AssistantMsg(name="a<b|c\\d/e>f", content="ok"),+ AssistantMsg(name="", content="anonymous"),+ ]+ gt = [+ {+ "role": "user",+ "name": "John_Doe",+ "content": [{"type": "text", "text": "Hi"}],+ },+ {+ "role": "assistant",+ "name": "Research_Assistant",+ "content": [{"type": "text", "text": "Let me check."}],+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "search", "arguments": "{}"},+ },+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "content": "result",+ "name": "search",+ },+ {+ "role": "assistant",+ "name": "Research_Assistant",+ "content": [{"type": "text", "text": "Done."}],+ },+ {+ "role": "assistant",+ "name": "a_b_c_d_e_f",+ "content": [{"type": "text", "text": "ok"}],+ },+ {+ "role": "assistant",+ "content": [{"type": "text", "text": "anonymous"}],+ },+ ]+ res = await OpenAIChatFormatter().format(msgs)+ self.assertListEqual(gt, res)++ # Tool sequences in multi-agent conversations reuse the chat+ # formatter, so their names are made valid as well.+ res = await OpenAIMultiAgentFormatter().format(msgs[1:2])+ self.assertListEqual(gt[1:4], res)+async def test_chat_formatter_url_image_in_tool_result(self,) -> None: