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