Azure realtime voice ai

From findscripter/everything-skills · View interactive version

Azure realtime voice ai is an AI agent skill from the GitHub repository findscripter/everything-skills. 当需用 Azure AI VoiceLive SDK(Python)通过 WebSocket 构建低延迟双向语音对话、实时语音助手或电话语音机器人时使用;做的事:建立异步连接、配置 session/语音/VAD、流式收发 PCM16 音频、处理事件与函数调用,产出可运行的实时语音应用骨架;不适用于:非 Azure 语音栈、批量离线语音转写、纯文本 LLM 对话。触发词:Azure 实时语音、VoiceLive、gpt-4o-realtime、语音助手 WebSocket

How to use this skill

Skill file

何时使用

适用场景:

不该用(负边界):

步骤

  1. 安装依赖:pip install azure-ai-voicelive aiohttp azure-identity
  2. 配置环境变量:设置端点 AZURE_COGNITIVE_SERVICES_ENDPOINT(形如 https://<region>.api.cognitive.microsoft.com);生产环境用托管身份认证,避免裸 API Key。
  3. 建立异步连接:用 connect() 异步上下文管理器,优先传 DefaultAzureCredential() 并指定 credential_scopes=["https://cognitiveservices.azure.com/.default"],传入 model。
  4. 更新 session:调 conn.session.update(session=...) 设置 instructions、modalities、voice、音频格式、turn_detection、tools。
  5. 音频收发:上行用 conn.input_audio_buffer.append(audio=b64)(Base64 PCM16);下行监听 response.audio.delta 事件并 base64.b64decode 播放。
  6. 事件循环:async for event in conn 按 event.type 分发——会话/语音起止/转写/响应/函数调用/错误。
  7. 函数调用回填:收到 response.function_call_arguments.done 后,conversation.item.create 写回 function_call_output,再 conn.response.create() 触发后续响应。
  8. 错误处理:捕获 ConnectionClosed / ConnectionError,并对 event.type == "error" 单独处理。

指令

from azure.ai.voicelive.aio import connect
from azure.identity.aio import DefaultAzureCredential

async with connect(
    endpoint=os.environ["AZURE_COGNITIVE_SERVICES_ENDPOINT"],
    credential=DefaultAzureCredential(),
    model="gpt-4o-realtime-preview",
    credential_scopes=["https://cognitiveservices.azure.com/.default"],
) as conn:
    ...

API Key 方式(不推荐生产):用 AzureKeyCredential(os.environ["AZURE_COGNITIVE_SERVICES_KEY"]) 替换 credential,可省 scopes。

| 资源 | 作用 | 关键方法 |

|------|------|---------|

| conn.session | 会话配置 | update(session=...) |

| conn.response | 模型响应 | create()、cancel() |

| conn.input_audio_buffer | 音频输入 | append()、commit()、clear() |

| conn.output_audio_buffer | 音频输出 | clear() |

| conn.conversation | 会话状态 | item.create()、item.delete()、item.truncate() |

| conn.transcription_session | 转写配置 | update(session=...) |

示例

最小可运行骨架(监听转写与响应完成):

import asyncio, os
from azure.ai.voicelive.aio import connect
from azure.identity.aio import DefaultAzureCredential

async def main():
    async with connect(
        endpoint=os.environ["AZURE_COGNITIVE_SERVICES_ENDPOINT"],
        credential=DefaultAzureCredential(),
        model="gpt-4o-realtime-preview",
        credential_scopes=["https://cognitiveservices.azure.com/.default"],
    ) as conn:
        await conn.session.update(session={
            "instructions": "你是一个乐于助人的语音助手。",
            "modalities": ["text", "audio"],
            "voice": "alloy",
        })
        async for event in conn:
            if event.type == "response.audio_transcript.done":
                print(f"转写: {event.transcript}")
            elif event.type == "response.done":
                break

asyncio.run(main())

事件分发 + 函数调用回填(核心片段):

async for event in conn:
    match event.type:
        case "input_audio_buffer.speech_started":   # 用户开始说话(可用于打断)
            await conn.response.cancel()
            await conn.output_audio_buffer.clear()
        case "conversation.item.input_audio_transcription.completed":
            print(f"用户: {event.transcript}")
        case "response.audio.delta":
            await play_audio(base64.b64decode(event.delta))
        case "response.function_call_arguments.done":
            result = handle_function(event.name, event.arguments)
            await conn.conversation.item.create(item={
                "type": "function_call_output",
                "call_id": event.call_id,
                "output": json.dumps(result),
            })
            await conn.response.create()
        case "error":
            print(f"错误: {event.error.code} - {event.error.message}")

手动断句(关闭 VAD):session.update(session={"turn_detection": None}),随后 append() → commit()(结束用户轮次) → response.create()(触发响应)。

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT License)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.