|
| 1 | +import asyncio |
| 2 | +import base64 |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from fastapi import FastAPI, WebSocket, WebSocketDisconnect |
| 9 | +from fastapi.responses import PlainTextResponse |
| 10 | + |
| 11 | +from agents import function_tool |
| 12 | +from agents.realtime import RealtimeAgent, RealtimeRunner, RealtimeSession |
| 13 | + |
| 14 | +logging.basicConfig(level=logging.INFO) |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +@function_tool |
| 19 | +def get_weather(city: str) -> str: |
| 20 | + """Get the weather in a city.""" |
| 21 | + return f"The weather in {city} is sunny." |
| 22 | + |
| 23 | + |
| 24 | +@function_tool |
| 25 | +def get_current_time() -> str: |
| 26 | + """Get the current time.""" |
| 27 | + from datetime import datetime |
| 28 | + |
| 29 | + return f"The current time is {datetime.now().strftime('%H:%M:%S')}" |
| 30 | + |
| 31 | + |
| 32 | +agent = RealtimeAgent( |
| 33 | + name="Twilio Assistant", |
| 34 | + instructions="You are a helpful assistant that starts every conversation with a creative greeting. Keep responses concise and friendly since this is a phone conversation.", |
| 35 | + tools=[get_weather, get_current_time], |
| 36 | +) |
| 37 | + |
| 38 | + |
| 39 | +class TwilioWebSocketManager: |
| 40 | + def __init__(self): |
| 41 | + self.active_sessions: dict[str, RealtimeSession] = {} |
| 42 | + self.session_contexts: dict[str, Any] = {} |
| 43 | + self.websockets: dict[str, WebSocket] = {} |
| 44 | + |
| 45 | + async def connect(self, websocket: WebSocket, call_sid: str): |
| 46 | + await websocket.accept() |
| 47 | + self.websockets[call_sid] = websocket |
| 48 | + logger.info(f"WebSocket connection accepted for call {call_sid}") |
| 49 | + |
| 50 | + runner = RealtimeRunner(agent) |
| 51 | + session_context = await runner.run() |
| 52 | + session = await session_context.__aenter__() |
| 53 | + self.active_sessions[call_sid] = session |
| 54 | + self.session_contexts[call_sid] = session_context |
| 55 | + |
| 56 | + # Start event processing task |
| 57 | + asyncio.create_task(self._process_events(call_sid)) |
| 58 | + |
| 59 | + async def disconnect(self, call_sid: str): |
| 60 | + logger.info(f"Disconnecting call {call_sid}") |
| 61 | + if call_sid in self.session_contexts: |
| 62 | + await self.session_contexts[call_sid].__aexit__(None, None, None) |
| 63 | + del self.session_contexts[call_sid] |
| 64 | + if call_sid in self.active_sessions: |
| 65 | + del self.active_sessions[call_sid] |
| 66 | + if call_sid in self.websockets: |
| 67 | + del self.websockets[call_sid] |
| 68 | + |
| 69 | + async def handle_twilio_message(self, call_sid: str, message: dict[str, Any]): |
| 70 | + """Handle incoming Twilio WebSocket messages""" |
| 71 | + event = message.get("event") |
| 72 | + |
| 73 | + if event == "connected": |
| 74 | + logger.info(f"Twilio media stream connected for call {call_sid}") |
| 75 | + elif event == "start": |
| 76 | + logger.info(f"Media stream started for call {call_sid}") |
| 77 | + elif event == "media": |
| 78 | + # Handle audio data from Twilio |
| 79 | + payload = message.get("media", {}) |
| 80 | + audio_data = payload.get("payload", "") |
| 81 | + if audio_data and call_sid in self.active_sessions: |
| 82 | + # Decode base64 audio and send to OpenAI |
| 83 | + try: |
| 84 | + audio_bytes = base64.b64decode(audio_data) |
| 85 | + await self.active_sessions[call_sid].send_audio(audio_bytes) |
| 86 | + except Exception as e: |
| 87 | + logger.error(f"Error processing audio for call {call_sid}: {e}") |
| 88 | + elif event == "stop": |
| 89 | + logger.info(f"Media stream stopped for call {call_sid}") |
| 90 | + |
| 91 | + async def send_audio_to_twilio(self, call_sid: str, audio_bytes: bytes): |
| 92 | + """Send audio back to Twilio""" |
| 93 | + if call_sid in self.websockets: |
| 94 | + websocket = self.websockets[call_sid] |
| 95 | + # Encode audio as base64 for Twilio |
| 96 | + audio_base64 = base64.b64encode(audio_bytes).decode("utf-8") |
| 97 | + |
| 98 | + message = {"event": "media", "streamSid": call_sid, "media": {"payload": audio_base64}} |
| 99 | + |
| 100 | + try: |
| 101 | + await websocket.send_text(json.dumps(message)) |
| 102 | + except Exception as e: |
| 103 | + logger.error(f"Error sending audio to Twilio for call {call_sid}: {e}") |
| 104 | + |
| 105 | + async def _process_events(self, call_sid: str): |
| 106 | + """Process events from OpenAI Realtime API and send audio to Twilio""" |
| 107 | + try: |
| 108 | + session = self.active_sessions[call_sid] |
| 109 | + |
| 110 | + async for event in session: |
| 111 | + if event.type == "audio": |
| 112 | + # Send audio back to Twilio |
| 113 | + await self.send_audio_to_twilio(call_sid, event.audio.data) |
| 114 | + elif event.type == "error": |
| 115 | + logger.error(f"OpenAI Realtime API error for call {call_sid}: {event}") |
| 116 | + |
| 117 | + except Exception as e: |
| 118 | + logger.error(f"Error processing events for call {call_sid}: {e}") |
| 119 | + |
| 120 | + |
| 121 | +manager = TwilioWebSocketManager() |
| 122 | + |
| 123 | +app = FastAPI() |
| 124 | + |
| 125 | + |
| 126 | +@app.get("/") |
| 127 | +async def root(): |
| 128 | + return {"message": "Twilio Media Stream Server is running!"} |
| 129 | + |
| 130 | + |
| 131 | +@app.post("/incoming-call") |
| 132 | +@app.get("/incoming-call") |
| 133 | +async def incoming_call(): |
| 134 | + """Handle incoming Twilio phone calls""" |
| 135 | + twiml_response = """<?xml version="1.0" encoding="UTF-8"?> |
| 136 | +<Response> |
| 137 | + <Say>Hello! You're now connected to an AI assistant. You can start talking!</Say> |
| 138 | + <Connect> |
| 139 | + <Stream url="wss://your-ngrok-url.ngrok.io/media-stream" /> |
| 140 | + </Connect> |
| 141 | +</Response>""" |
| 142 | + return PlainTextResponse(content=twiml_response, media_type="text/xml") |
| 143 | + |
| 144 | + |
| 145 | +@app.websocket("/media-stream") |
| 146 | +async def media_stream_endpoint(websocket: WebSocket): |
| 147 | + """WebSocket endpoint for Twilio Media Streams""" |
| 148 | + call_sid = None |
| 149 | + |
| 150 | + try: |
| 151 | + await websocket.accept() |
| 152 | + logger.info("WebSocket connection accepted") |
| 153 | + |
| 154 | + while True: |
| 155 | + data = await websocket.receive_text() |
| 156 | + message = json.loads(data) |
| 157 | + |
| 158 | + # Extract call SID from the first message |
| 159 | + if call_sid is None: |
| 160 | + call_sid = message.get("streamSid", "unknown") |
| 161 | + await manager.connect(websocket, call_sid) |
| 162 | + |
| 163 | + await manager.handle_twilio_message(call_sid, message) |
| 164 | + |
| 165 | + except WebSocketDisconnect: |
| 166 | + logger.info("WebSocket disconnected") |
| 167 | + if call_sid: |
| 168 | + await manager.disconnect(call_sid) |
| 169 | + except Exception as e: |
| 170 | + logger.error(f"WebSocket error: {e}") |
| 171 | + if call_sid: |
| 172 | + await manager.disconnect(call_sid) |
| 173 | + |
| 174 | + |
| 175 | +if __name__ == "__main__": |
| 176 | + import uvicorn |
| 177 | + |
| 178 | + port = int(os.getenv("PORT", 8000)) |
| 179 | + uvicorn.run(app, host="0.0.0.0", port=port) |
0 commit comments