openai/openai-python

Public

mirrored fromhttps://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.61.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/realtime/azure_realtime.py

57lines · modecode

1import os
2import asyncio
3
4from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider
5
6from openai import AsyncAzureOpenAI
7
8# Azure OpenAI Realtime Docs
9
10# How-to: https://learn.microsoft.com/azure/ai-services/openai/how-to/realtime-audio
11# Supported models and API versions: https://learn.microsoft.com/azure/ai-services/openai/how-to/realtime-audio#supported-models
12# Entra ID auth: https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity
13
14
15async def main() -> None:
16 """The following example demonstrates how to configure Azure OpenAI to use the Realtime API.
17 For an audio example, see push_to_talk_app.py and update the client and model parameter accordingly.
18
19 When prompted for user input, type a message and hit enter to send it to the model.
20 Enter "q" to quit the conversation.
21 """
22
23 credential = DefaultAzureCredential()
24 client = AsyncAzureOpenAI(
25 azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
26 azure_ad_token_provider=get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default"),
27 api_version="2024-10-01-preview",
28 )
29 async with client.beta.realtime.connect(
30 model="gpt-4o-realtime-preview", # deployment name for your model
31 ) as connection:
32 await connection.session.update(session={"modalities": ["text"]}) # type: ignore
33 while True:
34 user_input = input("Enter a message: ")
35 if user_input == "q":
36 break
37
38 await connection.conversation.item.create(
39 item={
40 "type": "message",
41 "role": "user",
42 "content": [{"type": "input_text", "text": user_input}],
43 }
44 )
45 await connection.response.create()
46 async for event in connection:
47 if event.type == "response.text.delta":
48 print(event.delta, flush=True, end="")
49 elif event.type == "response.text.done":
50 print()
51 elif event.type == "response.done":
52 break
53
54 await credential.close()
55
56
57asyncio.run(main())
58