Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

reliability: Retry on DB and OpenAI errors

Clémence Lesnéf37190c90379
diff --git a/main.py b/main.py
index 5555708..50e8a46 100644
--- a/main.py
+++ b/main.py
@@ -1,5 +1,5 @@
# General imports
-from typing import List, Optional, Tuple
+from typing import Any, List, Optional, Tuple
from azure.communication.callautomation import (
CallAutomationClient,
CallConnectionClient,
@@ -29,6 +29,7 @@ from models.synthesis import SynthesisModel
from persistence.ai_search import AiSearchSearch
from persistence.cosmos import CosmosStore
from persistence.sqlite import SqliteStore
+from tenacity import retry, stop_after_attempt, wait_random_exponential
import asyncio
import html
import re
@@ -40,6 +41,8 @@ from models.message import (
)
from models.claim import ClaimModel
from openai import AsyncAzureOpenAI
+from openai.types.chat import ChatCompletion
+from openai import _types as openaiTypes
from uuid import UUID
import json
@@ -542,12 +545,7 @@ async def gpt_completion(system: str, call: CallModel) -> str:
content = None
try:
- res = await oai_gpt.chat.completions.create(
- max_tokens=1000, # Arbitrary limit
- messages=messages,
- model=CONFIG.openai.gpt_model,
- temperature=0, # Most focused and deterministic
- )
+ res = await _gpt_completion(messages=messages)
content = res.choices[0].message.content
except Exception:
@@ -752,15 +750,10 @@ async def gpt_chat(
_logger.debug(f"Tools: {tools}")
try:
- # TODO: Manage to catch timeouts to limit waiting time for end users
- res = await oai_gpt.chat.completions.create(
- max_tokens=400, # Communication Services limit is 400 characters for TTS, 400 tokens ~= 300 words
+ res = await _gpt_completion(
messages=messages,
- model=CONFIG.openai.gpt_model,
- temperature=0, # Most focused and deterministic
tools=tools,
)
-
content = res.choices[0].message.content or ""
content = re.sub(
rf"(?:{'|'.join([action.value for action in MessageAction])}):",
@@ -1098,3 +1091,18 @@ async def post_call_synthesis(call: CallModel) -> None:
short=short,
)
await db.call_aset(call)
+
+
+@retry(stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30))
+async def _gpt_completion(
+ messages: List[dict[str, Any]],
+ tools: Optional[List[dict[str, Any]]] = None,
+ max_tokens: int = 1000, # Communication Services limit is 400 characters for TTS, 400 tokens ~= 300 words
+) -> ChatCompletion:
+ return await oai_gpt.chat.completions.create(
+ max_tokens=max_tokens,
+ messages=messages,
+ model=CONFIG.openai.gpt_model,
+ temperature=0, # Most focused and deterministic
+ tools=tools or openaiTypes.NOT_GIVEN,
+ )
diff --git a/persistence/ai_search.py b/persistence/ai_search.py
index 3278fb7..f259e55 100644
--- a/persistence/ai_search.py
+++ b/persistence/ai_search.py
@@ -9,6 +9,7 @@ from helpers.logging import build_logger
from models.training import TrainingModel
from persistence.isearch import ISearch
from pydantic import ValidationError
+from tenacity import retry, stop_after_attempt, wait_random_exponential
from typing import AsyncGenerator, List, Optional
@@ -27,8 +28,8 @@ class AiSearchSearch(ISearch):
if not text:
return None
trainings = []
- async with self._use_db() as db:
- try:
+ try:
+ async with self._use_db() as db:
results = await db.search(
query_language=CONFIG.workflow.conversation_lang, # Re-rank results based on language
query_speller="lexicon", # Spell correction
@@ -59,10 +60,13 @@ class AiSearchSearch(ISearch):
)
except ValidationError as e:
_logger.warn(f"Error parsing training, {e.message}")
- except HttpResponseError as e:
- _logger.error(f"Error connecting to AI Search, {e.message}")
+ except HttpResponseError as e:
+ _logger.error(f"Error connecting to AI Search, {e.message}")
return trainings or None
+ @retry(
+ stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30)
+ )
@asynccontextmanager
async def _use_db(self) -> AsyncGenerator[SearchClient, None]:
async with SearchClient(
diff --git a/persistence/cosmos.py b/persistence/cosmos.py
index dd5a72f..ad6a804 100644
--- a/persistence/cosmos.py
+++ b/persistence/cosmos.py
@@ -1,6 +1,7 @@
from azure.cosmos import CosmosClient, ContainerProxy
from azure.cosmos.exceptions import CosmosHttpResponseError
from azure.identity import DefaultAzureCredential
+from contextlib import asynccontextmanager
from datetime import datetime, timedelta
from fastapi.encoders import jsonable_encoder
from helpers.config import CONFIG
@@ -9,7 +10,8 @@ from helpers.logging import build_logger
from models.call import CallModel
from persistence.istore import IStore
from pydantic import ValidationError
-from typing import List, Optional
+from tenacity import retry, stop_after_attempt, wait_random_exponential
+from typing import AsyncGenerator, List, Optional
from uuid import UUID
@@ -31,11 +33,12 @@ class CosmosStore(IStore):
async def call_aget(self, call_id: UUID) -> Optional[CallModel]:
_logger.debug(f"Loading call {call_id}")
try:
- items = self._db.query_items(
- enable_cross_partition_query=True,
- query="SELECT * FROM c WHERE c.id = @id",
- parameters=[{"name": "@id", "value": str(call_id)}],
- )
+ async with self._use_db() as db:
+ items = db.query_items(
+ enable_cross_partition_query=True,
+ query="SELECT * FROM c WHERE c.id = @id",
+ parameters=[{"name": "@id", "value": str(call_id)}],
+ )
except CosmosHttpResponseError as e:
_logger.error(f"Error accessing CosmosDB, {e.message}")
return None
@@ -62,20 +65,21 @@ class CosmosStore(IStore):
async def call_asearch_one(self, phone_number: str) -> Optional[CallModel]:
_logger.debug(f"Loading last call for {phone_number}")
try:
- items = self._db.query_items(
- max_item_count=1,
- partition_key=phone_number,
- query="SELECT * FROM c WHERE c.created_at < @date_limit ORDER BY c.created_at DESC",
- parameters=[
- {
- "name": "@date_limit",
- "value": str(
- datetime.utcnow()
- + timedelta(hours=CONFIG.workflow.conversation_timeout_hour)
- ),
- }
- ],
- )
+ async with self._use_db() as db:
+ items = db.query_items(
+ max_item_count=1,
+ partition_key=phone_number,
+ query="SELECT * FROM c WHERE c.created_at < @date_limit ORDER BY c.created_at DESC",
+ parameters=[
+ {
+ "name": "@date_limit",
+ "value": str(
+ datetime.utcnow()
+ + timedelta(hours=CONFIG.workflow.conversation_timeout_hour)
+ ),
+ }
+ ],
+ )
except CosmosHttpResponseError as e:
_logger.error(f"Error accessing CosmosDB: {e.message}")
return None
@@ -92,10 +96,11 @@ class CosmosStore(IStore):
_logger.debug(f"Loading all calls for {phone_number}")
calls = []
try:
- items = self._db.query_items(
- partition_key=phone_number,
- query="SELECT * FROM c ORDER BY c.created_at DESC",
- )
+ async with self._use_db() as db:
+ items = db.query_items(
+ partition_key=phone_number,
+ query="SELECT * FROM c ORDER BY c.created_at DESC",
+ )
except CosmosHttpResponseError as e:
_logger.error(f"Error accessing CosmosDB, {e.message}")
return None
@@ -107,3 +112,10 @@ class CosmosStore(IStore):
except ValidationError as e:
_logger.warn(f"Error parsing call, {e.message}")
return calls or None
+
+ @retry(
+ stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30)
+ )
+ @asynccontextmanager
+ async def _use_db(self) -> AsyncGenerator[ContainerProxy, None]:
+ yield self._db
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index 69af073..65b1d69 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -7,6 +7,7 @@ from helpers.logging import build_logger
from models.call import CallModel
from persistence.istore import IStore
from pydantic import ValidationError
+from tenacity import retry, stop_after_attempt, wait_random_exponential
from typing import AsyncGenerator, List, Optional
from uuid import UUID
import json
@@ -37,7 +38,7 @@ class SqliteStore(IStore):
try:
return CallModel.model_validate_json(row[0])
except ValidationError as e:
- _logger.warn(f'Error parsing call, {e.message}')
+ _logger.warn(f"Error parsing call, {e.message}")
return None
async def call_aset(self, call: CallModel) -> bool:
@@ -69,7 +70,7 @@ class SqliteStore(IStore):
try:
return CallModel.model_validate_json(row[0])
except ValidationError as e:
- _logger.warn(f'Error parsing call, {e.message}')
+ _logger.warn(f"Error parsing call, {e.message}")
return None
async def call_asearch_all(self, phone_number: str) -> Optional[List[CallModel]]:
@@ -87,7 +88,7 @@ class SqliteStore(IStore):
try:
calls.append(CallModel.model_validate_json(row[0]))
except ValidationError as e:
- _logger.warn(f'Error parsing call, {e.message}')
+ _logger.warn(f"Error parsing call, {e.message}")
return calls or None
async def _init_db(self, db: SQLiteConnection):
@@ -113,6 +114,9 @@ class SqliteStore(IStore):
# Write changes to disk
await db.commit()
+ @retry(
+ stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30)
+ )
@asynccontextmanager
async def _use_db(self) -> AsyncGenerator[SQLiteConnection, None]:
# Create folder
diff --git a/requirements.txt b/requirements.txt
index 1361da2..5d4e841 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -14,4 +14,5 @@ pydantic-extra-types==2.4.1
pydantic-settings==2.1.0
python-dotenv==1.0.0
pyyaml==6.0.1
+tenacity==8.2.3
uvicorn==0.25.0