Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Add Cosmos DB as a database
Clémence Lesnéab08746b7e5d
diff --git a/.gitignore b/.gitignoreindex fe4c3ca..7a014ec 100644--- a/.gitignore+++ b/.gitignore@@ -2,7 +2,7 @@.version.cache# Temporary database-.local.sqlite+.local.sqlite*# Local app config fileconfig.yamldiff --git a/Makefile b/Makefileindex 009733d..ebe95f1 100644--- a/Makefile+++ b/Makefile@@ -44,7 +44,7 @@ tunnel:devtunnel host $(tunnel_name)dev:- VERSION=$(version_full) EVENTS_DOMAIN=$(tunnel_url) python3 -m uvicorn main:api \+ VERSION=$(version_full) API_EVENTS_DOMAIN=$(tunnel_url) python3 -m uvicorn main:api \--header x-version:$${VERSION} \--no-server-header \--port 8080 \@@ -64,7 +64,7 @@ start:@echo "🛠️ Deploying to localhost..."$(docker) run \--detach \- --env EVENTS_DOMAIN=$(tunnel_url) \+ --env API_EVENTS_DOMAIN=$(tunnel_url) \--env VERSION=$(version_full) \--mount type=bind,source="$(CURDIR)/.env",target="/app/.env" \--mount type=bind,source="$(CURDIR)/config.yaml",target="/app/config.yaml" \diff --git a/README.md b/README.mdindex faefc8e..62d2d5a 100644--- a/README.md+++ b/README.md@@ -133,7 +133,8 @@ Place a file called `config.yaml` in the root of the project with the followingapi:root_path: "/"-database: {}+database:+ sqlite: {}monitoring:logging:diff --git a/bicep/app.bicep b/bicep/app.bicepindex b80b506..837b65e 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -62,9 +62,6 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {}environmentId: acaEnv.idtemplate: {- scale: {- maxReplicas: 1- }containers: [{image: 'ghcr.io/clemlesne/claim-ai-phone-bot:${imageVersion}'@@ -75,12 +72,24 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {value: config}{- name: 'EVENTS_DOMAIN'+ name: 'API_EVENTS_DOMAIN'value: appUrl}{- name: 'SQLITE_PATH'- value: '/app/data/.default.sqlite'+ name: 'DATABASE_MODE'+ value: 'cosmos_db'+ }+ {+ name: 'DATABASE_COSMOS_DB_ENDPOINT'+ value: cosmos.properties.documentEndpoint+ }+ {+ name: 'DATABASE_COSMOS_DB_CONTAINER'+ value: container.name+ }+ {+ name: 'DATABASE_COSMOS_DB_DATABASE'+ value: database.name}]resources: {@@ -122,12 +131,12 @@ resource blobContainer 'Microsoft.Storage/storageAccounts/blobServices/containername: '$web'}-resource roleCommunicationContributor 'Microsoft.Authorization/roleDefinitions@2018-01-01-preview' existing = {+resource roleCommunicationContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {name: 'b24988ac-6180-42a0-ab88-20f7382dd24c'}-resource appContributeCommunication 'Microsoft.Authorization/roleAssignments@2022-04-01' = {- name: guid(subscription().id, deployment().name, 'appContributeCommunication')+resource appContribCommunication 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, deployment().name, 'appContribCommunication')scope: communicationproperties: {principalId: containerApp.identity.principalId@@ -150,12 +159,12 @@ resource eventgridTopic 'Microsoft.EventGrid/systemTopics@2023-12-15-preview' =}}-resource roleOpenaiContributor 'Microsoft.Authorization/roleDefinitions@2018-01-01-preview' existing = {+resource roleOpenaiContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {name: 'a001fd3d-188f-4b5d-821b-7da978bf7442'}-resource appAccessOpenai 'Microsoft.Authorization/roleAssignments@2022-04-01' = {- name: guid(subscription().id, deployment().name, 'appAccessOpenai')+resource appContribOpenai 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, deployment().name, 'appContribOpenai')scope: cognitiveOpenaiproperties: {principalId: containerApp.identity.principalId@@ -252,3 +261,100 @@ resource contentfilter 'Microsoft.CognitiveServices/accounts/raiPolicies@2023-06]}}++resource cosmos 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {+ name: prefix+ location: location+ tags: tags+ kind: 'GlobalDocumentDB'+ properties: {+ databaseAccountOfferType: 'Standard'+ locations: [+ {+ locationName: location+ }+ ]+ capabilities: [+ {+ name: 'EnableServerless'+ }+ ]+ }+}++resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15' = {+ parent: cosmos+ name: 'claim-ai'+ properties: {+ resource: {+ id: 'claim-ai'+ }+ }+}++resource roleSqlContrib 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2023-11-15' = {+ parent: cosmos+ name: guid('sql-role-definition-', deployment().name, 'roleSqlContrib')+ properties: {+ roleName: 'roleSqlContrib'+ type: 'CustomRole'+ assignableScopes: [+ cosmos.id+ ]+ permissions: [+ {+ dataActions: [+ 'Microsoft.DocumentDB/databaseAccounts/readMetadata'+ 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*'+ 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/executeQuery'+ ]+ }+ ]+ }+}++resource appContribSql 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2021-04-15' = {+ parent: cosmos+ name: guid(roleSqlContrib.id, deployment().name, 'appContribSql')+ properties: {+ principalId: containerApp.identity.principalId+ roleDefinitionId: roleSqlContrib.id+ scope: cosmos.id+ }+}++resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2023-11-15' = {+ parent: database+ name: 'calls'+ properties: {+ resource: {+ id: 'calls'+ indexingPolicy: {+ automatic: true+ includedPaths: [+ {+ path: '/created_at/?'+ indexes: [+ {+ dataType: 'String'+ kind: 'Range'+ precision: -1+ }+ ]+ }+ ]+ excludedPaths: [+ {+ path: '/*'+ }+ ]+ }+ partitionKey: {+ paths: [+ '/phone_number'+ ]+ kind: 'Hash'+ }+ }+ }+}diff --git a/helpers/config.py b/helpers/config.pyindex 2863b09..4c2df7d 100644--- a/helpers/config.py+++ b/helpers/config.py@@ -6,6 +6,7 @@ load_dotenv(find_dotenv())# Load depsfrom helpers.config_models.root import RootModel+from pydantic import ValidationErrorimport osimport yaml@@ -34,6 +35,8 @@ else:try:with open(path, "r", encoding="utf-8") as f:CONFIG = RootModel.model_validate(yaml.safe_load(f))+ except ValidationError as e:+ raise ConfigBadFormat(f"Config values are not valid") from eexcept Exception as e:- raise ConfigBadFormat(f'Config "{path}" is not valid YAML') from e+ raise ConfigBadFormat(f"Config YAML format is not valid") from eprint(f'Config "{path}" loaded')diff --git a/helpers/config_models/api.py b/helpers/config_models/api.pyindex 3b86189..b9f0f59 100644--- a/helpers/config_models/api.py+++ b/helpers/config_models/api.py@@ -1,8 +1,6 @@-from os import environ-from pydantic import BaseModel, Field+from pydantic_settings import BaseSettings-class ApiModel(BaseModel):- events_domain: str = environ["EVENTS_DOMAIN"]+class ApiModel(BaseSettings, env_prefix="api_"):+ events_domain: strroot_path: str = ""- version: str = Field(default=environ["VERSION"], frozen=True)diff --git a/helpers/config_models/cognitive_service.py b/helpers/config_models/cognitive_service.pyindex 8c8a682..20dc5fc 100644--- a/helpers/config_models/cognitive_service.py+++ b/helpers/config_models/cognitive_service.py@@ -1,5 +1,5 @@-from pydantic import BaseModel+from pydantic_settings import BaseSettings-class CognitiveServiceModel(BaseModel):+class CognitiveServiceModel(BaseSettings, env_prefix="cognitive_service_"):endpoint: strdiff --git a/helpers/config_models/communication_service.py b/helpers/config_models/communication_service.pyindex aeab3ec..edb323b 100644--- a/helpers/config_models/communication_service.py+++ b/helpers/config_models/communication_service.py@@ -1,12 +1,13 @@-from pydantic import BaseModel, SecretStr+from pydantic import SecretStrfrom pydantic_extra_types.phone_numbers import PhoneNumber+from pydantic_settings import BaseSettings# E164 is standard accross all Microsoft servicesPhoneNumber.phone_format = "E164"-class CommunicationServiceModel(BaseModel):+class CommunicationServiceModel(BaseSettings, env_prefix="communication_service_"):access_key: SecretStrendpoint: strphone_number: PhoneNumberdiff --git a/helpers/config_models/database.py b/helpers/config_models/database.pyindex 6ad98d8..182e6c0 100644--- a/helpers/config_models/database.py+++ b/helpers/config_models/database.py@@ -1,6 +1,38 @@-from pydantic import BaseModel-from os import environ+from enum import Enum+from pydantic import validator+from pydantic_settings import BaseSettings+from typing import Optional-class DatabaseModel(BaseModel):- sqlite_path: str = environ.get("SQLITE_PATH", ".local.sqlite")+class Mode(str, Enum):+ COSMOS_DB = "cosmos_db"+ SQLITE = "sqlite"+++class CosmosDbModel(BaseSettings, env_prefix="database_cosmos_db_"):+ container: str+ database: str+ endpoint: str+++class SqliteModel(BaseSettings, env_prefix="database_sqlite_"):+ path: str = ".local.sqlite"+ table: str = "calls"+++class DatabaseModel(BaseSettings, env_prefix="database_"):+ cosmos_db: Optional[CosmosDbModel] = None+ mode: Mode = Mode.SQLITE+ sqlite: Optional[SqliteModel] = None++ @validator("cosmos_db", always=True)+ def check_cosmos_db(cls, v, values, **kwargs):+ if not v and values.get("mode", None) == Mode.COSMOS_DB:+ raise ValueError("Cosmos DB config required")+ return v++ @validator("sqlite", always=True)+ def check_sqlite(cls, v, values, **kwargs):+ if not v and values.get("mode", None) == Mode.SQLITE:+ raise ValueError("Sqlite config required")+ return vdiff --git a/helpers/config_models/eventgrid.py b/helpers/config_models/eventgrid.pyindex 05e8596..e324a85 100644--- a/helpers/config_models/eventgrid.py+++ b/helpers/config_models/eventgrid.py@@ -1,7 +1,7 @@-from pydantic import BaseModel+from pydantic_settings import BaseSettings-class EventgridModel(BaseModel):+class EventgridModel(BaseSettings, env_prefix="eventgrid_"):resource_group: strsubscription_id: strsystem_topic: strdiff --git a/helpers/config_models/monitoring.py b/helpers/config_models/monitoring.pyindex a7b9e1b..3c9d7f4 100644--- a/helpers/config_models/monitoring.py+++ b/helpers/config_models/monitoring.py@@ -1,5 +1,5 @@from enum import Enum-from pydantic import BaseModel, SecretStr+from pydantic_settings import BaseSettingsclass LoggingLevel(str, Enum):@@ -12,10 +12,10 @@ class LoggingLevel(str, Enum):WARNING = "WARNING"-class LoggingMonitoringModel(BaseModel):+class LoggingMonitoringModel(BaseSettings, env_prefix="monitoring_logging_"):app_level: LoggingLevel = LoggingLevel.INFOsys_level: LoggingLevel = LoggingLevel.WARNING-class MonitoringModel(BaseModel):+class MonitoringModel(BaseSettings, env_prefix="monitoring_"):logging: LoggingMonitoringModeldiff --git a/helpers/config_models/openai.py b/helpers/config_models/openai.pyindex 0a247ff..9d79386 100644--- a/helpers/config_models/openai.py+++ b/helpers/config_models/openai.py@@ -1,8 +1,9 @@-from pydantic import BaseModel, SecretStr+from pydantic import SecretStr+from pydantic_settings import BaseSettingsfrom typing import Optional-class OpenAiModel(BaseModel):+class OpenAiModel(BaseSettings, env_prefix="openai_"):api_key: Optional[SecretStr] = Noneendpoint: strgpt_deployment: strdiff --git a/helpers/config_models/resources.py b/helpers/config_models/resources.pyindex b717970..ccf1168 100644--- a/helpers/config_models/resources.py+++ b/helpers/config_models/resources.py@@ -1,5 +1,5 @@-from pydantic import BaseModel+from pydantic_settings import BaseSettings-class ResourcesModel(BaseModel):+class ResourcesModel(BaseSettings, env_prefix="resources_"):public_url: strdiff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex 4445a73..60d74b8 100644--- a/helpers/config_models/root.py+++ b/helpers/config_models/root.py@@ -7,10 +7,11 @@ from helpers.config_models.monitoring import MonitoringModelfrom helpers.config_models.openai import OpenAiModelfrom helpers.config_models.resources import ResourcesModelfrom helpers.config_models.workflow import WorkflowModel-from pydantic import BaseModel+from pydantic import Field+from pydantic_settings import BaseSettings-class RootModel(BaseModel):+class RootModel(BaseSettings, env_prefix=""):api: ApiModelcognitive_service: CognitiveServiceModelcommunication_service: CommunicationServiceModel@@ -19,4 +20,5 @@ class RootModel(BaseModel):monitoring: MonitoringModelopenai: OpenAiModelresources: ResourcesModel+ version: str = Field(frozen=True)workflow: WorkflowModeldiff --git a/helpers/config_models/workflow.py b/helpers/config_models/workflow.pyindex bddeece..72274c6 100644--- a/helpers/config_models/workflow.py+++ b/helpers/config_models/workflow.py@@ -1,12 +1,12 @@-from pydantic import BaseModelfrom pydantic_extra_types.phone_numbers import PhoneNumber+from pydantic_settings import BaseSettings# E164 is standard accross all Microsoft servicesPhoneNumber.phone_format = "E164"-class WorkflowModel(BaseModel):+class WorkflowModel(BaseSettings, env_prefix="workflow_"):agent_phone_number: PhoneNumberbot_company: strbot_name: strdiff --git a/main.py b/main.pyindex d60fbe3..41fce7f 100644--- a/main.py+++ b/main.py@@ -13,11 +13,9 @@ from azure.core.exceptions import ResourceNotFoundErrorfrom azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNamesfrom azure.identity import DefaultAzureCredential, get_bearer_token_provider-from contextlib import asynccontextmanagerfrom datetime import datetimefrom enum import Enumfrom fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks-from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, HTMLResponsefrom helpers.config import CONFIGfrom helpers.logging import build_logger@@ -25,6 +23,9 @@ from helpers.prompts import LLM as LLMPrompt, TTS as TTSPrompt, Sounds as SoundPfrom jinja2 import Environment, FileSystemLoader, select_autoescapefrom models.action import ActionModel, Indent as IndentActionfrom models.reminder import ReminderModel+from helpers.config_models.database import Mode as DatabaseMode+from persistence.sqlite import SqliteStore+from persistence.cosmos import CosmosStorefrom pydantic.json import pydantic_encoderimport asynciofrom models.call import (@@ -35,24 +36,19 @@ from models.call import ()from models.claim import ClaimModelfrom openai import AsyncAzureOpenAI-from uuid import UUID, uuid4+from uuid import UUIDimport json-import aiosqlite-import os_logger = build_logger(__name__)--ROOT_PATH = CONFIG.api.root_path-AZ_CREDENTIAL = DefaultAzureCredential()--_logger.info(f'Using root path "{ROOT_PATH}"')+_logger.info(f"claim-ai v{CONFIG.version}")jinja = Environment(autoescape=select_autoescape(),enable_async=True,loader=FileSystemLoader("public_website"),)+_logger.info(f"Using OpenAI GPT model {CONFIG.openai.gpt_model}")oai_gpt = AsyncAzureOpenAI(api_version="2023-12-01-preview",azure_deployment=CONFIG.openai.gpt_deployment,@@ -61,14 +57,14 @@ oai_gpt = AsyncAzureOpenAI(api_key=CONFIG.openai.api_key.get_secret_value() if CONFIG.openai.api_key else None,azure_ad_token_provider=(get_bearer_token_provider(- AZ_CREDENTIAL, "https://cognitiveservices.azure.com/.default"+ DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")if not CONFIG.openai.api_keyelse None),)-eventgrid_subscription_name = f"tmp-{uuid4()}"source_caller = PhoneNumberIdentifier(CONFIG.communication_service.phone_number)+_logger.info(f"Using phone number {str(CONFIG.communication_service.phone_number)}")# Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)call_automation_client = CallAutomationClient(endpoint=CONFIG.communication_service.endpoint,@@ -77,25 +73,14 @@ call_automation_client = CallAutomationClient(),)sms_client = SmsClient(- credential=AZ_CREDENTIAL, endpoint=CONFIG.communication_service.endpoint+ credential=DefaultAzureCredential(), endpoint=CONFIG.communication_service.endpoint)--CALL_EVENT_URL = f'{CONFIG.api.events_domain.strip("/")}/call/event'-CALL_INBOUND_URL = f'{CONFIG.api.events_domain.strip("/")}/call/inbound'---class Context(str, Enum):- TRANSFER_FAILED = "transfer_failed"- CONNECT_AGENT = "connect_agent"- GOODBYE = "goodbye"---@asynccontextmanager-async def lifespan(_: FastAPI):- await init_db()- yield--+db = (+ SqliteStore(CONFIG.database.sqlite)+ if CONFIG.database.mode == DatabaseMode.SQLITE+ else CosmosStore(CONFIG.database.cosmos_db)+)+_logger.info(f'Using root path "{CONFIG.api.root_path}"')api = FastAPI(contact={"url": "https://github.com/clemlesne/claim-ai-phone-bot",@@ -105,18 +90,20 @@ api = FastAPI("name": "Apache-2.0","url": "https://github.com/clemlesne/claim-ai-phone-bot/blob/master/LICENCE",},- lifespan=lifespan,- root_path=ROOT_PATH,+ root_path=CONFIG.api.root_path,title="claim-ai-phone-bot",- version=CONFIG.api.version,+ version=CONFIG.version,)-api.add_middleware(- CORSMiddleware,- allow_headers=["*"],- allow_methods=["*"],- allow_origins=["*"],-)++CALL_EVENT_URL = f'{CONFIG.api.events_domain.strip("/")}/call/event'+CALL_INBOUND_URL = f'{CONFIG.api.events_domain.strip("/")}/call/inbound'+++class Context(str, Enum):+ TRANSFER_FAILED = "transfer_failed"+ CONNECT_AGENT = "connect_agent"+ GOODBYE = "goodbye"@api.get(@@ -133,7 +120,7 @@ async def health_liveness_get() -> None:description="Display the call report in a web page.",)async def call_report_get(call_id: UUID) -> HTMLResponse:- call = await get_call_by_id(call_id)+ call = await db.call_aget(call_id)if not call:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,@@ -154,7 +141,7 @@ async def call_report_get(call_id: UUID) -> HTMLResponse:description="Get all calls by phone number.",)async def call_get(phone_number: str) -> List[CallModel]:- return await get_calls_by_phone_number(phone_number)+ return await db.call_asearch_all(phone_number) or []@api.get(@@ -227,7 +214,7 @@ async def call_event_post(async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:- call = await get_call_by_id(call_id)+ call = await db.call_aget(call_id)if not call:_logger.warn(f"Call {call_id} not found")return@@ -244,7 +231,7 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:_logger.debug(event.data)if event_type == "Microsoft.Communication.CallConnected": # Call answered- _logger.info(f"Call connected ({call.id})")+ _logger.info(f"Call connected ({call.call_id})")call.recognition_retry = 0 # Reset recognition retry counterif not call.messages: # First call@@ -268,7 +255,7 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:await intelligence(call, client)elif event_type == "Microsoft.Communication.CallDisconnected": # Call hung up- _logger.info(f"Call disconnected ({call.id})")+ _logger.info(f"Call disconnected ({call.call_id})")await handle_hangup(call=call, client=client)elif (@@ -276,7 +263,7 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:): # Speech recognizedif event.data["recognitionType"] == "speech":speech_text = event.data["speechResult"]["speech"]- _logger.info(f"Recognition completed ({call.id}): {speech_text}")+ _logger.info(f"Recognition completed ({call.call_id}): {speech_text}")if speech_text is not None and len(speech_text) > 0:call.messages.append(@@ -314,22 +301,24 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:)elif event_type == "Microsoft.Communication.PlayCompleted": # Media played- _logger.debug(f"Play completed ({call.id})")+ _logger.debug(f"Play completed ({call.call_id})")if (operation_context == Context.TRANSFER_FAILEDor operation_context == Context.GOODBYE): # Call ended- _logger.info(f"Ending call ({call.id})")+ _logger.info(f"Ending call ({call.call_id})")await handle_hangup(call=call, client=client)elif operation_context == Context.CONNECT_AGENT: # Call transfer- _logger.info(f"Initiating transfer call initiated ({call.id})")- agent_caller = PhoneNumberIdentifier(CONFIG.workflow.agent_phone_number)+ _logger.info(f"Initiating transfer call initiated ({call.call_id})")+ agent_caller = PhoneNumberIdentifier(+ str(CONFIG.workflow.agent_phone_number)+ )client.transfer_call_to_participant(target_participant=agent_caller)elif event_type == "Microsoft.Communication.PlayFailed": # Media play failed- _logger.debug(f"Play failed ({call.id})")+ _logger.debug(f"Play failed ({call.call_id})")result_information = event.data["resultInformation"]error_code = result_information["subCode"]@@ -347,16 +336,16 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:elif (event_type == "Microsoft.Communication.CallTransferAccepted"): # Call transfer accepted- _logger.info(f"Call transfer accepted event ({call.id})")+ _logger.info(f"Call transfer accepted event ({call.call_id})")# TODO: Is there anything to do here?elif (event_type == "Microsoft.Communication.CallTransferFailed"): # Call transfer failed- _logger.debug(f"Call transfer failed event ({call.id})")+ _logger.debug(f"Call transfer failed event ({call.call_id})")result_information = event.data["resultInformation"]sub_code = result_information["subCode"]- _logger.info(f"Error during call transfer, subCode {sub_code} ({call.id})")+ _logger.info(f"Error during call transfer, subCode {sub_code} ({call.call_id})")await handle_play(call=call,client=client,@@ -364,7 +353,7 @@ async def communication_evnt_worker(event_dict: dict, call_id: UUID) -> None:text=TTSPrompt.CALLTRANSFER_FAILURE,)- await save_call(call)+ await db.call_aset(call)async def intelligence(call: CallModel, client: CallConnectionClient) -> None:@@ -385,7 +374,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> None:try:while True:- _logger.debug(f"Chat task status ({call.id}): {chat_task.done()}")+ _logger.debug(f"Chat task status ({call.call_id}): {chat_task.done()}")# Play loading soundawait handle_media(call=call,@@ -403,7 +392,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> None:# Break when hard timeout is reachedif hard_timeout_task.done():_logger.warn(- f"Hard timeout of {CONFIG.workflow.intelligence_hard_timeout_sec}s reached ({call.id})"+ f"Hard timeout of {CONFIG.workflow.intelligence_hard_timeout_sec}s reached ({call.call_id})")# Clean upchat_task.cancel()@@ -412,7 +401,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> None:# Speak when soft timeout is reachedif soft_timeout_task.done() and not soft_timeout_triggered:_logger.warn(- f"Soft timeout of {CONFIG.workflow.intelligence_soft_timeout_sec}s reached ({call.id})"+ f"Soft timeout of {CONFIG.workflow.intelligence_soft_timeout_sec}s reached ({call.call_id})")soft_timeout_triggered = Trueawait handle_play(@@ -423,16 +412,16 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> None:# Wait to not block the event loop and play too many soundsawait asyncio.sleep(5)except Exception:- _logger.warn(f"Error loading intelligence ({call.id})", exc_info=True)+ _logger.warn(f"Error loading intelligence ({call.call_id})", exc_info=True)# For any error reason, answer with errorif not chat_res:_logger.debug(- f"Error loading intelligence ({call.id}), answering with default error"+ f"Error loading intelligence ({call.call_id}), answering with default error")chat_res = ActionModel(content=TTSPrompt.ERROR, intent=IndentAction.CONTINUE)- _logger.info(f"Chat ({call.id}): {chat_res}")+ _logger.info(f"Chat ({call.call_id}): {chat_res}")if chat_res.intent == IndentAction.TALK_TO_HUMAN:await handle_play(@@ -456,7 +445,7 @@ async def intelligence(call: CallModel, client: CallConnectionClient) -> None:IndentAction.NEW_OR_UPDATED_REMINDER,):# Save in DB allowing demos to be more "real-time"- await save_call(call)+ await db.call_aset(call)# Answer with intermediate responseawait handle_play(call=call,@@ -509,17 +498,17 @@ async def handle_play(try:for chunk in chunks:- _logger.debug(f"Playing chunk ({call.id}): {chunk}")+ _logger.debug(f"Playing chunk ({call.call_id}): {chunk}")client.play_media(operation_context=context,play_source=audio_from_text(chunk),)except ResourceNotFoundError:- _logger.debug(f"Call hung up before playing ({call.id})")+ _logger.debug(f"Call hung up before playing ({call.call_id})")async def gpt_completion(system: LLMPrompt, call: CallModel) -> str:- _logger.debug(f"Running GPT completion ({call.id})")+ _logger.debug(f"Running GPT completion ({call.call_id})")messages = [{@@ -557,7 +546,7 @@ async def gpt_completion(system: LLMPrompt, call: CallModel) -> str:async def gpt_chat(call: CallModel) -> ActionModel:- _logger.debug(f"Running GPT chat ({call.id})")+ _logger.debug(f"Running GPT chat ({call.call_id})")messages = [{@@ -598,7 +587,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:"role": "assistant","tool_calls": [{- "id": tool_call.id,+ "id": tool_call.tool_id,"type": "function","function": {"arguments": tool_call.function_arguments,@@ -614,7 +603,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:{"content": message.content,"role": "tool",- "tool_call_id": tool_call.id,+ "tool_call_id": tool_call.tool_id,})_logger.debug(f"Messages: {messages}")@@ -765,7 +754,7 @@ async def gpt_chat(call: CallModel) -> ActionModel:content="",function_arguments=arguments,function_name=name,- id=tool_call.id,+ tool_id=tool_call.id,)if name == IndentAction.TALK_TO_HUMAN:@@ -876,7 +865,7 @@ async def handle_recognize_text(text=text,)- _logger.debug(f"Recognizing ({call.id})")+ _logger.debug(f"Recognizing ({call.call_id})")await handle_recognize_media(call=call,client=client,@@ -903,7 +892,7 @@ async def handle_recognize_media(target_participant=PhoneNumberIdentifier(call.phone_number),)except ResourceNotFoundError:- _logger.debug(f"Call hung up before recognizing ({call.id})")+ _logger.debug(f"Call hung up before recognizing ({call.call_id})")async def handle_media(@@ -918,26 +907,26 @@ async def handle_media(play_source=FileSource(url=sound),)except ResourceNotFoundError:- _logger.debug(f"Call hung up before playing ({call.id})")+ _logger.debug(f"Call hung up before playing ({call.call_id})")async def handle_hangup(client: CallConnectionClient, call: CallModel) -> None:- _logger.debug(f"Hanging up call ({call.id})")+ _logger.debug(f"Hanging up call ({call.call_id})")try:client.hang_up(is_for_everyone=True)except ResourceNotFoundError:- _logger.debug(f"Call already hung up ({call.id})")+ _logger.debug(f"Call already hung up ({call.call_id})")call.messages.append(CallMessageModel(content="Customer ended the call.", persona=CallPersona.HUMAN))content = await gpt_completion(LLMPrompt.SMS_SUMMARY_SYSTEM, call)- _logger.info(f"SMS report ({call.id}): {content}")+ _logger.info(f"SMS report ({call.call_id}): {content}")try:responses = sms_client.send(- from_=CONFIG.communication_service.phone_number,+ from_=str(CONFIG.communication_service.phone_number),message=content,to=call.phone_number,)@@ -945,7 +934,7 @@ async def handle_hangup(client: CallConnectionClient, call: CallModel) -> None:if response.successful:_logger.info(- f"SMS report sent {response.message_id} to {response.to} ({call.id})"+ f"SMS report sent {response.message_id} to {response.to} ({call.call_id})")call.messages.append(CallMessageModel(@@ -955,7 +944,7 @@ async def handle_hangup(client: CallConnectionClient, call: CallModel) -> None:)else:_logger.warn(- f"Failed SMS to {response.to}, status {response.http_status_code}, error {response.error_message} ({call.id})"+ f"Failed SMS to {response.to}, status {response.http_status_code}, error {response.error_message} ({call.call_id})")call.messages.append(CallMessageModel(@@ -965,7 +954,9 @@ async def handle_hangup(client: CallConnectionClient, call: CallModel) -> None:)except Exception:- _logger.warn(f"Failed SMS to {call.phone_number} ({call.id})", exc_info=True)+ _logger.warn(+ f"Failed SMS to {call.phone_number} ({call.call_id})", exc_info=True+ )def audio_from_text(text: str) -> SsmlSource:@@ -990,67 +981,8 @@ async def callback_url(caller_id: str) -> str:If the caller has already called, use the same call ID, to keep the conversation history. Otherwise, create a new call ID."""- call = await get_last_call_by_phone_number(caller_id)+ call = await db.call_asearch_one(caller_id)if not call:call = CallModel(phone_number=caller_id)- await save_call(call)- return f"{CALL_EVENT_URL}/{call.id}"---async def init_db():- # Create folder- db_path = CONFIG.database.sqlite_path- db_folder = db_path[: db_path.rfind("/")]- if not os.path.exists(db_folder):- os.makedirs(db_folder)-- # Create table- async with aiosqlite.connect(db_path) as db:- await db.execute(- "CREATE TABLE IF NOT EXISTS calls (id VARCHAR(32) PRIMARY KEY, phone_number TEXT, data TEXT, created_at TEXT)"- )- await db.commit()---async def save_call(call: CallModel):- async with aiosqlite.connect(CONFIG.database.sqlite_path) as db:- await db.execute(- "INSERT OR REPLACE INTO calls VALUES (?, ?, ?, ?)",- (- call.id.hex, # id- call.phone_number, # phone_number- call.model_dump_json(), # data- call.created_at.isoformat(), # created_at- ),- )- await db.commit()---async def get_call_by_id(call_id: UUID) -> Optional[CallModel]:- async with aiosqlite.connect(CONFIG.database.sqlite_path) as db:- cursor = await db.execute(- "SELECT data FROM calls WHERE id = ?",- (call_id.hex,),- )- row = await cursor.fetchone()- return CallModel.model_validate_json(row[0]) if row else None---async def get_last_call_by_phone_number(phone_number: str) -> Optional[CallModel]:- async with aiosqlite.connect(CONFIG.database.sqlite_path) as db:- cursor = await db.execute(- f"SELECT data FROM calls WHERE phone_number = ? AND DATETIME(created_at) > DATETIME('now', '-{CONFIG.workflow.conversation_timeout_hour} hours') ORDER BY DATETIME(created_at) DESC LIMIT 1",- (phone_number,),- )- row = await cursor.fetchone()- return CallModel.model_validate_json(row[0]) if row else None---async def get_calls_by_phone_number(phone_number: str) -> List[CallModel]:- async with aiosqlite.connect(CONFIG.database.sqlite_path) as db:- cursor = await db.execute(- f"SELECT data FROM calls WHERE phone_number = ? ORDER BY DATETIME(created_at) DESC",- (phone_number,),- )- rows = await cursor.fetchall()- return [CallModel.model_validate_json(row[0]) for row in rows if row]+ await db.call_aset(call)+ return f"{CALL_EVENT_URL}/{call.call_id}"diff --git a/models/call.py b/models/call.pyindex 3fd0a44..a4b0faa 100644--- a/models/call.py+++ b/models/call.py@@ -17,7 +17,7 @@ class ToolModel(BaseModel):content: strfunction_arguments: strfunction_name: str- id: str+ tool_id: strclass MessageModel(BaseModel):@@ -28,9 +28,9 @@ class MessageModel(BaseModel):class CallModel(BaseModel):+ call_id: UUID = Field(default_factory=uuid4, frozen=True)claim: ClaimModel = Field(default_factory=ClaimModel)created_at: datetime = Field(default_factory=datetime.utcnow, frozen=True)- id: UUID = Field(default_factory=uuid4, frozen=True)messages: List[MessageModel] = []phone_number: strrecognition_retry: int = Field(default=0)diff --git a/models/claim.py b/models/claim.pyindex 2bcd98f..8094d5d 100644--- a/models/claim.py+++ b/models/claim.py@@ -7,7 +7,7 @@ import stringclass ClaimModel(BaseModel):# Immutable fields- id: str = Field(+ claim_id: str = Field(default_factory=(lambda: "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(6)diff --git a/persistence/cosmos.py b/persistence/cosmos.pynew file mode 100644index 0000000..1d70f51--- /dev/null+++ b/persistence/cosmos.py@@ -0,0 +1,109 @@+from azure.cosmos import CosmosClient, ContainerProxy+from azure.cosmos.exceptions import CosmosHttpResponseError+from azure.identity import DefaultAzureCredential+from datetime import datetime, timedelta+from fastapi.encoders import jsonable_encoder+from helpers.config import CONFIG+from helpers.config_models.database import CosmosDbModel+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 uuid import UUID+++_logger = build_logger(__name__)+AZ_CREDENTIAL = DefaultAzureCredential()+++class CosmosStore(IStore):+ _db: ContainerProxy++ def __init__(self, config: CosmosDbModel):+ _logger.info(f"Using CosmosDB {config.database}/{config.container}")+ client = CosmosClient(+ connection_timeout=5, credential=AZ_CREDENTIAL, url=config.endpoint+ )+ database = client.get_database_client(config.database)+ self._db = database.get_container_client(config.container)++ 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)}],+ )+ except CosmosHttpResponseError as e:+ _logger.error(f"Error accessing CosmosDB: {e}")+ return None+ try:+ raw = next(items)+ try:+ return CallModel(**raw)+ except ValidationError as e:+ _logger.warn(f'Error parsing call, "{e}"')+ except StopIteration:+ return None++ async def call_aset(self, call: CallModel) -> bool:+ data = jsonable_encoder(call, exclude_none=True)+ data["id"] = str(call.call_id) # CosmosDB requires an id field+ _logger.debug(f"Saving call {call.call_id}: {data}")+ try:+ self._db.upsert_item(body=data)+ return True+ except CosmosHttpResponseError as e:+ _logger.error(f"Error accessing CosmosDB: {e}")+ return False++ 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)+ ),+ }+ ],+ )+ except CosmosHttpResponseError as e:+ _logger.error(f"Error accessing CosmosDB: {e}")+ return None+ try:+ raw = next(items)+ try:+ return CallModel(**raw)+ except ValidationError as e:+ _logger.warn(f'Error parsing call, "{e}"')+ except StopIteration:+ return None++ async def call_asearch_all(self, phone_number: str) -> Optional[List[CallModel]]:+ _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",+ )+ except CosmosHttpResponseError as e:+ _logger.error(f"Error accessing CosmosDB: {e}")+ return None+ for raw in items:+ if not raw:+ continue+ try:+ calls.append(CallModel(**raw))+ except ValidationError as e:+ _logger.warn(f'Error parsing call, "{e}"')+ return calls or Nonediff --git a/persistence/istore.py b/persistence/istore.pynew file mode 100644index 0000000..84bb7ef--- /dev/null+++ b/persistence/istore.py@@ -0,0 +1,22 @@+from abc import ABC, abstractmethod+from models.call import CallModel+from typing import List, Optional+from uuid import UUID+++class IStore(ABC):+ @abstractmethod+ async def call_aget(self, call_id: UUID) -> Optional[CallModel]:+ pass++ @abstractmethod+ async def call_aset(self, call: CallModel) -> bool:+ pass++ @abstractmethod+ async def call_asearch_one(self, phone_number: str) -> Optional[CallModel]:+ pass++ @abstractmethod+ async def call_asearch_all(self, phone_number: str) -> Optional[List[CallModel]]:+ passdiff --git a/persistence/sqlite.py b/persistence/sqlite.pynew file mode 100644index 0000000..5d888d0--- /dev/null+++ b/persistence/sqlite.py@@ -0,0 +1,133 @@+from aiosqlite import connect as sqlite_connect, Connection as SQLiteConnection+from contextlib import asynccontextmanager+from fastapi.encoders import jsonable_encoder+from helpers.config import CONFIG+from helpers.config_models.database import SqliteModel+from helpers.logging import build_logger+from models.call import CallModel+from persistence.istore import IStore+from pydantic import ValidationError+from typing import AsyncGenerator, List, Optional+from uuid import UUID+import json+import os+++_logger = build_logger(__name__)+++class SqliteStore(IStore):+ _config: SqliteModel++ def __init__(self, config: SqliteModel):+ _logger.info(+ f"Using SQLite database at {config.path} with table {config.table}"+ )+ self._config = config++ async def call_aget(self, call_id: UUID) -> Optional[CallModel]:+ _logger.debug(f"Loading call {call_id}")+ async with self._use_db() as db:+ cursor = await db.execute(+ f"SELECT data FROM {self._config.table} WHERE id = ?",+ (str(call_id),),+ )+ row = await cursor.fetchone()+ if row:+ try:+ return CallModel.model_validate_json(row[0])+ except ValidationError as e:+ _logger.warn(f'Error parsing call, "{e}"')+ return None++ async def call_aset(self, call: CallModel) -> bool:+ # TODO: Catch exceptions and return False if something goes wrong+ data = jsonable_encoder(call, exclude_none=True)+ _logger.debug(f"Saving call {call.call_id}: {data}")+ async with self._use_db() as db:+ await db.execute(+ f"INSERT OR REPLACE INTO {self._config.table} VALUES (?, ?, ?, ?)",+ (+ str(call.call_id), # id+ call.phone_number, # phone_number+ json.dumps(data), # data+ call.created_at.isoformat(), # created_at+ ),+ )+ await db.commit()+ return True++ async def call_asearch_one(self, phone_number: str) -> Optional[CallModel]:+ _logger.debug(f"Loading last call for {phone_number}")+ async with self._use_db() as db:+ cursor = await db.execute(+ f"SELECT data FROM {self._config.table} WHERE phone_number = ? AND DATETIME(created_at) < DATETIME('now', '{CONFIG.workflow.conversation_timeout_hour} hours') ORDER BY DATETIME(created_at) DESC LIMIT 1",+ (phone_number,),+ )+ row = await cursor.fetchone()+ if row:+ try:+ return CallModel.model_validate_json(row[0])+ except ValidationError as e:+ _logger.warn(f'Error parsing call, "{e}"')+ return None++ async def call_asearch_all(self, phone_number: str) -> Optional[List[CallModel]]:+ _logger.debug(f"Loading all {self._config.table} for {phone_number}")+ calls = []+ async with self._use_db() as db:+ cursor = await db.execute(+ f"SELECT data FROM {self._config.table} WHERE phone_number = ? ORDER BY DATETIME(created_at) DESC",+ (phone_number,),+ )+ rows = await cursor.fetchall()+ for row in rows:+ if not row:+ continue+ try:+ calls.append(CallModel.model_validate_json(row[0]))+ except ValidationError as e:+ _logger.warn(f'Error parsing call, "{e}"')+ return calls or None++ async def _init_db(self, db: SQLiteConnection):+ """+ Initialize the database.++ See: https://sqlite.org/cgi/src/doc/wal2/doc/wal2.md+ """+ _logger.info("First run, init database")+ # Optimize performance for concurrent writes+ await db.execute("PRAGMA journal_mode=WAL")+ # Create table+ await db.execute(+ f"CREATE TABLE IF NOT EXISTS {self._config.table} (id VARCHAR(36) PRIMARY KEY, phone_number TEXT, data TEXT, created_at TEXT)"+ )+ # Create indexes+ await db.execute(+ f"CREATE INDEX IF NOT EXISTS {self._config.table}_phone_number ON {self._config.table} (phone_number)"+ )+ await db.execute(+ f"CREATE INDEX IF NOT EXISTS {self._config.table}_created_at ON {self._config.table} (created_at)"+ )+ # Write changes to disk+ await db.commit()++ @asynccontextmanager+ async def _use_db(self) -> AsyncGenerator[SQLiteConnection, None]:+ # Create folder+ db_path = self._config.path+ first_run = False+ if not os.path.isfile(db_path):+ db_folder = db_path[: db_path.rfind("/")]+ os.makedirs(name=db_folder, exist_ok=True)+ first_run = True++ # Connect to DB+ async with sqlite_connect(+ autocommit=False,+ database=db_path,+ ) as db:+ if first_run:+ await self._init_db(db)+ yield dbdiff --git a/public_website/report.html b/public_website/report.htmlindex 1ec673b..e5364a2 100644--- a/public_website/report.html+++ b/public_website/report.html@@ -4,14 +4,14 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><script src="https://cdn.tailwindcss.com"></script>- <title>Claim report {{ call.claim.id }}</title>+ <title>Claim report {{ call.claim.claim_id }}</title></head><body class="container mx-auto px-4 bg-white text-sm"><div class="grid grid-cols-6 gap-4 m-4"><!-- Top introduction --><div class="col-span-full px-4 py-8"><h2 class="text-2xl">Hello {{ call.claim.policyholder_name }} 👋🏻</h2>- <p>Your claim <span class="font-mono">#{{ call.claim.id }}</span> of the {{ call.claim.created_at.strftime('%d %b %Y') }} is being processed.</p>+ <p>Your claim <span class="font-mono">#{{ call.claim.claim_id }}</span> of the {{ call.claim.created_at.strftime('%d %b %Y') }} is being processed.</p></div><!-- Claim details -->diff --git a/requirements.txt b/requirements.txtindex 0d99af2..e5de941 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,6 +1,7 @@aiosqlite==0.19.0azure-communication-callautomation==1.1.0azure-communication-sms==1.0.1+azure-cosmos==4.5.1azure-eventgrid==4.16.0azure-identity==1.15.0fastapi==0.108.0@@ -8,6 +9,7 @@ jinja2==3.1.3openai==1.7.1phonenumbers==8.13.27pydantic-extra-types==2.4.0+pydantic-settings==2.1.0python-dotenv==1.0.0pyyaml==6.0.1uvicorn==0.25.0