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

refacto: Use Functions Apps native HTTP handlers

Clémence Lesnée85272b51b8c
diff --git a/README.md b/README.md
index ceae050..bb22e6b 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ Insurance, IT support, customer service, and more. The bot can be customized in
# Ask the bot to call a phone number
data='{
"bot_company": "Contoso",
- "bot_name": "Marion",
+ "bot_name": "Amélie",
"phone_number": "+11234567890",
"task": "Assistant will help the customer with their digital workplace. Assistant is working for the IT support department. The objective is to help the customer with their issue and gather information in the claim.",
"agent_phone_number": "+33612345678",
@@ -140,34 +140,44 @@ graph LR
user(["User"])
subgraph "Claim AI"
- ai_search[("RAG\n(AI Search)")]
- app["App"]
- communication_service_sms["SMS gateway\n(Communication Services)"]
- communication_services["Call gateway\n(Communication Services)"]
+ ada["Embedding\n(ADA)"]
+ app["App\n(Functions App)"]
+ communication_services["Call & SMS gateway\n(Communication Services)"]
constent_safety["Moderation\n(Content Safety)"]
- db[("Conversations and claims\n(Cosmos DB or SQLite)")]
- event_grid[("Broker\n(Event Grid)")]
- gpt["GPT-4 Turbo\n(OpenAI)"]
+ db[("Conversations and claims\n(Cosmos DB / SQLite)")]
+ eventgrid["Broker\n(Event Grid)"]
+ gpt["LLM\n(GPT-4o)"]
+ queues[("Queues\n(Azure Storage)")]
redis[("Cache\n(Redis)")]
+ search[("RAG\n(AI Search)")]
+ sounds[("Sounds\n(Azure Storage)")]
+ sst["Speech-to-Text\n(Cognitive Services)"]
translation["Translation\n(Cognitive Services)"]
+ tts["Text-to-Speech\n(Cognitive Services)"]
end
app -- Answer with text --> communication_services
app -- Ask for translation --> translation
- app -- Few-shot training --> ai_search
+ app -- Ask to transfer --> communication_services
+ app -- Few-shot training --> search
app -- Generate completion --> gpt
app -- Get cached data --> redis
app -- Save conversation --> db
- app -- Send SMS report --> communication_service_sms
+ app -- Send SMS report --> communication_services
app -- Test for profanity --> constent_safety
- app -- Transfer to agent --> communication_services
- app -. Watch .-> event_grid
+ app -. Watch .-> queues
- communication_services -- Notifies --> event_grid
+ communication_services -- Generate voice --> tts
+ communication_services -- Load sound --> sounds
+ communication_services -- Notifies --> eventgrid
+ communication_services -- Send SMS --> user
communication_services -- Transfer to --> agent
+ communication_services -- Transform voice --> sst
communication_services -. Send voice .-> user
- communication_service_sms -- Send SMS --> user
+ eventgrid -- Push to --> queues
+
+ search -- Generate embeddings --> ada
user -- Call --> communication_services
```
@@ -254,7 +264,7 @@ workflow:
initiate:
agent_phone_number: "+33612345678"
bot_company: Contoso
- bot_name: Robert
+ bot_name: Amélie
lang: {}
communication_services:
@@ -302,8 +312,11 @@ workflow:
communication_services:
access_key: xxx
+ call_queue_name: call-33612345678
endpoint: https://xxx.france.communication.azure.com
phone_number: "+33612345678"
+ post_queue_name: post-33612345678
+ sms_queue_name: sms-33612345678
cognitive_service:
# Must be of type "AI services multi-service account"
@@ -623,7 +636,3 @@ prompts:
### Why no LLM framework is used?
At the time of development, no LLM framework was available to handle all of these features: streaming capability with multi-tools, backup models on availability issue, callbacks mechanisms in the triggered tools. So, OpenAI SDK is used directly and some algorithms are implemented to handle reliability.
-
-### What's missing in this project for production deployment?
-
-Mostly decoupling. Today, post-call intelligence is done with the BackgroundTasks implementation from Starlette. But this executes tasks in the worker same thread, after the HTTP reponse made. For production, a message broker like Azure Service Bus should be used (Dapr can ease your life by abstracting it from the code).
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 5fd8b97..13bd72b 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -24,6 +24,7 @@ var gptModelFullName = toLower('${gptModel}-${gptVersion}')
var adaModelFullName = toLower('${adaModel}-${adaVersion}')
var cosmosContainerName = 'calls-v3' // Third schema version
var localConfig = loadYamlContent('../config.yaml')
+var phonenumberSanitized = replace(localConfig.communication_services.phone_number, '+', '')
var config = {
public_domain: appUrl
monitoring: {
@@ -53,9 +54,11 @@ var config = {
}
communication_services: {
access_key: communicationServices.listKeys().primaryKey
+ call_queue_name: callQueue.name
endpoint: communicationServices.properties.hostName
phone_number: localConfig.communication_services.phone_number
- queue_name: communicationServicesQueue.name
+ post_queue_name: postQueue.name
+ sms_queue_name: smsQueue.name
}
sms: localConfig.sms
cognitive_service: {
@@ -208,11 +211,11 @@ resource functionApp 'Microsoft.Web/sites@2023-12-01' = {
alwaysReady: [
{
instanceCount: 1
- name: 'function:eventgrid_event_post'
+ name: 'function:communicationservices_event_post'
}
{
instanceCount: 1
- name: 'function:http_app_func'
+ name: 'function:call_event'
}
]
}
@@ -287,9 +290,19 @@ resource queueService 'Microsoft.Storage/storageAccounts/queueServices@2023-01-0
name: 'default'
}
-resource communicationServicesQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-01-01' = {
+resource callQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-01-01' = {
parent: queueService
- name: 'communication-services-${replace(localConfig.communication_services.phone_number, '+', '')}'
+ name: 'call-${phonenumberSanitized}'
+}
+
+resource smsQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-01-01' = {
+ parent: queueService
+ name: 'sms-${phonenumberSanitized}'
+}
+
+resource postQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-01-01' = {
+ parent: queueService
+ name: 'post-${phonenumberSanitized}'
}
resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01' = {
@@ -356,7 +369,7 @@ resource assignmentEventgridTopicQueueSender 'Microsoft.Authorization/roleAssign
resource eventgridSubscriptionCall 'Microsoft.EventGrid/systemTopics/eventSubscriptions@2024-06-01-preview' = {
parent: eventgridTopic
- name: '${prefix}-${replace(localConfig.communication_services.phone_number, '+', '')}'
+ name: '${prefix}-${phonenumberSanitized}'
properties: {
eventDeliverySchema: 'EventGridSchema'
deliveryWithResourceIdentity: {
@@ -367,7 +380,7 @@ resource eventgridSubscriptionCall 'Microsoft.EventGrid/systemTopics/eventSubscr
endpointType: 'StorageQueue'
properties: {
queueMessageTimeToLiveInSeconds: 60 // Short lived messages, only new call events
- queueName: communicationServicesQueue.name
+ queueName: callQueue.name
resourceId: storageAccount.id
}
}
@@ -391,7 +404,7 @@ resource eventgridSubscriptionCall 'Microsoft.EventGrid/systemTopics/eventSubscr
resource eventgridSubscriptionSms 'Microsoft.EventGrid/systemTopics/eventSubscriptions@2024-06-01-preview' = {
parent: eventgridTopic
- name: '${prefix}-${replace(localConfig.communication_services.phone_number, '+', '')}-sms'
+ name: '${prefix}-${phonenumberSanitized}-sms'
properties: {
eventDeliverySchema: 'EventGridSchema'
deliveryWithResourceIdentity: {
@@ -402,7 +415,7 @@ resource eventgridSubscriptionSms 'Microsoft.EventGrid/systemTopics/eventSubscri
endpointType: 'StorageQueue'
properties: {
queueMessageTimeToLiveInSeconds: -1 // Infinite persistence, SMS is async
- queueName: communicationServicesQueue.name
+ queueName: smsQueue.name
resourceId: storageAccount.id
}
}
diff --git a/function_app.py b/function_app.py
index 1ddf3e5..d785aa9 100644
--- a/function_app.py
+++ b/function_app.py
@@ -1,18 +1,13 @@
# First imports, to make sure the following logs are first
-from helpers.logging import logger
+from helpers.logging import logger, APP_NAME
from helpers.config import CONFIG
-logger.info(f"call-center-ai v{CONFIG.version}")
+logger.info(f"{APP_NAME} v{CONFIG.version}")
# General imports
-from typing import (
- Any,
- Literal,
- Optional,
- Union,
-)
+from typing import Any, Optional
from azure.communication.callautomation import (
CallAutomationClient,
PhoneNumberIdentifier,
@@ -20,28 +15,19 @@ from azure.communication.callautomation import (
from azure.core.credentials import AzureKeyCredential
from azure.core.messaging import CloudEvent
from azure.eventgrid import EventGridEvent, SystemEventNames
-from fastapi import (
- BackgroundTasks,
- FastAPI,
- Form,
- HTTPException,
- Request,
- Response,
- status,
-)
-from fastapi.responses import JSONResponse, HTMLResponse
+from helpers.pydantic_types.phone_numbers import PhoneNumber
from jinja2 import Environment, FileSystemLoader
from models.call import CallStateModel, CallGetModel, CallInitiateModel
from models.next import ActionEnum as NextActionEnum
+from twilio.twiml.messaging_response import MessagingResponse
from urllib.parse import quote_plus, urljoin
-import asyncio
from uuid import UUID
+import asyncio
import mistune
-from helpers.pydantic_types.phone_numbers import PhoneNumber
-from twilio.twiml.messaging_response import MessagingResponse
from helpers.call_events import (
on_call_connected,
on_call_disconnected,
+ on_end_call,
on_ivr_recognized,
on_new_call,
on_play_completed,
@@ -54,8 +40,10 @@ from helpers.call_events import (
on_transfer_error,
)
from helpers.call_utils import ContextEnum as CallContextEnum
-from models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatus
from htmlmin.minify import html_minify
+from http import HTTPStatus
+from models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatus
+from pydantic import TypeAdapter, ValidationError
import azure.functions as func
import json
@@ -88,33 +76,10 @@ _db = CONFIG.database.instance()
_search = CONFIG.ai_search.instance()
_sms = CONFIG.sms.instance()
-# FastAPI
-api = FastAPI(
- contact={
- "url": "https://github.com/clemlesne/call-center-ai",
- },
- description="AI-powered call center solution with Azure and OpenAI GPT.",
- license_info={
- "name": "Apache-2.0",
- "url": "https://github.com/clemlesne/call-center-ai/blob/master/LICENCE",
- },
- title="call-center-ai",
- version=CONFIG.version,
- servers=[
- {
- "url": CONFIG.public_domain,
- "description": "Current environment",
- },
- ],
-)
-
# Azure Functions
-app = func.AsgiFunctionApp(
- app=api,
- http_auth_level=func.AuthLevel.ANONYMOUS,
-)
+app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
-#
+# Communication Services callback
assert CONFIG.public_domain, "public_domain config is not set"
_COMMUNICATIONSERVICES_CALLABACK_TPL = urljoin(
str(CONFIG.public_domain),
@@ -123,21 +88,19 @@ _COMMUNICATIONSERVICES_CALLABACK_TPL = urljoin(
logger.info(f"Using call event URL {_COMMUNICATIONSERVICES_CALLABACK_TPL}")
- "/health/liveness",
- status_code=status.HTTP_204_NO_CONTENT,
- description="Liveness healthckeck, always returns 204, used to check if the API is up.",
- name="Get liveness",
+ "health/liveness",
+ methods=["GET"],
)
-async def health_liveness_get() -> None:
- pass
+async def health_liveness_get(req: func.HttpRequest) -> func.HttpResponse:
+ return func.HttpResponse(status_code=HTTPStatus.NO_CONTENT)
- "/health/readiness",
- description="Readiness healthckeck, returns the status of all components, and fails if one of them is not ready. If all components are ready, returns 200, otherwise 503.",
+ "health/readiness",
+ methods=["GET"],
)
-async def health_readiness_get() -> JSONResponse:
+async def health_readiness_get(req: func.HttpRequest) -> func.HttpResponse:
# Check all components in parallel
cache_check, db_check, search_check, sms_check = await asyncio.gather(
_cache.areadiness(), _db.areadiness(), _search.areadiness(), _sms.areadiness()
@@ -153,26 +116,33 @@ async def health_readiness_get() -> JSONResponse:
],
)
# If one of the checks fails, the whole readiness fails
- status_code = status.HTTP_200_OK
+ status_code = HTTPStatus.OK
for check in readiness.checks:
if check.status != ReadinessStatus.OK:
readiness.status = ReadinessStatus.FAIL
- status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ status_code = HTTPStatus.SERVICE_UNAVAILABLE
break
- return JSONResponse(
- content=readiness.model_dump(mode="json"),
+ return func.HttpResponse(
+ body=readiness.model_dump_json(indent=None),
+ mimetype="application/json",
status_code=status_code,
)
- "/report",
- description="Display the calls history for all phone numbers in a web page.",
- name="Search for reports (browser)",
+ "report",
+ methods=["GET"],
+ trigger_arg_name="req",
)
-async def report_get(
- phone_number: Optional[Union[PhoneNumber, Literal[""]]] = None,
-) -> HTMLResponse:
+async def report_get(req: func.HttpRequest) -> func.HttpResponse:
+ try:
+ phone_number = (
+ PhoneNumber(req.params["phone_number"])
+ if "phone_number" in req.params
+ else None
+ )
+ except Exception as e:
+ return _validation_error(e)
count = 100
calls, total = (
await _db.call_asearch_all(
@@ -191,20 +161,29 @@ async def report_get(
version=CONFIG.version,
)
render = html_minify(render) # Minify HTML
- return HTMLResponse(content=render)
+ return func.HttpResponse(
+ body=render,
+ mimetype="text/html",
+ status_code=HTTPStatus.OK,
+ )
- "/report/{call_id}",
- description="Display the call report in a web page.",
- name="Get a report (browser)",
+ "report/{call_id:guid}",
+ methods=["GET"],
+ trigger_arg_name="req",
)
-async def report_single_get(call_id: UUID) -> HTMLResponse:
+async def report_single_get(req: func.HttpRequest) -> func.HttpResponse:
+ try:
+ call_id = UUID(req.route_params["call_id"])
+ except Exception as e:
+ return _validation_error(e)
call = await _db.call_aget(call_id)
if not call:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Call {call_id} not found",
+ return func.HttpResponse(
+ body=f"Call {call_id} not found",
+ mimetype="text/plain",
+ status_code=HTTPStatus.NOT_FOUND,
)
template = _jinja.get_template("single.html.jinja")
render = await template.render_async(
@@ -216,42 +195,67 @@ async def report_single_get(call_id: UUID) -> HTMLResponse:
version=CONFIG.version,
)
render = html_minify(render) # Minify HTML
- return HTMLResponse(content=render)
+ return func.HttpResponse(
+ body=render,
+ mimetype="text/html",
+ status_code=HTTPStatus.OK,
+ )
# TODO: Add total (int) and calls (list) as a wrapper for the list of calls
- "/call",
- description="Search all calls by phone number.",
- name="Search calls",
+ "call/{phone_number}",
+ methods=["GET"],
+ trigger_arg_name="req",
)
-async def call_search_get(phone_number: PhoneNumber) -> list[CallGetModel]:
+async def call_search_get(req: func.HttpRequest) -> func.HttpResponse:
+ try:
+ phone_number = PhoneNumber(req.route_params["phone_number"])
+ except Exception as e:
+ return _validation_error(e)
calls, _ = await _db.call_asearch_all(phone_number=phone_number, count=1)
output = [CallGetModel.model_validate(call) for call in calls or []]
- return output
+ return func.HttpResponse(
+ body=TypeAdapter(list[CallGetModel]).dump_json(output),
+ mimetype="application/json",
+ status_code=HTTPStatus.OK,
+ )
- "/call/{call_id}",
- description="Get a call by its ID.",
- name="Get call",
+ "call/{call_id:guid}",
+ methods=["GET"],
+ trigger_arg_name="req",
)
-async def call_get(call_id: UUID) -> CallGetModel:
+async def call_get(req: func.HttpRequest) -> func.HttpResponse:
+ try:
+ call_id = UUID(req.route_params["call_id"])
+ except Exception as e:
+ return _validation_error(e)
call = await _db.call_aget(call_id)
if not call:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Call {call_id} not found",
+ return func.HttpResponse(
+ body=f"Call {call_id} not found",
+ mimetype="text/plain",
+ status_code=HTTPStatus.NOT_FOUND,
)
- return CallGetModel.model_validate(call)
+ return func.HttpResponse(
+ body=call.model_dump_json(indent=None),
+ mimetype="application/json",
+ status_code=HTTPStatus.OK,
+ )
- "/call",
- description="Initiate a call to a phone number.",
- name="Create call",
+ "call",
+ methods=["POST"],
+ trigger_arg_name="req",
)
-async def call_post(initiate: CallInitiateModel) -> CallGetModel:
+async def call_post(req: func.HttpRequest) -> func.HttpResponse:
+ try:
+ initiate = CallInitiateModel.model_validate_json(req.get_body())
+ except Exception as e:
+ return _validation_error(e)
url, call = await _communicationservices_event_url(initiate.phone_number, initiate)
call_connection_properties = _automation_client.create_call(
callback_url=url,
@@ -262,76 +266,115 @@ async def call_post(initiate: CallInitiateModel) -> CallGetModel:
logger.info(
f"Created call with connection id: {call_connection_properties.call_connection_id}"
)
- return CallGetModel.model_validate(call)
+ return func.HttpResponse(
+ body=CallGetModel.model_validate(call).model_dump_json(indent=None),
+ mimetype="application/json",
+ status_code=HTTPStatus.CREATED,
+ )
@app.queue_trigger(
- arg_name="msg",
+ arg_name="call",
connection="Storage",
- queue_name=CONFIG.communication_services.queue_name,
+ queue_name=CONFIG.communication_services.call_queue_name,
)
-async def eventgrid_event_post(msg: func.QueueMessage) -> None:
- background_tasks = BackgroundTasks()
- event = EventGridEvent.from_json(msg.get_body())
+async def call_event(
+ call: func.QueueMessage,
+) -> None:
+ event = EventGridEvent.from_json(call.get_body())
event_type = event.event_type
- logger.debug(f"Call inbound event {event_type} with data {event.data}")
+ logger.debug(f"Call event with data {event.data}")
+ if not event_type == SystemEventNames.AcsIncomingCallEventName:
+ logger.warning(f"Event {event_type} not supported")
+ return
- if event_type == SystemEventNames.AcsIncomingCallEventName:
- call_context: str = event.data["incomingCallContext"]
- phone_number = event.data["from"]["phoneNumber"]["value"]
- phone_number = PhoneNumber(phone_number)
- url, _ = await _communicationservices_event_url(phone_number)
- await on_new_call(
- callback_url=url,
- client=_automation_client,
- incoming_context=call_context,
- phone_number=phone_number,
- )
+ call_context: str = event.data["incomingCallContext"]
+ phone_number = PhoneNumber(event.data["from"]["phoneNumber"]["value"])
+ url, _ = await _communicationservices_event_url(phone_number)
+ await on_new_call(
+ callback_url=url,
+ client=_automation_client,
+ incoming_context=call_context,
+ phone_number=phone_number,
+ )
- elif event_type == SystemEventNames.AcsSmsReceivedEventName:
- message: str = event.data["message"]
- phone_number: str = event.data["from"]
- call = await _db.call_asearch_one(phone_number)
- if not call:
- logger.warning(f"Call for phone number {phone_number} not found")
- return
- await on_sms_received(
- background_tasks=background_tasks,
- call=call,
- client=_automation_client,
- message=message,
- )
- await background_tasks()
+ arg_name="sms",
+ connection="Storage",
+ queue_name=CONFIG.communication_services.sms_queue_name,
+)
+ arg_name="post",
+ connection="Storage",
+ queue_name=CONFIG.communication_services.post_queue_name,
+)
+async def sms_event(
+ sms: func.QueueMessage,
+ post: func.Out[str],
+) -> None:
+ event = EventGridEvent.from_json(sms.get_body())
+ event_type = event.event_type
+
+ logger.debug(f"SMS event with data {event.data}")
+ if not event_type == SystemEventNames.AcsSmsReceivedEventName:
+ logger.warning(f"Event {event_type} not supported")
+ return
+
+ message: str = event.data["message"]
+ phone_number: str = event.data["from"]
+ call = await _db.call_asearch_one(phone_number)
+ if not call:
+ logger.warning(f"Call for phone number {phone_number} not found")
+ return
+ await on_sms_received(
+ call=call,
+ client=_automation_client,
+ message=message,
+ post_call_callback=lambda _call: _trigger_post_call_event(
+ call=_call, post=post
+ ),
+ )
- "/communicationservices/event/{call_id}/{secret}",
- description="Handle callbacks from Azure Communication Services.",
- name="Receive Communication Services event",
- status_code=status.HTTP_204_NO_CONTENT,
+ "communicationservices/event/{call_id:guid}/{secret:length(16)}",
+ methods=["POST"],
+ trigger_arg_name="req",
+)
+ arg_name="post",
+ connection="Storage",
+ queue_name=CONFIG.communication_services.post_queue_name,
)
async def communicationservices_event_post(
- request: Request,
- background_tasks: BackgroundTasks,
- call_id: UUID,
- secret: str,
-) -> None:
+ post: func.Out[str],
+ req: func.HttpRequest,
+) -> func.HttpResponse:
+ try:
+ call_id = UUID(req.route_params["call_id"])
+ secret: str = req.route_params["secret"]
+ except Exception as e:
+ return _validation_error(e)
await asyncio.gather(
*[
_communicationservices_event_worker(
- background_tasks, event_dict, call_id, secret
+ call_id=call_id,
+ event_dict=event_dict,
+ post=post,
+ secret=secret,
)
- for event_dict in await request.json()
+ for event_dict in req.get_json()
]
)
+ return func.HttpResponse(status_code=HTTPStatus.NO_CONTENT)
async def _communicationservices_event_worker(
- background_tasks: BackgroundTasks,
- event_dict: dict,
call_id: UUID,
+ event_dict: dict,
+ post: func.Out[str],
secret: str,
) -> None:
call = await _db.call_aget(call_id)
@@ -369,9 +412,11 @@ async def _communicationservices_event_worker(
elif event_type == "Microsoft.Communication.CallDisconnected": # Call hung up
await on_call_disconnected(
- background_tasks=background_tasks,
call=call,
client=_automation_client,
+ post_call_callback=lambda _call: _trigger_post_call_event(
+ call=_call, post=post
+ ),
)
elif (
@@ -383,19 +428,23 @@ async def _communicationservices_event_worker(
speech_text: Optional[str] = event.data["speechResult"]["speech"]
if speech_text:
await on_speech_recognized(
- background_tasks=background_tasks,
call=call,
client=_automation_client,
text=speech_text,
+ post_call_callback=lambda _call: _trigger_post_call_event(
+ call=_call, post=post
+ ),
)
elif recognition_result == "choices": # Handle IVR
label_detected: str = event.data["choiceResult"]["label"]
await on_ivr_recognized(
- background_tasks=background_tasks,
call=call,
client=_automation_client,
label=label_detected,
+ post_call_callback=lambda _call: _trigger_post_call_event(
+ call=_call, post=post
+ ),
)
elif (
@@ -423,10 +472,12 @@ async def _communicationservices_event_worker(
elif event_type == "Microsoft.Communication.PlayCompleted": # Media played
await on_play_completed(
- background_tasks=background_tasks,
call=call,
client=_automation_client,
contexts=operation_contexts,
+ post_call_callback=lambda _call: _trigger_post_call_event(
+ call=_call, post=post
+ ),
)
elif event_type == "Microsoft.Communication.PlayFailed": # Media play failed
@@ -455,6 +506,29 @@ async def _communicationservices_event_worker(
) # TODO: Do not persist on every event, this is simpler but not efficient
+ arg_name="post",
+ connection="Storage",
+ queue_name=CONFIG.communication_services.post_queue_name,
+)
+async def post_event(
+ post: func.QueueMessage,
+) -> None:
+ call = CallStateModel.model_validate_json(post.get_body())
+ logger.debug(f"Post event received for call {call}")
+ await on_end_call(call)
+
+
+def _trigger_post_call_event(
+ call: CallStateModel,
+ post: func.Out[str],
+) -> None:
+ """
+ Shortcut to add post-call intelligence to the queue.
+ """
+ post.set(call.model_dump_json(indent=None))
+
+
async def _communicationservices_event_url(
phone_number: PhoneNumber, initiate: Optional[CallInitiateModel] = None
) -> tuple[str, CallStateModel]:
@@ -483,46 +557,70 @@ async def _communicationservices_event_url(
# TODO: Secure this endpoint with a secret, either in the Authorization header or in the URL
- "/twilio/sms",
- description="Handle incoming SMS event from Twilio.",
- name="Receive Twilio SMS event",
- responses={
- status.HTTP_200_OK: {
- "content": {
- "application/xml": {
- "example": str(MessagingResponse()),
- },
- },
- },
- },
+ "twilio/sms",
+ methods=["POST"],
+ trigger_arg_name="req",
+)
+ arg_name="post",
+ connection="Storage",
+ queue_name=CONFIG.communication_services.post_queue_name,
)
-async def twilio_sms(
- background_tasks: BackgroundTasks,
- Body: str = Form(alias="Body"),
- From: str = Form(alias="From"),
-) -> Response:
+async def twilio_sms_post(
+ post: func.Out[str],
+ req: func.HttpRequest,
+) -> func.HttpResponse:
"""
Handle incoming SMS event from Twilio.
"""
- phone_number = PhoneNumber(From)
+ if not req.form:
+ return _validation_error(Exception("No form data"))
+ try:
+ phone_number = PhoneNumber(req.form["From"])
+ message: str = req.form["Body"]
+ except Exception as e:
+ return _validation_error(e)
call = await _db.call_asearch_one(phone_number)
if not call:
logger.warning(f"Call for phone number {phone_number} not found")
else:
event_status = await on_sms_received(
call=call,
- message=Body,
+ message=message,
client=_automation_client,
- background_tasks=background_tasks,
+ post_call_callback=lambda _call: _trigger_post_call_event(
+ call=_call, post=post
+ ),
)
if not event_status:
- return Response(
- background=background_tasks,
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
- return Response(
- background=background_tasks,
- content=str(MessagingResponse()), # Twilio expects an empty response everytime
- media_type="application/xml",
+ return func.HttpResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
+ return func.HttpResponse(
+ body=str(MessagingResponse()), # Twilio expects an empty response everytime
+ mimetype="application/xml",
+ status_code=HTTPStatus.OK,
+ )
+
+
+def _validation_error(
+ e: Exception,
+) -> func.HttpResponse:
+ body: dict[str, Any] = {
+ "error": {
+ "message": "Validation error",
+ "details": [],
+ }
+ }
+ if isinstance(e, ValidationError):
+ body["error"][
+ "details"
+ ] = e.errors() # Pydantic returns well formatted errors, use them
+ elif isinstance(e, ValueError):
+ body["error"]["details"] = str(
+ e
+ ) # TODO: Could it expose sensitive information?
+ return func.HttpResponse(
+ body=json.dumps(body),
+ mimetype="application/json",
+ status_code=HTTPStatus.BAD_REQUEST,
)
diff --git a/helpers/call_events.py b/helpers/call_events.py
index d8d4060..2f61583 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Callable, Optional
from azure.communication.callautomation import (
CallAutomationClient,
DtmfTone,
@@ -28,10 +28,9 @@ from helpers.call_utils import (
handle_recognize_text,
handle_transfer,
)
-from fastapi import BackgroundTasks
-import asyncio
-from models.next import NextModel
from helpers.call_llm import llm_completion, llm_model, load_llm_chat
+from models.next import NextModel
+import asyncio
_sms = CONFIG.sms.instance()
@@ -99,19 +98,23 @@ async def on_call_connected(
@tracer.start_as_current_span("on_call_disconnected")
async def on_call_disconnected(
- background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
+ post_call_callback: Callable[[CallStateModel], None],
) -> None:
logger.info("Call disconnected")
- await _handle_hangup(background_tasks, client, call)
+ await _handle_hangup(
+ call=call,
+ client=client,
+ post_call_callback=post_call_callback,
+ )
@tracer.start_as_current_span("on_speech_recognized")
async def on_speech_recognized(
- background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
+ post_call_callback: Callable[[CallStateModel], None],
text: str,
) -> None:
logger.info(f"Voice recognition: {text}")
@@ -120,13 +123,13 @@ async def on_speech_recognized(
call
) # Save ASAP in DB allowing SMS answers to be more "in-sync"
await handle_clear_queue(
- call=call, client=client
+ call=call,
+ client=client,
) # When the user speak, the conversation should continue based on its last message
call = await load_llm_chat(
- background_tasks=background_tasks,
call=call,
client=client,
- post_call_intelligence=_post_call_intelligence,
+ post_call_callback=post_call_callback,
)
@@ -143,10 +146,10 @@ async def on_speech_timeout_error(
res_context = None
if call.voice_recognition_retry < 10:
call.voice_recognition_retry += 1
- trigger_timeout = True # Should re-trigger an error or the LLM
+ timeout_error = True # Should re-trigger an error or the LLM
text = await CONFIG.prompts.tts.timeout_silence(call)
else:
- trigger_timeout = False # Shouldn't trigger anything, as call is ending
+ timeout_error = False # Shouldn't trigger anything, as call is ending
res_context = CallContextEnum.GOODBYE
text = await CONFIG.prompts.tts.goodbye(call)
@@ -156,7 +159,7 @@ async def on_speech_timeout_error(
context=res_context,
store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
text=text,
- trigger_timeout=trigger_timeout,
+ timeout_error=timeout_error,
)
@@ -182,10 +185,10 @@ async def on_speech_unknown_error(
@tracer.start_as_current_span("on_play_completed")
async def on_play_completed(
- background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
contexts: Optional[list[CallContextEnum]],
+ post_call_callback: Callable[[CallStateModel], None],
) -> None:
logger.debug("Play completed")
@@ -197,7 +200,11 @@ async def on_play_completed(
or CallContextEnum.GOODBYE in contexts
): # Call ended
logger.info("Ending call")
- await _handle_hangup(background_tasks, client, call)
+ await _handle_hangup(
+ call=call,
+ client=client,
+ post_call_callback=post_call_callback,
+ )
elif CallContextEnum.CONNECT_AGENT in contexts: # Call transfer
logger.info("Initiating transfer call initiated")
@@ -228,10 +235,10 @@ async def on_play_error(error_code: int) -> None:
@tracer.start_as_current_span("on_ivr_recognized")
async def on_ivr_recognized(
- client: CallAutomationClient,
call: CallStateModel,
+ client: CallAutomationClient,
label: str,
- background_tasks: BackgroundTasks,
+ post_call_callback: Callable[[CallStateModel], None],
) -> None:
try:
lang = next(
@@ -261,13 +268,12 @@ async def on_ivr_recognized(
client=client,
style=MessageStyleEnum.CHEERFUL,
text=await CONFIG.prompts.tts.welcome_back(call),
- trigger_timeout=False, # Do not trigger timeout, as the chat will continue
+ timeout_error=False, # Do not trigger timeout, as the chat will continue
)
call = await load_llm_chat(
- background_tasks=background_tasks,
call=call,
client=client,
- post_call_intelligence=_post_call_intelligence,
+ post_call_callback=post_call_callback,
)
@@ -294,10 +300,10 @@ async def on_transfer_error(
@tracer.start_as_current_span("on_sms_received")
async def on_sms_received(
- background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
message: str,
+ post_call_callback: Callable[[CallStateModel], None],
) -> bool:
logger.info(f"SMS received from {call.initiate.phone_number}: {message}")
call.messages.append(
@@ -315,18 +321,17 @@ async def on_sms_received(
else:
logger.info("Call in progress, answering with voice")
await load_llm_chat(
- background_tasks=background_tasks,
call=call,
client=client,
- post_call_intelligence=_post_call_intelligence,
+ post_call_callback=post_call_callback,
)
return True
async def _handle_hangup(
- background_tasks: BackgroundTasks,
- client: CallAutomationClient,
call: CallStateModel,
+ client: CallAutomationClient,
+ post_call_callback: Callable[[CallStateModel], None],
) -> None:
await handle_hangup(client=client, call=call)
call.messages.append(
@@ -336,11 +341,11 @@ async def _handle_hangup(
action=MessageActionEnum.HANGUP,
)
)
- _post_call_intelligence(call, background_tasks)
+ post_call_callback(call)
-def _post_call_intelligence(
- call: CallStateModel, background_tasks: BackgroundTasks
+async def on_end_call(
+ call: CallStateModel,
) -> None:
"""
Shortcut to run all post-call intelligence tasks in background.
@@ -355,12 +360,15 @@ def _post_call_intelligence(
"Call ended before any interaction, skipping post-call intelligence"
)
return
- background_tasks.add_task(_post_call_next, call)
- background_tasks.add_task(_post_call_sms, call)
- background_tasks.add_task(_post_call_synthesis, call)
+
+ await asyncio.gather(
+ _intelligence_next(call),
+ _intelligence_sms(call),
+ _intelligence_synthesis(call),
+ )
-async def _post_call_sms(call: CallStateModel) -> None:
+async def _intelligence_sms(call: CallStateModel) -> None:
"""
Send an SMS report to the customer.
"""
@@ -401,7 +409,7 @@ async def _post_call_sms(call: CallStateModel) -> None:
await _db.call_aset(call)
-async def _post_call_synthesis(call: CallStateModel) -> None:
+async def _intelligence_synthesis(call: CallStateModel) -> None:
"""
Synthesize the call and store it to the model.
"""
@@ -442,7 +450,7 @@ async def _post_call_synthesis(call: CallStateModel) -> None:
await _db.call_aset(call)
-async def _post_call_next(call: CallStateModel) -> None:
+async def _intelligence_next(call: CallStateModel) -> None:
"""
Generate next action for the call.
"""
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 7748601..c01ee51 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -17,7 +17,6 @@ from helpers.call_utils import (
handle_recognize_text,
tts_sentence_split,
)
-from fastapi import BackgroundTasks
from helpers.llm_tools import LlmPlugins
import asyncio
from helpers.llm_worker import (
@@ -110,10 +109,9 @@ def _llm_completion_system(
async def load_llm_chat(
- background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
- post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],
+ post_call_callback: Callable[[CallStateModel], None],
_iterations_remaining: int = 3,
) -> CallStateModel:
"""
@@ -127,7 +125,7 @@ async def load_llm_chat(
should_play_sound = True
- async def _user_callback(text: str, style: MessageStyleEnum) -> None:
+ async def _tts_callback(text: str, style: MessageStyleEnum) -> None:
"""
Send back the TTS to the user.
"""
@@ -145,7 +143,7 @@ async def load_llm_chat(
client=client,
style=style,
text=text,
- trigger_timeout=False, # Voice will continue, don't trigger
+ timeout_error=False, # Voice will continue, don't trigger
)
await _db.call_aset(
@@ -165,12 +163,11 @@ async def load_llm_chat(
# Chat
chat_task = asyncio.create_task(
_execute_llm_chat(
- background_tasks=background_tasks,
call=call,
client=client,
- post_call_intelligence=post_call_intelligence,
+ post_call_callback=post_call_callback,
use_tools=_iterations_remaining > 0,
- user_callback=_user_callback,
+ tts_callback=_tts_callback,
)
)
@@ -252,9 +249,9 @@ async def load_llm_chat(
await handle_recognize_text(
call=call,
client=client,
- trigger_timeout=False, # Voice will continue, don't trigger
store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
text=await CONFIG.prompts.tts.timeout_loading(call),
+ timeout_error=False, # Voice will continue, don't trigger
)
elif (
@@ -278,7 +275,7 @@ async def load_llm_chat(
logger.warning("Maximum retries reached, stopping chat")
content = await CONFIG.prompts.tts.error(call)
style = MessageStyleEnum.NONE
- await _user_callback(content, style)
+ await _tts_callback(content, style)
call.messages.append(
MessageModel(
content=content,
@@ -290,33 +287,37 @@ async def load_llm_chat(
else: # Retry chat after an error
logger.info(f"Retrying chat, {_iterations_remaining - 1} remaining")
return await load_llm_chat(
- background_tasks=background_tasks,
call=call,
client=client,
- post_call_intelligence=post_call_intelligence,
+ post_call_callback=post_call_callback,
_iterations_remaining=_iterations_remaining - 1,
)
-
- elif continue_chat: # Contiue chat
- logger.info(f"Continuing chat, {_iterations_remaining - 1} remaining")
- return await load_llm_chat(
- background_tasks=background_tasks,
- call=call,
- client=client,
- post_call_intelligence=post_call_intelligence,
- _iterations_remaining=_iterations_remaining - 1,
- )
+ else:
+ if continue_chat: # Contiue chat
+ logger.info(f"Continuing chat, {_iterations_remaining - 1} remaining")
+ return await load_llm_chat(
+ call=call,
+ client=client,
+ post_call_callback=post_call_callback,
+ _iterations_remaining=_iterations_remaining - 1,
+ )
+ else:
+ await handle_recognize_text(
+ call=call,
+ client=client,
+ style=MessageStyleEnum.NONE,
+ text=None,
+ ) # Trigger an empty text to recognize and generate timeout error if user does not speak
return call
async def _execute_llm_chat(
- background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
- post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],
+ post_call_callback: Callable[[CallStateModel], None],
+ tts_callback: Callable[[str, MessageStyleEnum], Awaitable],
use_tools: bool,
- user_callback: Callable[[str, MessageStyleEnum], Awaitable],
) -> Tuple[bool, bool, CallStateModel]:
"""
Perform the chat with the LLM model.
@@ -335,10 +336,10 @@ async def _execute_llm_chat(
logger.debug("Running LLM chat")
content_full = ""
- async def _tools_callback(text: str, style: MessageStyleEnum) -> None:
+ async def _buffer_callback(text: str, style: MessageStyleEnum) -> None:
nonlocal content_full
content_full += f" {text}"
- await user_callback(text, style)
+ await tts_callback(text, style)
async def _content_callback(
buffer: str, style: MessageStyleEnum
@@ -349,7 +350,7 @@ async def _execute_llm_chat(
)
new_style = local_style or style
if local_content:
- await user_callback(local_content, new_style)
+ await tts_callback(local_content, new_style)
return new_style
# Build RAG
@@ -376,10 +377,8 @@ async def _execute_llm_chat(
plugins = LlmPlugins(
call=call,
client=client,
- post_call_intelligence=lambda call: post_call_intelligence(
- call, background_tasks
- ),
- user_callback=_tools_callback,
+ post_call_callback=post_call_callback,
+ tts_callback=_buffer_callback,
)
tools = []
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index 471c6fa..c389d63 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -68,7 +68,7 @@ async def _handle_recognize_media(
contexts: Optional[list[ContextEnum]],
end_silence: Optional[int],
style: MessageStyleEnum,
- text: str,
+ text: Optional[str],
) -> None:
"""
Play a media to a call participant and start recognizing the response.
@@ -82,11 +82,15 @@ async def _handle_recognize_media(
input_type=RecognizeInputType.SPEECH,
interrupt_prompt=True,
operation_context=json.dumps(contexts) if contexts else None,
- play_prompt=_audio_from_text(
- call=call,
- style=style,
- text=text,
- ),
+ play_prompt=(
+ _audio_from_text(
+ call=call,
+ style=style,
+ text=text,
+ )
+ if text
+ else None
+ ), # If no text is provided, only recognize
speech_language=call.lang.short_code,
target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore
)
@@ -127,35 +131,46 @@ async def handle_media(
async def handle_recognize_text(
- client: CallAutomationClient,
call: CallStateModel,
- text: str,
- trigger_timeout: bool = True,
+ client: CallAutomationClient,
+ text: Optional[str],
context: Optional[ContextEnum] = None,
- style: MessageStyleEnum = MessageStyleEnum.NONE,
store: bool = True,
+ style: MessageStyleEnum = MessageStyleEnum.NONE,
+ timeout_error: bool = True,
) -> None:
"""
Play a text to a call participant and start recognizing the response.
If `store` is `True`, the text will be stored in the call messages. Starts by playing text, then the "ready" sound, and finally starts recognizing the response.
"""
+ timeout_value = 5 # Wait 5 seconds for the user to speak and end the recognition
contexts = [context] if context else []
+
+ if not text: # Only recognize
+ contexts.append(ContextEnum.LAST_CHUNK)
+ await _handle_recognize_media(
+ call=call,
+ client=client,
+ contexts=contexts,
+ end_silence=timeout_value,
+ style=style,
+ text=None,
+ )
+ return
+
chunks = await _chunk_before_tts(
call=call,
store=store,
style=style,
text=text,
)
-
for i, chunk in enumerate(chunks):
context = None
end_silence = None
if i == len(chunks) - 1: # Last chunk
- end_silence = (
- 5 # Wait 5 seconds for the user to speak and end the recognition
- )
- if trigger_timeout:
+ end_silence = timeout_value
+ if timeout_error:
contexts.append(ContextEnum.LAST_CHUNK)
await _handle_recognize_media(
call=call,
diff --git a/helpers/config_models/communication_services.py b/helpers/config_models/communication_services.py
index 228ff79..049dba3 100644
--- a/helpers/config_models/communication_services.py
+++ b/helpers/config_models/communication_services.py
@@ -1,9 +1,11 @@
from helpers.pydantic_types.phone_numbers import PhoneNumber
-from pydantic import SecretStr, BaseModel
+from pydantic import SecretStr, BaseModel, computed_field
class CommunicationServicesModel(BaseModel):
access_key: SecretStr
+ call_queue_name: str
endpoint: str
phone_number: PhoneNumber
- queue_name: str
+ post_queue_name: str
+ sms_queue_name: str
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index 819f279..68b145f 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -1,6 +1,5 @@
from azure.core.exceptions import HttpResponseError
from datetime import datetime, UTC
-from fastapi.encoders import jsonable_encoder
from functools import cached_property
from logging import Logger
from models.call import CallStateModel
@@ -365,7 +364,7 @@ class LlmModel(BaseModel):
self.chat_system_tpl,
actions=", ".join([action.value for action in MessageActionEnum]),
bot_company=call.initiate.bot_company,
- claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
+ claim=json.dumps(call.claim),
default_lang=call.lang.human_name,
reminders=TypeAdapter(list[ReminderModel])
.dump_json(call.reminders, exclude_none=True)
@@ -380,7 +379,7 @@ class LlmModel(BaseModel):
self.sms_summary_system_tpl,
bot_company=call.initiate.bot_company,
bot_name=call.initiate.bot_name,
- claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
+ claim=json.dumps(call.claim),
default_lang=call.lang.human_name,
messages=TypeAdapter(list[MessageModel])
.dump_json(call.messages, exclude_none=True)
@@ -394,7 +393,7 @@ class LlmModel(BaseModel):
def synthesis_short_system(self, call: CallStateModel) -> str:
return self._return(
self.synthesis_short_system_tpl,
- claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
+ claim=json.dumps(call.claim),
messages=TypeAdapter(list[MessageModel])
.dump_json(call.messages, exclude_none=True)
.decode(),
@@ -407,7 +406,7 @@ class LlmModel(BaseModel):
def synthesis_long_system(self, call: CallStateModel) -> str:
return self._return(
self.synthesis_long_system_tpl,
- claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
+ claim=json.dumps(call.claim),
messages=TypeAdapter(list[MessageModel])
.dump_json(call.messages, exclude_none=True)
.decode(),
@@ -430,7 +429,7 @@ class LlmModel(BaseModel):
return self._return(
self.citations_system_tpl,
- claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
+ claim=json.dumps(call.claim),
reminders=TypeAdapter(list[ReminderModel])
.dump_json(call.reminders, exclude_none=True)
.decode(),
@@ -441,7 +440,7 @@ class LlmModel(BaseModel):
return self._return(
self.next_system_tpl,
actions=", ".join([action.value for action in NextActionEnum]),
- claim=json.dumps(jsonable_encoder(call.claim, exclude_none=True)),
+ claim=json.dumps(call.claim),
messages=TypeAdapter(list[MessageModel])
.dump_json(call.messages, exclude_none=True)
.decode(),
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index 3da29d4..9562614 100644
--- a/helpers/llm_tools.py
+++ b/helpers/llm_tools.py
@@ -31,21 +31,21 @@ class UpdateClaimDict(TypedDict):
class LlmPlugins:
call: CallStateModel
client: CallAutomationClient
- post_call_intelligence: Callable[[CallStateModel], None]
+ post_call_callback: Callable[[CallStateModel], None]
style: MessageStyleEnum = MessageStyleEnum.NONE
- user_callback: Callable[[str, MessageStyleEnum], Awaitable]
+ tts_callback: Callable[[str, MessageStyleEnum], Awaitable]
def __init__(
self,
call: CallStateModel,
client: CallAutomationClient,
- post_call_intelligence: Callable[[CallStateModel], None],
- user_callback: Callable[[str, MessageStyleEnum], Awaitable],
+ post_call_callback: Callable[[CallStateModel], None],
+ tts_callback: Callable[[str, MessageStyleEnum], Awaitable],
):
self.call = call
self.client = client
- self.post_call_intelligence = post_call_intelligence
- self.user_callback = user_callback
+ self.post_call_callback = post_call_callback
+ self.tts_callback = tts_callback
async def end_call(self) -> str:
"""
@@ -68,7 +68,7 @@ class LlmPlugins:
client=self.client,
context=CallContextEnum.GOODBYE,
text=await CONFIG.prompts.tts.goodbye(self.call),
- trigger_timeout=False, # Shouldn't trigger anything, as call is ending
+ timeout_error=False, # Shouldn't trigger anything, as call is ending
)
return "Call ended"
@@ -90,9 +90,9 @@ class LlmPlugins:
- Approval from the customer must be explicitely given (e.g. 'I want to create a new claim')
- This should be used only when the subject is totally different
"""
- await self.user_callback(customer_response, self.style)
+ await self.tts_callback(customer_response, self.style)
# Launch post-call intelligence for the current call
- self.post_call_intelligence(self.call)
+ self.post_call_callback(self.call)
# Store the last message and use it at first message of the new claim
last_message = self.call.messages[-1]
call = CallStateModel(
@@ -145,7 +145,7 @@ class LlmPlugins:
- If a reminder already exists, it will be updated with the new values
- The due date should be in the future
"""
- await self.user_callback(customer_response, self.style)
+ await self.tts_callback(customer_response, self.style)
# Check if reminder already exists, if so update it
for reminder in self.call.reminders:
@@ -215,7 +215,7 @@ class LlmPlugins:
- For values, it is OK to approximate dates if the customer is not precise (e.g., "last night" -> today 04h, "I'm stuck on the highway" -> now)
- It is best to update multiple fields at once
"""
- await self.user_callback(customer_response, self.style)
+ await self.tts_callback(customer_response, self.style)
# Update all claim fields
res = "# Updated fields"
for field in updates:
@@ -254,8 +254,8 @@ class LlmPlugins:
call=self.call,
client=self.client,
context=CallContextEnum.CONNECT_AGENT,
- trigger_timeout=False, # Shouldn't trigger anything, as conversation with Assistant is ending
text=await CONFIG.prompts.tts.end_call_to_connect_agent(self.call),
+ timeout_error=False, # Shouldn't trigger anything, as conversation with Assistant is ending
)
return "Transferring to human agent"
@@ -280,7 +280,7 @@ class LlmPlugins:
# Searchable topics
contract, law, regulation, article, procedure, guide
"""
- await self.user_callback(customer_response, self.style)
+ await self.tts_callback(customer_response, self.style)
# Execute in parallel
tasks = await asyncio.gather(
*[
@@ -334,7 +334,7 @@ class LlmPlugins:
- 'I am stuck in a car in fire'
- 'My neighbor is having a heart attack'
"""
- await self.user_callback(customer_response, self.style)
+ await self.tts_callback(customer_response, self.style)
# TODO: Implement notification to emergency services for production usage
logger.info(
f"Notifying {service}, location {location}, contact {contact}, reason {reason}."
@@ -360,7 +360,7 @@ class LlmPlugins:
- Confirm a detail like a reference number, if there is a misunderstanding
- Send a confirmation, if the customer wants to have a written proof
"""
- await self.user_callback(customer_response, self.style)
+ await self.tts_callback(customer_response, self.style)
success = await _sms.asend(
content=message,
phone_number=self.call.initiate.phone_number,
diff --git a/helpers/logging.py b/helpers/logging.py
index 3af4835..d8184f8 100644
--- a/helpers/logging.py
+++ b/helpers/logging.py
@@ -7,9 +7,11 @@ from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from os import environ
+APP_NAME = "call-center-ai"
+
# Logger
basicConfig(level=CONFIG.monitoring.logging.sys_level.value)
-logger = getLogger("call-center-ai")
+logger = getLogger(APP_NAME)
logger.setLevel(CONFIG.monitoring.logging.app_level.value)
# OpenTelemetry
@@ -21,5 +23,5 @@ AioHttpClientInstrumentor().instrument() # Instrument aiohttp
HTTPXClientInstrumentor().instrument() # Instrument httpx
tracer = trace.get_tracer(
instrumenting_library_version=CONFIG.version,
- instrumenting_module_name="com.github.clemlesne.call-center-ai",
+ instrumenting_module_name=f"com.github.clemlesne.{APP_NAME}",
) # Create a tracer that will be used in the app
diff --git a/host.json b/host.json
index fdf67a0..03d5449 100644
--- a/host.json
+++ b/host.json
@@ -21,7 +21,8 @@
"queues": {
"batchSize": 16,
"maxDequeueCount": 3,
- "maxPollingInterval": "00:00:02"
+ "maxPollingInterval": "00:00:02",
+ "visibilityTimeout": "00:00:01"
}
}
}
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index 31c81aa..a029eed 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -57,7 +57,7 @@ class SqliteStore(IStore):
async def call_aset(self, call: CallStateModel) -> bool:
# TODO: Catch exceptions and return False if something goes wrong
- data = call.model_dump_json(exclude_none=True)
+ data = call.model_dump_json(indent=None, exclude_none=True)
logger.debug(f"Saving call {call.call_id}: {data}")
async with self._use_db() as db:
await db.execute(
diff --git a/requirements.txt b/requirements.txt
index d512cac..d4526cb 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -12,13 +12,11 @@ azure-monitor-opentelemetry==1.4.2
azure-search-documents==11.6.0b3
azure-storage-queue==12.10.0
django-htmlmin==0.11.0
-fastapi==0.111.0
jinja2==3.1.4
json-repair==0.20.1
mistune==3.0.2
openai==1.30.3
opentelemetry-instrumentation-aiohttp-client==0.45b0
-opentelemetry-instrumentation-fastapi==0.45b0
opentelemetry-instrumentation-httpx==0.45b0
opentelemetry-instrumentation-openai==0.21.0
opentelemetry-instrumentation-redis==0.45b0
diff --git a/tests/conftest.py b/tests/conftest.py
index 65420c1..e18c60d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,13 +1,12 @@
from azure.identity import ManagedIdentityCredential, get_bearer_token_provider
from deepeval.models.gpt_model import GPTModel
-from fastapi import BackgroundTasks
from helpers.config import CONFIG
from helpers.logging import logger
from langchain_core.language_models import BaseChatModel
from langchain_openai import AzureChatOpenAI
from models.call import CallStateModel, CallInitiateModel
from textwrap import dedent
-from typing import Any, Callable, Optional, Tuple, Union
+from typing import Any, Callable, Tuple, Union
import hashlib
import pytest
import random
@@ -79,11 +78,6 @@ class CallConnectionClientMock(CallConnectionClient):
logger.info("hang_up, ignoring")
-def background_tasks() -> BackgroundTasks:
- return BackgroundTasks()
-
-
@pytest.fixture
def random_text() -> str:
text = "".join(random.choice(string.printable) for _ in range(100))
diff --git a/tests/llm.py b/tests/llm.py
index 664d8c9..ab10852 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -7,7 +7,6 @@ from deepeval.metrics import (
)
from deepeval.models.gpt_model import GPTModel
from deepeval.test_case import LLMTestCase
-from fastapi import BackgroundTasks
from helpers.call_events import (
on_speech_recognized,
on_call_connected,
@@ -146,7 +145,6 @@ from tests.conftest import CallAutomationClientMock
@pytest.mark.asyncio # Allow async functions
@pytest.mark.repeat(3) # Catch non deterministic issues
async def test_llm(
- background_tasks: BackgroundTasks,
call: CallStateModel,
claim_tests_excl: list[str],
claim_tests_incl: list[str],
@@ -182,17 +180,15 @@ async def test_llm(
call=call,
client=client,
)
- await background_tasks()
# Simulate conversation with speech recognition
for input in inputs:
await on_speech_recognized(
- background_tasks=background_tasks,
call=call,
client=client,
+ post_call_callback=lambda _call: None, # Disable post call
text=input,
)
- await background_tasks()
# Remove newlines for log comparison
actual_output = _remove_newlines(actual_output)