跳转至

OpenAI TTS

OpenAITTSModel

Bases: TTSModel

OpenAI 的文本转语音模型。

Source code in src/agents/voice/models/openai_tts.py
class OpenAITTSModel(TTSModel):
    """OpenAI 的文本转语音模型。"""

    def __init__(
        self,
        model: str,
        openai_client: AsyncOpenAI,
    ):
        """创建一个新的 OpenAI 文本转语音模型。

        参数:
            model: 要使用的模型名称。
            openai_client: 要使用的 OpenAI 客户端。
        """
        self.model = model
        self._client = openai_client

    @property
    def model_name(self) -> str:
        return self.model

    async def run(self, text: str, settings: TTSModelSettings) -> AsyncIterator[bytes]:
        """运行文本转语音模型。

        参数:
            text: 要转换为语音的文本。
            settings: 用于文本转语音模型的设置。

        返回:
            音频块的迭代器。
        """
        response = self._client.audio.speech.with_streaming_response.create(
            model=self.model,
            voice=settings.voice or DEFAULT_VOICE,
            input=text,
            response_format="pcm",
            extra_body={
                "instructions": settings.instructions,
            },
        )

        async with response as stream:
            async for chunk in stream.iter_bytes(chunk_size=1024):
                yield chunk

__init__

__init__(model: str, openai_client: AsyncOpenAI)

创建一个新的 OpenAI 文本转语音模型。

参数

model: 要使用的模型名称。 openai_client: 要使用的 OpenAI 客户端。

Source code in src/agents/voice/models/openai_tts.py
def __init__(
    self,
    model: str,
    openai_client: AsyncOpenAI,
):
    """创建一个新的 OpenAI 文本转语音模型。

    参数:
        model: 要使用的模型名称。
        openai_client: 要使用的 OpenAI 客户端。
    """
    self.model = model
    self._client = openai_client

run async

run(
    text: str, settings: TTSModelSettings
) -> AsyncIterator[bytes]

运行文本转语音模型。

参数

text: 要转换为语音的文本。 settings: 用于文本转语音模型的设置。

返回

音频块的迭代器。

Source code in src/agents/voice/models/openai_tts.py
async def run(self, text: str, settings: TTSModelSettings) -> AsyncIterator[bytes]:
    """运行文本转语音模型。

    参数:
        text: 要转换为语音的文本。
        settings: 用于文本转语音模型的设置。

    返回:
        音频块的迭代器。
    """
    response = self._client.audio.speech.with_streaming_response.create(
        model=self.model,
        voice=settings.voice or DEFAULT_VOICE,
        input=text,
        response_format="pcm",
        extra_body={
            "instructions": settings.instructions,
        },
    )

    async with response as stream:
        async for chunk in stream.iter_bytes(chunk_size=1024):
            yield chunk