你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于语音和音频的 GPT-4o 实时 API(预览版)

注意

此功能目前处于公开预览状态。 此预览版未提供服务级别协议,不建议将其用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

适用于语音和音频的 Azure OpenAI GPT-4o 实时 API 是 GPT-4o 模型系列的一部分,该系列支持低延迟的“语音传入,语音传出”对话交互。

可以通过 WebRTC 或 WebSocket 使用实时 API 将音频输入发送到模型并实时接收音频响应。

按照本文中的说明通过 WebSocket 开始使用实时 API。 在不需要低延迟的服务器到服务器方案中通过 WebSocket 使用实时 API。

提示

在大多数情况下,我们建议 通过 WebRTC 使用实时 API 在客户端应用程序(如 Web 应用程序或移动应用)中实时音频流式处理。 WebRTC 专为低延迟、实时音频流式处理而设计,最适合大多数用例。

支持的模型

GPT 4o 实时模型可用于全局部署。

  • gpt-4o-realtime-preview(版本 2024-12-17
  • gpt-4o-mini-realtime-preview(版本 2024-12-17

有关详细信息,请参阅模型和版本文档

API 支持

首次在 API 版本 2024-10-01-preview (已停用)中添加对实时 API 的支持。 使用版本 2025-04-01-preview 访问最新的实时 API 功能。

为实时音频部署模型

若要在 Azure AI Foundry 门户中部署 gpt-4o-mini-realtime-preview 模型,请执行以下操作:

  1. 转到 Azure AI Foundry 门户 ,创建或选择项目。
  2. 从左窗格中的“我的资产”下选择“模型 + 终结点”。
  3. 选择 “+ 部署模型>部署基本模型 ”以打开部署窗口。
  4. 搜索并选择 gpt-4o-mini-realtime-preview 模型,然后选择“确认”。
  5. 查看部署详细信息,然后选择“ 部署”。
  6. 按照向导完成模型部署。

现在您已经部署了模型 gpt-4o-mini-realtime-preview,可以在 Azure AI Foundry 门户中的 音频 游乐场或实时 API 中与其交互。

使用 GPT-4o 实时音频

若要在 gpt-4o-mini-realtime-preview 实时音频操场中与已部署的 模型聊天,请按照以下步骤操作:

  1. 转到 Azure AI Foundry 门户,选择具有已部署模型的项目。

  2. 从左窗格中选择“游乐场地”

  3. 选择音频游乐场>试用音频游乐场

    注意

    聊天实验室不支持gpt-4o-mini-realtime-preview模型。 使用本节中所述的音频操场

  4. 从“部署”gpt-4o-mini-realtime-preview下拉列表中选择部署的 模型。

    音频操场的屏幕截图,其中选择了已部署的模型。

  5. (可选)你可以在“为模型提供指令和上下文”文本框中编辑内容。 为模型提供有关它应该如何运行以及在生成回复时应引用的任何上下文的说明。 你可以描述助手的个性,告诉它应该回答什么和不应该回答什么,并告诉它如何设置回复的格式。

  6. (可选)更改阈值、前缀填充和静音持续时间等设置。

  7. 选择“开始收听”以启动会话。 可以对着麦克风说话来开始聊天。

  8. 可以随时通过说话来中断聊天。 可以通过选择“停止收听”按钮来结束聊天。

先决条件

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User角色分配给用户帐户。 你可以在 Azure 门户的“访问控制(IAM)”“添加角色分配”下分配角色。>

为实时音频部署模型

若要在 Azure AI Foundry 门户中部署 gpt-4o-mini-realtime-preview 模型,请执行以下操作:

  1. 转到 Azure AI Foundry 门户 ,创建或选择项目。
  2. 从左窗格中的“我的资产”下选择“模型 + 终结点”。
  3. 选择 “+ 部署模型>部署基本模型 ”以打开部署窗口。
  4. 搜索并选择 gpt-4o-mini-realtime-preview 模型,然后选择“确认”。
  5. 查看部署详细信息,然后选择“ 部署”。
  6. 按照向导完成模型部署。

现在您已经部署了模型 gpt-4o-mini-realtime-preview,可以在 Azure AI Foundry 门户中的 音频 游乐场或实时 API 中与其交互。

设置

  1. 创建新文件夹 realtime-audio-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir realtime-audio-quickstart && cd realtime-audio-quickstart
    
  2. 使用以下命令创建 package.json

    npm init -y
    
  3. 使用以下命令安装适用于 JavaScript 的 OpenAI 客户端库:

    npm install openai
    
  4. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令安装 包:@azure/identity

    npm install @azure/identity
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

注意

若要对 SDK 使用推荐的无密钥身份验证,请确保未设置 AZURE_OPENAI_API_KEY 环境变量。

音频输出中的文本

  1. 使用以下代码创建 index.js 文件:

    import { OpenAIRealtimeWS } from "openai/beta/realtime/ws";
    import { AzureOpenAI } from "openai";
    import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
    async function main() {
        // You will need to set these environment variables or edit the following values
        const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "AZURE_OPENAI_ENDPOINT";
        // Required Azure OpenAI deployment name and API version
        const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4o-mini-realtime-preview";
        const apiVersion = process.env.OPENAI_API_VERSION || "2025-04-01-preview";
        // Keyless authentication 
        const credential = new DefaultAzureCredential();
        const scope = "https://cognitiveservices.azure.com/.default";
        const azureADTokenProvider = getBearerTokenProvider(credential, scope);
        const azureOpenAIClient = new AzureOpenAI({
            azureADTokenProvider,
            apiVersion: apiVersion,
            deployment: deploymentName,
            endpoint: endpoint,
        });
        const realtimeClient = await OpenAIRealtimeWS.azure(azureOpenAIClient);
        realtimeClient.socket.on("open", () => {
            console.log("Connection opened!");
            realtimeClient.send({
                type: "session.update",
                session: {
                    modalities: ["text", "audio"],
                    model: "gpt-4o-mini-realtime-preview",
                },
            });
            realtimeClient.send({
                type: "conversation.item.create",
                item: {
                    type: "message",
                    role: "user",
                    content: [{ type: "input_text", text: "Please assist the user" }],
                },
            });
            realtimeClient.send({ type: "response.create" });
        });
        realtimeClient.on("error", (err) => {
            // Instead of throwing the error, you can log it
            // and continue processing events.
            throw err;
        });
        realtimeClient.on("session.created", (event) => {
            console.log("session created!", event.session);
            console.log();
        });
        realtimeClient.on("response.text.delta", (event) => process.stdout.write(event.delta));
        realtimeClient.on("response.audio.delta", (event) => {
            const buffer = Buffer.from(event.delta, "base64");
            console.log(`Received ${buffer.length} bytes of audio data.`);
        });
        realtimeClient.on("response.audio_transcript.delta", (event) => {
            console.log(`Received text delta:${event.delta}.`);
        });
        realtimeClient.on("response.text.done", () => console.log());
        realtimeClient.on("response.done", () => realtimeClient.close());
        realtimeClient.socket.on("close", () => console.log("\nConnection closed!"));
    }
    main().catch((err) => {
        console.error("The sample encountered an error:", err);
    });
    export { main };
    
  2. 使用以下命令登录到 Azure:

    az login
    
  3. 运行 JavaScript 文件。

    node index.js
    

片刻之后即可获得响应。

输出

该脚本将从模型获取响应,并打印收到的脚本和音频数据。

输出将类似于以下内容:

Received text delta:Of.
Received text delta: course.
Received text delta:!.
Received text delta: How.
Received text delta: can.
Received 4800 bytes of audio data.
Received 7200 bytes of audio data.
Received text delta: I.
Received 12000 bytes of audio data.
Received text delta: help.
Received text delta: you.
Received text delta: today.
Received text delta:?.
Received 12000 bytes of audio data.
Received 12000 bytes of audio data.
Received 12000 bytes of audio data.
Received 26400 bytes of audio data.

Connection closed!

先决条件

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User角色分配给用户帐户。 你可以在 Azure 门户的“访问控制(IAM)”“添加角色分配”下分配角色。>

为实时音频部署模型

若要在 Azure AI Foundry 门户中部署 gpt-4o-mini-realtime-preview 模型,请执行以下操作:

  1. 转到 Azure AI Foundry 门户 ,创建或选择项目。
  2. 从左窗格中的“我的资产”下选择“模型 + 终结点”。
  3. 选择 “+ 部署模型>部署基本模型 ”以打开部署窗口。
  4. 搜索并选择 gpt-4o-mini-realtime-preview 模型,然后选择“确认”。
  5. 查看部署详细信息,然后选择“ 部署”。
  6. 按照向导完成模型部署。

现在您已经部署了模型 gpt-4o-mini-realtime-preview,可以在 Azure AI Foundry 门户中的 音频 游乐场或实时 API 中与其交互。

设置

  1. 创建新文件夹 realtime-audio-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir realtime-audio-quickstart && cd realtime-audio-quickstart
    
  2. 创建虚拟环境。 如果已安装 Python 3.10 或更高版本,则可以使用以下命令创建虚拟环境:

    py -3 -m venv .venv
    .venv\scripts\activate
    

    激活 Python 环境意味着当通过命令行运行 pythonpip 时,你将使用应用程序的 .venv 文件夹中包含的 Python 解释器。 可以使用 deactivate 命令退出 python 虚拟环境,并在需要时重新激活它。

    提示

    建议你创建并激活一个新的 Python 环境,用于安装本教程所需的包。 请勿将包安装到你的全局 Python 安装中。 安装 Python 包时,请务必使用虚拟或 Conda 环境,否则可能会中断 Python 的全局安装。

  3. 使用以下项安装 OpenAI Python 客户端库:

    pip install openai[realtime]
    

    注意

    此库由 OpenAI 维护。 请参阅发布历史记录,以跟踪库的最新更新。

  4. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令安装 包:azure-identity

    pip install azure-identity
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

注意

若要对 SDK 使用推荐的无密钥身份验证,请确保未设置 AZURE_OPENAI_API_KEY 环境变量。

音频输出中的文本

  1. 使用以下代码创建 text-in-audio-out.py 文件:

    import os
    import base64
    import asyncio
    from openai import AsyncAzureOpenAI
    from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider
    
    async def main() -> None:
        """
        When prompted for user input, type a message and hit enter to send it to the model.
        Enter "q" to quit the conversation.
        """
    
        credential = DefaultAzureCredential()
        token_provider=get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
        client = AsyncAzureOpenAI(
            azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
            azure_ad_token_provider=token_provider,
            api_version="2025-04-01-preview",
        )
        async with client.beta.realtime.connect(
            model="gpt-4o-realtime-preview",  # name of your deployment
        ) as connection:
            await connection.session.update(session={"modalities": ["text", "audio"]})  
            while True:
                user_input = input("Enter a message: ")
                if user_input == "q":
                    break
    
                await connection.conversation.item.create(
                    item={
                        "type": "message",
                        "role": "user",
                        "content": [{"type": "input_text", "text": user_input}],
                    }
                )
                await connection.response.create()
                async for event in connection:
                    if event.type == "response.text.delta":
                        print(event.delta, flush=True, end="")
                    elif event.type == "response.audio.delta":
    
                        audio_data = base64.b64decode(event.delta)
                        print(f"Received {len(audio_data)} bytes of audio data.")
                    elif event.type == "response.audio_transcript.delta":
                        print(f"Received text delta: {event.delta}")
                    elif event.type == "response.text.done":
                        print()
                    elif event.type == "response.done":
                        break
    
        await credential.close()
    
    asyncio.run(main())
    
  2. 使用以下命令登录到 Azure:

    az login
    
  3. 运行该 Python 文件。

    python text-in-audio-out.py
    
  4. 出现用户输入提示时,键入消息并按 Enter 将其发送到模型。 输入“q”退出对话。

片刻之后即可获得响应。

输出

该脚本将从模型获取响应,并打印收到的脚本和音频数据。

输出如下所示:

Enter a message: Please assist the user
Received text delta: Of
Received text delta:  course
Received text delta: !
Received text delta:  How
Received 4800 bytes of audio data.
Received 7200 bytes of audio data.
Received 12000 bytes of audio data.
Received text delta:  can
Received text delta:  I
Received text delta:  assist
Received 12000 bytes of audio data.
Received 12000 bytes of audio data.
Received text delta:  you
Received text delta:  today
Received text delta: ?
Received 12000 bytes of audio data.
Received 24000 bytes of audio data.
Received 36000 bytes of audio data.
Enter a message: q

先决条件

Microsoft Entra ID 先决条件

若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,你需要:

  • 安装使用 Microsoft Entra ID 进行无密钥身份验证所需的 Azure CLI
  • Cognitive Services User角色分配给用户帐户。 你可以在 Azure 门户的“访问控制(IAM)”“添加角色分配”下分配角色。>

为实时音频部署模型

若要在 Azure AI Foundry 门户中部署 gpt-4o-mini-realtime-preview 模型,请执行以下操作:

  1. 转到 Azure AI Foundry 门户 ,创建或选择项目。
  2. 从左窗格中的“我的资产”下选择“模型 + 终结点”。
  3. 选择 “+ 部署模型>部署基本模型 ”以打开部署窗口。
  4. 搜索并选择 gpt-4o-mini-realtime-preview 模型,然后选择“确认”。
  5. 查看部署详细信息,然后选择“ 部署”。
  6. 按照向导完成模型部署。

现在您已经部署了模型 gpt-4o-mini-realtime-preview,可以在 Azure AI Foundry 门户中的 音频 游乐场或实时 API 中与其交互。

设置

  1. 创建新文件夹 realtime-audio-quickstart,并使用以下命令转到快速入门文件夹:

    mkdir realtime-audio-quickstart && cd realtime-audio-quickstart
    
  2. 使用以下命令创建 package.json

    npm init -y
    
  3. 使用以下命令将 package.json 更新为 ECMAScript:

    npm pkg set type=module
    
  4. 使用以下命令安装适用于 JavaScript 的 OpenAI 客户端库:

    npm install openai
    
  5. 若要使用 Microsoft Entra ID 进行推荐的无密钥身份验证,请使用以下命令安装 包:@azure/identity

    npm install @azure/identity
    

检索资源信息

需要检索以下信息才能使用 Azure OpenAI 资源对应用程序进行身份验证:

变量名称
AZURE_OPENAI_ENDPOINT 从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。
AZURE_OPENAI_DEPLOYMENT_NAME 此值将对应于在部署模型时为部署选择的自定义名称。 Azure 门户中的“资源管理”“模型部署”下提供了此值。>
OPENAI_API_VERSION 详细了解 API 版本

可以在代码中更改版本或使用环境变量。

详细了解无密钥身份验证,以及如何设置环境变量

注意

若要对 SDK 使用推荐的无密钥身份验证,请确保未设置 AZURE_OPENAI_API_KEY 环境变量。

音频输出中的文本

  1. 使用以下代码创建 index.ts 文件:

    import { OpenAIRealtimeWS } from "openai/beta/realtime/ws";
    import { AzureOpenAI } from "openai";
    import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
    
    async function main(): Promise<void> {
    
        // You will need to set these environment variables or edit the following values
        const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "AZURE_OPENAI_ENDPOINT";
    
        // Required Azure OpenAI deployment name and API version
        const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "gpt-4o-mini-realtime-preview";
        const apiVersion = process.env.OPENAI_API_VERSION || "2025-04-01-preview"; 
    
        // Keyless authentication 
        const credential = new DefaultAzureCredential();
        const scope = "https://cognitiveservices.azure.com/.default";
        const azureADTokenProvider = getBearerTokenProvider(credential, scope);
    
        const azureOpenAIClient = new AzureOpenAI({
            azureADTokenProvider,
            apiVersion: apiVersion,
            deployment: deploymentName,
            endpoint: endpoint,
        });
    
        const realtimeClient = await OpenAIRealtimeWS.azure(azureOpenAIClient);
    
        realtimeClient.socket.on("open", () => {
            console.log("Connection opened!");
            realtimeClient.send({
            type: "session.update",
            session: {
                modalities: ["text", "audio"],
                model: "gpt-4o-mini-realtime-preview",
            },
            });
            realtimeClient.send({
            type: "conversation.item.create",
            item: {
                type: "message",
                role: "user",
                content: [{ type: "input_text", text: "Please assist the user" }],
            },
            });
            realtimeClient.send({ type: "response.create" });
        });
        realtimeClient.on("error", (err) => {
            // Instead of throwing the error, you can log it
            // and continue processing events.
            throw err;
        });
        realtimeClient.on("session.created", (event) => {
            console.log("session created!", event.session);
            console.log();
        });
        realtimeClient.on("response.text.delta", (event) => process.stdout.write(event.delta));
        realtimeClient.on("response.audio.delta", (event) => {
            const buffer = Buffer.from(event.delta, "base64");
            console.log(`Received ${buffer.length} bytes of audio data.`);
        });
        realtimeClient.on("response.audio_transcript.delta", (event) => {
            console.log(`Received text delta:${event.delta}.`);
        });
        realtimeClient.on("response.text.done", () => console.log());
        realtimeClient.on("response.done", () => realtimeClient.close());
        realtimeClient.socket.on("close", () => console.log("\nConnection closed!"));
    }
    
    main().catch((err) => {
        console.error("The sample encountered an error:", err);
    });
    
    export { main };
    
  2. 创建 tsconfig.json 文件以转译 TypeScript 代码,然后复制以下 ECMAScript 代码。

    {
        "compilerOptions": {
          "module": "NodeNext",
          "target": "ES2022", // Supports top-level await
          "moduleResolution": "NodeNext",
          "skipLibCheck": true, // Avoid type errors from node_modules
          "strict": true // Enable strict type-checking options
        },
        "include": ["*.ts"]
    }
    
  3. 从 TypeScript 转译到 JavaScript。

    tsc
    
  4. 使用以下命令登录到 Azure:

    az login
    
  5. 使用以下命令运行代码:

    node index.js
    

片刻之后即可获得响应。

输出

该脚本将从模型获取响应,并打印收到的脚本和音频数据。

输出将类似于以下内容:

Received text delta:Of.
Received text delta: course.
Received text delta:!.
Received text delta: How.
Received text delta: can.
Received 4800 bytes of audio data.
Received 7200 bytes of audio data.
Received text delta: I.
Received 12000 bytes of audio data.
Received text delta: help.
Received text delta: you.
Received text delta: today.
Received text delta:?.
Received 12000 bytes of audio data.
Received 12000 bytes of audio data.
Received 12000 bytes of audio data.
Received 26400 bytes of audio data.

Connection closed!