Skip to content

Commit 84f2f9c

Browse files
docs(examples/azure): example script with realtime API (#1967)
1 parent c16f58e commit 84f2f9c

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: examples/realtime/azure_realtime.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import os
2+
import asyncio
3+
4+
from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider
5+
6+
from 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+
15+
async 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+
57+
asyncio.run(main())

0 commit comments

Comments
 (0)