Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(model): handle audio output for OpenAI API (#1623)
qbc45c3526fddf1
diff --git a/scripts/model_examples/openai_chat_multimodal.py b/scripts/model_examples/openai_chat_multimodal.pyindex 07ec51dc8..b4dcb48a8 100644--- a/scripts/model_examples/openai_chat_multimodal.py+++ b/scripts/model_examples/openai_chat_multimodal.py@@ -22,6 +22,12 @@ TEST_IMAGE_URL = ("-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg")+# A publicly accessible test audio+TEST_AUDIO_URL = (+ "https://help-static-aliyun-doc.aliyuncs.com/file-manage"+ "-files/zh-CN/20250211/tixcef/cherry.wav"+)+async def example_image_url() -> None:"""Call gpt-4.1 with an image URL and ask what is in the image."""@@ -130,7 +136,59 @@ async def example_image_base64() -> None:await stream_and_collect(await model(msgs))+async def example_audio() -> None:+ """Call gpt-audio-mini with an audio URL.++ Audio understanding requires an audio-capable model such as+ ``gpt-audio-mini``. The formatter converts the audio source+ to the ``input_audio`` format expected by the Chat Completions API.+ """+ model = OpenAIChatModel(+ credential=OpenAICredential(+ api_key=os.environ["OPENAI_API_KEY"],+ ),+ model="gpt-audio-mini",+ stream=True,+ )++ audio_block = DataBlock(+ source=URLSource(+ url=TEST_AUDIO_URL,+ media_type="audio/wav",+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[+ TextBlock(text="What is being said in this audio clip?"),+ audio_block,+ ],+ role="user",+ ),+ ]++ print("=== Multimodal Call (Audio Input and Output) ===")+ response = await stream_and_collect(+ await model(+ msgs,+ modalities=["text", "audio"],+ audio={"voice": "alloy", "format": "pcm16"},+ ),+ )++ # Save audio if present+ for block in response.content:+ if isinstance(block, DataBlock) and block.source.media_type.startswith(+ "audio/",+ ):+ audio_bytes = base64.b64decode(block.source.data)+ print(f" Audio received: {len(audio_bytes)} bytes")++if __name__ == "__main__":asyncio.run(example_image_url())asyncio.run(example_image_local_path())asyncio.run(example_image_base64())+ asyncio.run(example_audio())diff --git a/src/agentscope/formatter/_openai_response_formatter.py b/src/agentscope/formatter/_openai_response_formatter.pyindex fee822f1a..82aa82d81 100644--- a/src/agentscope/formatter/_openai_response_formatter.py+++ b/src/agentscope/formatter/_openai_response_formatter.py@@ -27,10 +27,11 @@ class _OpenAIResponseFormatterBase(_OpenAIFormatterBase, ABC):"""input_types: list[str] = Field(- default_factory=lambda: ["text/plain", "image/*", "audio/*"],+ default_factory=lambda: ["text/plain", "image/*"],description=("The supported input types. "- 'Defaults to ``["text/plain", "image/*", "audio/*"]``.'+ 'Defaults to ``["text/plain", "image/*"]``. '+ "Audio is not supported by the Responses API."),)@@ -41,6 +42,14 @@ class _OpenAIResponseFormatterBase(_OpenAIFormatterBase, ABC):) -> dict[str, Any] | None:"""Format a DataBlock into the Response API format.+ The Responses API uses different content types from the Chat+ Completions API:++ * ``image_url`` → ``input_image``+ * ``input_audio`` → skipped (the Responses API does not support+ audio input yet; use Chat Completions API instead). See+ https://developers.openai.com/api/docs/guides/audio+Args:block (`DataBlock`):The DataBlock to format.@@ -52,6 +61,20 @@ class _OpenAIResponseFormatterBase(_OpenAIFormatterBase, ABC):A dictionary in the Responses API format, or ``None`` when theblock type is unsupported."""+ # Intercept audio blocks before the generic formatter rejects them+ # with a less helpful "Unsupported media type" warning. The Responses+ # API does not support audio input yet; use Chat Completions API with+ # an audio-capable model instead.+ # https://developers.openai.com/api/docs/guides/audio+ media_type = getattr(block.source, "media_type", "") or ""+ if media_type.split("/", 1)[0] == "audio":+ logger.warning(+ "Audio input is not supported by the OpenAI Responses API. "+ "Use OpenAIChatModel with an audio-capable model instead. "+ "This audio block will be skipped.",+ )+ return None+base_result = self._format_openai_data_block(block, role)if base_result is None:return Nonediff --git a/src/agentscope/model/_openai_chat/_model.py b/src/agentscope/model/_openai_chat/_model.pyindex 86ecc9c9d..ccef80ae5 100644--- a/src/agentscope/model/_openai_chat/_model.py+++ b/src/agentscope/model/_openai_chat/_model.py@@ -11,7 +11,14 @@ from .._model_response import ChatResponsefrom .._model_usage import ChatUsagefrom ...credential import OpenAICredentialfrom ...formatter import FormatterBase, OpenAIChatFormatter-from ...message import Msg, ThinkingBlock, ToolCallBlock, TextBlock+from ...message import (+ Msg,+ ThinkingBlock,+ ToolCallBlock,+ TextBlock,+ DataBlock,+ Base64Source,+)from ...tool import ToolChoiceif TYPE_CHECKING:@@ -202,15 +209,31 @@ class OpenAIChatModel(ChatModelBase):start_datetime = datetime.now()response = await client.chat.completions.create(**kwargs)+ audio_cfg = kwargs.get("audio")+ audio_fmt = (+ audio_cfg.get("format", "wav")+ if isinstance(audio_cfg, dict)+ else "wav"+ )+if self.stream:- return self._parse_stream_response(start_datetime, response)+ return self._parse_stream_response(+ start_datetime,+ response,+ audio_fmt,+ )- return self._parse_completion_response(start_datetime, response)+ return self._parse_completion_response(+ start_datetime,+ response,+ audio_fmt,+ )async def _parse_stream_response(self,start_datetime: datetime,response: AsyncStream,+ audio_format: str = "wav",) -> AsyncGenerator[ChatResponse, None]:"""Parse the OpenAI Chat streaming response.@@ -219,6 +242,9 @@ class OpenAIChatModel(ChatModelBase):The start datetime of the response generation.response (`AsyncStream`):The OpenAI async stream object.+ audio_format (`str`, defaults to ``"wav"``):+ The audio format requested (used to set the media type on+ the output ``DataBlock``).Yields:`ChatResponse`:@@ -231,6 +257,8 @@ class OpenAIChatModel(ChatModelBase):acc_text = TextBlock(text="")acc_thinking = ThinkingBlock(thinking="")acc_tool_calls: OrderedDict = OrderedDict()+ acc_audio_data: str = ""+ acc_audio_transcript: str = ""async with response as stream:async for chunk in stream:@@ -267,6 +295,23 @@ class OpenAIChatModel(ChatModelBase):delta_text = getattr(delta, "content", None) or ""+ # Collect audio output (delta.audio.data /+ # delta.audio.transcript)+ delta_audio = getattr(delta, "audio", None)+ if delta_audio is not None:+ if isinstance(delta_audio, dict):+ audio_chunk = delta_audio.get("data", "")+ transcript_chunk = delta_audio.get("transcript", "")+ else:+ audio_chunk = getattr(delta_audio, "data", "") or ""+ transcript_chunk = (+ getattr(delta_audio, "transcript", "") or ""+ )+ if audio_chunk:+ acc_audio_data += audio_chunk+ if transcript_chunk:+ acc_audio_transcript += transcript_chunk+acc_thinking.thinking += delta_thinkingacc_text.text += delta_text@@ -317,15 +362,28 @@ class OpenAIChatModel(ChatModelBase):_kwargs["id"] = response_idyield ChatResponse(**_kwargs)- final_contents: List[TextBlock | ToolCallBlock | ThinkingBlock] = []+ final_contents: List[+ TextBlock | ToolCallBlock | ThinkingBlock | DataBlock+ ] = []if acc_thinking.thinking:final_contents.append(acc_thinking)if acc_text.text:final_contents.append(acc_text)+ elif acc_audio_transcript:+ final_contents.append(TextBlock(text=acc_audio_transcript))for tc in acc_tool_calls.values():final_contents.append(ToolCallBlock(id=tc["id"], name=tc["name"], input=tc["input"]),)+ if acc_audio_data:+ final_contents.append(+ DataBlock(+ source=Base64Source(+ data=acc_audio_data,+ media_type=f"audio/{audio_format}",+ ),+ ),+ )_final_kwargs: dict[str, Any] = {"content": final_contents,@@ -340,6 +398,7 @@ class OpenAIChatModel(ChatModelBase):self,start_datetime: datetime,response: ChatCompletion,+ audio_format: str = "wav",) -> ChatResponse:"""Parse the OpenAI Chat non-streaming response.@@ -348,12 +407,17 @@ class OpenAIChatModel(ChatModelBase):The start datetime of the response generation.response (`ChatCompletion`):The OpenAI chat completion object.+ audio_format (`str`, defaults to ``"wav"``):+ The audio format requested (used to set the media type on+ the output ``DataBlock``).Returns:`ChatResponse`:A single ``ChatResponse`` with ``is_last=True``."""- content_blocks: List[TextBlock | ToolCallBlock | ThinkingBlock] = []+ content_blocks: List[+ TextBlock | ToolCallBlock | ThinkingBlock | DataBlock+ ] = []if response.choices:choice = response.choices[0]@@ -366,6 +430,30 @@ class OpenAIChatModel(ChatModelBase):if choice.message.content:content_blocks.append(TextBlock(text=choice.message.content))+ # Extract audio output (message.audio.data /+ # message.audio.transcript)+ audio_obj = getattr(choice.message, "audio", None)+ if audio_obj is not None:+ if isinstance(audio_obj, dict):+ audio_data = audio_obj.get("data", "")+ audio_transcript = audio_obj.get("transcript", "")+ else:+ audio_data = getattr(audio_obj, "data", "") or ""+ audio_transcript = (+ getattr(audio_obj, "transcript", "") or ""+ )+ if not choice.message.content and audio_transcript:+ content_blocks.append(TextBlock(text=audio_transcript))+ if audio_data:+ content_blocks.append(+ DataBlock(+ source=Base64Source(+ data=audio_data,+ media_type=f"audio/{audio_format}",+ ),+ ),+ )+for tool_call in choice.message.tool_calls or []:content_blocks.append(ToolCallBlock(diff --git a/src/agentscope/model/_openai_response/_model.py b/src/agentscope/model/_openai_response/_model.pyindex 6c004b28d..d17040f5a 100644--- a/src/agentscope/model/_openai_response/_model.py+++ b/src/agentscope/model/_openai_response/_model.py@@ -22,6 +22,9 @@ else:ResponseStreamEvent = AnyAsyncStream = Any+# kwargs accepted by Chat Completions but NOT by the Responses API.+_RESPONSES_UNSUPPORTED_KWARGS = frozenset({"modalities", "audio"})+class OpenAIResponseModel(ChatModelBase):"""The OpenAI Responses API chat model.@@ -176,7 +179,18 @@ class OpenAIResponseModel(ChatModelBase):"effort": self.parameters.reasoning_effort,}- api_kwargs.update(generate_kwargs)+ # The Responses API does not yet support audio output+ # (modalities / audio params). Strip them so callers that+ # mistakenly pass Chat-Completions-style audio kwargs don't+ # trigger a TypeError.+ # https://developers.openai.com/api/docs/guides/migrate-to-responses+ api_kwargs.update(+ {+ k: v+ for k, v in generate_kwargs.items()+ if k not in _RESPONSES_UNSUPPORTED_KWARGS+ },+ )fmt_tools, fmt_tool_choice = self._format_tools(tools, tool_choice)if fmt_tools is not None:diff --git a/tests/model_openai_chat_test.py b/tests/model_openai_chat_test.pyindex 9dc9fccbd..31e36e376 100644--- a/tests/model_openai_chat_test.py+++ b/tests/model_openai_chat_test.py@@ -14,7 +14,13 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom utils import AnyString-from agentscope.message import TextBlock, ToolCallBlock, ThinkingBlock+from agentscope.message import (+ TextBlock,+ ToolCallBlock,+ ThinkingBlock,+ DataBlock,+ Base64Source,+)from agentscope.model import OpenAIChatModelfrom agentscope.credential import OpenAICredentialfrom agentscope.tool import ToolChoice@@ -41,12 +47,14 @@ def _mock_completion(tool_calls: Any = None,reasoning: Any = None,response_id: str = "resp-1",+ audio: dict | None = None,) -> MagicMock:"""Build a mock non-streaming ChatCompletion response."""msg = MagicMock()msg.content = textmsg.reasoning_content = reasoningmsg.reasoning = None+ msg.audio = audiomsg.tool_calls = Noneif tool_calls:@@ -78,6 +86,7 @@ def _make_stream_chunk(response_id: str = "resp-1",usage: dict | None = None,has_choices: bool = True,+ delta_audio: dict | None = None,) -> MagicMock:"""Build a single mock streaming chunk."""chunk = MagicMock()@@ -96,6 +105,7 @@ def _make_stream_chunk(delta.content = delta_textdelta.reasoning_content = delta_reasoningdelta.reasoning = None+ delta.audio = delta_audiodelta.tool_calls = tool_callschoice = MagicMock()choice.delta = delta@@ -207,6 +217,47 @@ class TestOpenAIChatNonStream(IsolatedAsyncioTestCase):),)+ @patch("openai.AsyncClient")+ async def test_audio_response(+ self,+ mock_client_cls: MagicMock,+ ) -> None:+ """Non-stream audio-only output yields transcript TextBlock + audio+ DataBlock."""+ mock_create = AsyncMock(+ return_value=_mock_completion(+ text=None,+ audio={+ "data": "QUJDREVG",+ "transcript": "Hello from audio.",+ },+ ),+ )+ mock_client_cls.return_value.chat.completions.create = mock_create++ result = await self.model([])++ self.assertEqual(+ (result.is_last, result.content),+ (+ True,+ [+ TextBlock.model_construct(+ id=A,+ text="Hello from audio.",+ ),+ DataBlock.model_construct(+ id=A,+ source=Base64Source.model_construct(+ type="base64",+ media_type="audio/wav",+ data="QUJDREVG",+ ),+ ),+ ],+ ),+ )+@patch("openai.AsyncClient")async def test_thinking_response(self,@@ -421,6 +472,55 @@ class TestOpenAIChatStream(IsolatedAsyncioTestCase):self.assertEqual(responses[-1].usage.input_tokens, 100)self.assertEqual(responses[-1].usage.output_tokens, 20)+ @patch("openai.AsyncClient")+ async def test_stream_audio_response(+ self,+ mock_client_cls: MagicMock,+ ) -> None:+ """Stream audio deltas accumulate into a final DataBlock with the+ concatenated base64 payload and a transcript TextBlock."""+ chunks = [+ _make_stream_chunk(+ delta_audio={"data": "AAAA", "transcript": "Hello"},+ ),+ _make_stream_chunk(+ delta_audio={"data": "BBBB", "transcript": " world"},+ ),+ _make_stream_chunk(+ delta_audio={"data": "CCCC", "transcript": "!"},+ ),+ _make_stream_chunk(+ has_choices=False,+ usage={"prompt_tokens": 10, "completion_tokens": 6},+ ),+ ]+ mock_create = AsyncMock(return_value=_MockAsyncStream(chunks))+ mock_client_cls.return_value.chat.completions.create = mock_create++ gen = await self.model([])+ responses = [r async for r in gen]++ # Only the final response carries the assembled audio content; the+ # per-chunk deltas have no text/thinking/tool_call so no delta+ # ChatResponse is yielded mid-stream.+ self.assertEqual(len(responses), 1)+ final = responses[0]+ self.assertTrue(final.is_last)+ self.assertEqual(+ final.content,+ [+ TextBlock.model_construct(id=A, text="Hello world!"),+ DataBlock.model_construct(+ id=A,+ source=Base64Source.model_construct(+ type="base64",+ media_type="audio/wav",+ data="AAAABBBBCCCC",+ ),+ ),+ ],+ )+class TestOpenAIChatModelParameters(unittest.TestCase):"""Tests for OpenAIChatModel.Parameters."""