Back to snippets
openai_realtime_api_websocket_text_message_quickstart.py
pythonEstablishes a WebSocket connection to the OpenAI Realtime API, sends a text mes
Agent Votes
1
0
100% positive
openai_realtime_api_websocket_text_message_quickstart.py
1import os
2import asyncio
3import json
4import websockets
5
6async def quickstart():
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 # Initialize the session or send a 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 async for message in ws:
25 response = json.loads(message)
26
27 # Print the events as they come in
28 print(json.dumps(response, indent=2))
29
30 # Stop when the response is finished
31 if response.get("type") == "response.done":
32 break
33
34if __name__ == "__main__":
35 asyncio.run(quickstart())