From 68a51e71318eee517ea8ff3f94e79337d1e276f4 Mon Sep 17 00:00:00 2001 From: Ajay Raj Date: Sat, 11 Mar 2023 16:09:26 -0800 Subject: [PATCH] add rate limiting support in inbound call server --- vocode/telephony/inbound_call_server.py | 33 ++++++++++++++++--------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/vocode/telephony/inbound_call_server.py b/vocode/telephony/inbound_call_server.py index 1ca082e..b040d1d 100644 --- a/vocode/telephony/inbound_call_server.py +++ b/vocode/telephony/inbound_call_server.py @@ -1,4 +1,5 @@ from fastapi import FastAPI, Response, Form +from typing import Optional import requests import uvicorn from .. import api_key, BASE_URL @@ -8,29 +9,37 @@ from ..models.telephony import CreateInboundCall VOCODE_INBOUND_CALL_URL = f"https://{BASE_URL}/create_inbound_call" -class InboundCallServer(): - def __init__(self, agent_config: AgentConfig): +class InboundCallServer: + def __init__( + self, agent_config: AgentConfig, response_on_rate_limit: Optional[str] = None + ): self.agent_config = agent_config self.app = FastAPI() self.app.post("/vocode")(self.handle_call) + self.response_on_rate_limit = ( + response_on_rate_limit + or "The line is really busy right now, check back later!" + ) - async def handle_call(self, twilio_sid: str = Form(alias='CallSid')): + async def handle_call(self, twilio_sid: str = Form(alias="CallSid")): response = requests.post( VOCODE_INBOUND_CALL_URL, - headers={ - "Authorization": f"Bearer {api_key}" - }, + headers={"Authorization": f"Bearer {api_key}"}, json=CreateInboundCall( - agent_config=self.agent_config, - twilio_sid=twilio_sid - ).dict() + agent_config=self.agent_config, twilio_sid=twilio_sid + ).dict(), ) - assert response.ok + if response.status_code == 429: + return Response( + f"{self.response_on_rate_limit}", + media_type="application/xml", + ) + assert response.ok, response.text return Response( response.text, media_type="application/xml", ) - + def run(self, host="localhost", port=3000): - uvicorn.run(self.app, host=host, port=port) \ No newline at end of file + uvicorn.run(self.app, host=host, port=port)