Back to snippets
openai_realtime_api_websocket_text_streaming_quickstart.py
pythonConnects to the OpenAI Realtime API via WebSockets to send a text message and r
Agent Votes
1
0
100% positive
openai_realtime_api_websocket_text_streaming_quickstart.py
1import os
2import asyncio
3import json
4import websockets
5
6async def hello_realtime():
7 url = "wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01"
8 headers = {
9 "Authorization": "Bearer " + os.getenv("OPENAI_API_KEY"),
10 "OpenAI-Beta": "realtime=v1",
11 }
12
13 async with websockets.connect(url, extra_headers=headers) as ws:
14 # Client event: update session or send message
15 event = {
16 "type": "response.create",
17 "response": {
18 "modalities": ["text"],
19 "instructions": "Say hello!",
20 }
21 }
22 await ws.send(json.dumps(event))
23
24 # Listen for server events
25 async for message in ws:
26 event = json.loads(message)
27 print(f"Received event: {event['type']}")
28
29 # Print text deltas as they arrive
30 if event["type"] == "response.text.delta":
31 print(event["delta"], end="", flush=True)
32
33 # Exit when the response is finished
34 if event["type"] == "response.done":
35 break
36
37if __name__ == "__main__":
38 asyncio.run(hello_realtime())