azure-ai-voicelive-py

द्वारा microsoft

Azure AI Voice Live SDK (azure-ai-voicelive) का उपयोग करके रीयल-टाइम वॉयस AI एप्लिकेशन बनाएं। इस कौशल का उपयोग तब करें जब Python एप्लिकेशन बनाए जा रहे हों जिन्हें रीयल-टाइम…

npx skills add https://github.com/microsoft/skills --skill azure-ai-voicelive-py

Azure AI Voice Live SDK

Build real-time voice AI applications with bidirectional WebSocket communication.

Installation

pip install azure-ai-voicelive aiohttp azure-identity

Environment Variables

AZURE_COGNITIVE_SERVICES_ENDPOINT=https://<region>.api.cognitive.microsoft.com  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
AZURE_COGNITIVE_SERVICES_KEY=<api-key>  # Only required for the legacy API-key auth path below

Authentication & Lifecycle

🔑 Two rules apply to every code sample below:

  1. Prefer DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
    • Local dev: DefaultAzureCredential works as-is.
    • Production: set AZURE_TOKEN_CREDENTIALS=prod (or AZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.
  2. Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
    • Sync: with <Client>(...) as client:
    • Async: async with <Client>(...) as client: and async with DefaultAzureCredential() as credential: (from azure.identity.aio)

Snippets may abbreviate this setup, but production code should always follow both rules.

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

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

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

Legacy: API Key (existing keyed deployments)

New code should use DefaultAzureCredential above. Use AzureKeyCredential only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.voicelive.aio import connect

async with connect(
    endpoint=os.environ["AZURE_COGNITIVE_SERVICES_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["AZURE_COGNITIVE_SERVICES_KEY"]),
    model="gpt-4o-realtime-preview",
) as conn:
    ...

Quick Start

import asyncio
import 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:
        # Update session with instructions
        await conn.session.update(session={
            "instructions": "You are a helpful assistant.",
            "modalities": ["text", "audio"],
            "voice": "alloy"
        })
        
        # Listen for events
        async for event in conn:
            print(f"Event: {event.type}")
            if event.type == "response.audio_transcript.done":
                print(f"Transcript: {event.transcript}")
            elif event.type == "response.done":
                break

asyncio.run(main())

Core Architecture

Connection Resources

The VoiceLiveConnection exposes these resources:

ResourcePurposeKey Methods
conn.sessionSession configurationupdate(session=...)
conn.responseModel responsescreate(), cancel()
conn.input_audio_bufferAudio inputappend(), commit(), clear()
conn.output_audio_bufferAudio outputclear()
conn.conversationConversation stateitem.create(), item.delete(), item.truncate()
conn.transcription_sessionTranscription configupdate(session=...)

Session Configuration

from azure.ai.voicelive.models import RequestSession, FunctionTool

await conn.session.update(session=RequestSession(
    instructions="You are a helpful voice assistant.",
    modalities=["text", "audio"],
    voice="alloy",  # or "echo", "shimmer", "sage", etc.
    input_audio_format="pcm16",
    output_audio_format="pcm16",
    turn_detection={
        "type": "server_vad",
        "threshold": 0.5,
        "prefix_padding_ms": 300,
        "silence_duration_ms": 500
    },
    tools=[
        FunctionTool(
            type="function",
            name="get_weather",
            description="Get current weather",
            parameters={
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                },
                "required": ["location"]
            }
        )
    ]
))

Audio Streaming

Send Audio (Base64 PCM16)

import base64

# Read audio chunk (16-bit PCM, 24kHz mono)
audio_chunk = await read_audio_from_microphone()
b64_audio = base64.b64encode(audio_chunk).decode()

await conn.input_audio_buffer.append(audio=b64_audio)

Receive Audio

async for event in conn:
    if event.type == "response.audio.delta":
        audio_bytes = base64.b64decode(event.delta)
        await play_audio(audio_bytes)
    elif event.type == "response.audio.done":
        print("Audio complete")

Event Handling

async for event in conn:
    match event.type:
        # Session events
        case "session.created":
            print(f"Session: {event.session}")
        case "session.updated":
            print("Session updated")
        
        # Audio input events
        case "input_audio_buffer.speech_started":
            print(f"Speech started at {event.audio_start_ms}ms")
        case "input_audio_buffer.speech_stopped":
            print(f"Speech stopped at {event.audio_end_ms}ms")
        
        # Transcription events
        case "conversation.item.input_audio_transcription.completed":
            print(f"User said: {event.transcript}")
        case "conversation.item.input_audio_transcription.delta":
            print(f"Partial: {event.delta}")
        
        # Response events
        case "response.created":
            print(f"Response started: {event.response.id}")
        case "response.audio_transcript.delta":
            print(event.delta, end="", flush=True)
        case "response.audio.delta":
            audio = base64.b64decode(event.delta)
        case "response.done":
            print(f"Response complete: {event.response.status}")
        
        # Function calls
        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()
        
        # Errors
        case "error":
            print(f"Error: {event.error.message}")

Common Patterns

Manual Turn Mode (No VAD)

await conn.session.update(session={"turn_detection": None})

# Manually control turns
await conn.input_audio_buffer.append(audio=b64_audio)
await conn.input_audio_buffer.commit()  # End of user turn
await conn.response.create()  # Trigger response

Interrupt Handling

async for event in conn:
    if event.type == "input_audio_buffer.speech_started":
        # User interrupted - cancel current response
        await conn.response.cancel()
        await conn.output_audio_buffer.clear()

Conversation History

# Add system message
await conn.conversation.item.create(item={
    "type": "message",
    "role": "system",
    "content": [{"type": "input_text", "text": "Be concise."}]
})

# Add user message
await conn.conversation.item.create(item={
    "type": "message",
    "role": "user", 
    "content": [{"type": "input_text", "text": "Hello!"}]
})

await conn.response.create()

Voice Options

VoiceDescription
alloyNeutral, balanced
echoWarm, conversational
shimmerClear, professional
sageCalm, authoritative
coralFriendly, upbeat
ashDeep, measured
balladExpressive
verseStorytelling

Azure voices: Use AzureStandardVoice, AzureCustomVoice, or AzurePersonalVoice models.

Audio Formats

FormatSample RateUse Case
pcm1624kHzDefault, high quality
pcm16-8000hz8kHzTelephony
pcm16-16000hz16kHzVoice assistants
g711_ulaw8kHzTelephony (US)
g711_alaw8kHzTelephony (EU)

Turn Detection Options

# Server VAD (default)
{"type": "server_vad", "threshold": 0.5, "silence_duration_ms": 500}

# Azure Semantic VAD (smarter detection)
{"type": "azure_semantic_vad"}
{"type": "azure_semantic_vad_en"}  # English optimized
{"type": "azure_semantic_vad_multilingual"}

Error Handling

from azure.ai.voicelive.aio import ConnectionError, ConnectionClosed

try:
    async with connect(...) as conn:
        async for event in conn:
            if event.type == "error":
                print(f"API Error: {event.error.code} - {event.error.message}")
except ConnectionClosed as e:
    print(f"Connection closed: {e.code} - {e.reason}")
except ConnectionError as e:
    print(f"Connection error: {e}")

Best Practices

  1. This SDK is async-only; use azure.ai.voicelive.aio throughout. Do not try to pair it with sync clients from other Azure SDKs in the same call path — keep the whole request path async.
  2. Always use context managers for clients and async credentials. Wrap every connection in async with connect(...) as conn:. For async DefaultAzureCredential from azure.identity.aio, also use async with credential: so tokens and transports are cleaned up.

References

microsoft की और Skills

oss-growth
microsoft
OSS ग्रोथ हैकर व्यक्तित्व
official
microsoft-foundry
microsoft
Foundry एजेंटों को एंड-टू-एंड डिप्लॉय, मूल्यांकन और प्रबंधित करें: Docker बिल्ड, ACR पुश, होस्टेड/प्रॉम्प्ट एजेंट क्रिएट, कंटेनर स्टार्ट, बैच इवैल्यूएशन, कंटीन्यूअस इवैल्यूएशन, प्रॉम्प्ट ऑप्टिमाइज़र वर्कफ़्लो, agent.yaml, ट्रेस से डेटासेट क्यूरेशन। इसका उपयोग करें: Foundry पर एजेंट डिप्लॉय करना, होस्टेड एजेंट, एजेंट बनाना, एजेंट को इनवोक करना, एजेंट का मूल्यांकन
officialdevelopmentdevops
azure-ai
microsoft
Azure AI के लिए उपयोग करें: खोज, वाक्, OpenAI, दस्तावेज़ बुद्धिमत्ता। खोज, वेक्टर/हाइब्रिड खोज, वाक्-से-पाठ, पाठ-से-वाक्, प्रतिलेखन, OCR में सहायता करता है। कब उपयोग करें: AI खोज, क्वेरी खोज, वेक्टर खोज, हाइब्रिड खोज, सिमैंटिक खोज, वाक्-से-पाठ, पाठ-से-वाक्, प्रतिलेखन, OCR, पाठ को वाक् में बदलना।
officialdevelopmentapi
azure-deploy
microsoft
पहले से तैयार एप्लिकेशनों के लिए Azure डिप्लॉयमेंट निष्पादित करें जिनमें मौजूदा .azure/deployment-plan.md और इंफ्रास्ट्रक्चर फ़ाइलें हों। इस स्किल का उपयोग तब न करें जब उपयोगकर्ता कोई नया एप्लिकेशन बनाने के लिए कहे — इसके बजाय azure-prepare का उपयोग करें। यह स्किल azd up, azd deploy, terraform apply, और az deployment कमांड को बिल्ट-इन एरर रिकवरी के साथ चलाती है। इसके लिए azure-prepare से .azure/deployment-plan.md और azure-validate से सत्यापित स्थिति आवश्यक है। कब: "azd
officialdevopsaws
azure-storage
microsoft
Azure Storage सेवाएँ जिनमें Blob Storage, File Shares, Queue Storage, Table Storage और Data Lake शामिल हैं। स्टोरेज एक्सेस टियर (हॉट, कूल, कोल्ड, आर्काइव), प्रत्येक टियर का उपयोग कब करें और टियर तुलना के बारे में प्रश्नों के उत्तर देता है। ऑब्जेक्ट स्टोरेज, SMB फ़ाइल शेयर, एसिंक्रोनस मैसेजिंग, NoSQL की-वैल्यू और बिग डेटा एनालिटिक्स प्रदान करता है। लाइफसाइकिल प्रबंधन शामिल है। उपयोग करें: ब्लॉब स्टोरेज, फ़ाइल शेयर, क्य
officialdevelopmentdatabase
azure-diagnostics
microsoft
Azure पर AppLens, Azure Monitor, संसाधन स्वास्थ्य और सुरक्षित ट्राइएज का उपयोग करके Azure उत्पादन समस्याओं को डीबग करें। कब: उत्पादन समस्याओं को डीबग करना, ऐप सेवा समस्या निवारण, ऐप सेवा उच्च CPU, ऐप सेवा परिनियोजन विफलता, कंटेनर ऐप्स समस्या निवारण, फंक्शन्स समस्या निवारण, AKS समस्या निवारण, kubectl कनेक्ट नहीं हो सकता, kube-system/CoreDNS विफलताएँ, पॉड लंबित, क्रैशलूप, नोड तैयार नहीं, अपग्रेड विफ
officialdevopsdevelopment
azure-prepare
microsoft
Azure ऐप्स को तैनाती के लिए तैयार करें (infra Bicep/Terraform, azure.yaml, Dockerfiles)। निर्माण/आधुनिकीकरण या निर्माण+तैनाती के लिए उपयोग करें; क्रॉस-क्लाउड माइग्रेशन के लिए नहीं (azure-cloud-migrate का उपयोग करें)। इसका उपयोग न करें: copilot-sdk ऐप्स के लिए (azure-hosted-copilot-sdk का उपयोग करें)। कब: "create app", "build web app", "create API", "create serverless HTTP API", "create frontend", "create back end", "build a service", "modernize application", "update application", "add authentication", "add caching", "host on Azure", "create and...
officialdevelopmentdevops
azure-validate
microsoft
Azure तैनाती-पूर्व तत्परता के लिए सत्यापन। तैनाती से पहले कॉन्फ़िगरेशन, इंफ्रास्ट्रक्चर (Bicep या Terraform), RBAC भूमिका असाइनमेंट, प्रबंधित पहचान अनुमतियाँ और पूर्वापेक्षाओं की गहन जाँच करें। कब: मेरे ऐप को सत्यापित करें, तैनाती तत्परता की जाँच करें, प्रीफ्लाइट जाँच चलाएँ, कॉन्फ़िगरेशन सत्यापित करें, तैनाती के लिए तैयार है या नहीं जाँचें, azure.yaml सत्यापित करें, Bicep सत्यापित
officialdevopstesting