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

breaking: Report URL are now displaying list of every calls made

Clémence Lesné76118fc90442
diff --git a/main.py b/main.py
index c625c6b..4f8dbf5 100644
--- a/main.py
+++ b/main.py
@@ -10,6 +10,7 @@ _logger.info(f"call-center-ai v{CONFIG.version}")
# General imports
from typing import (
Any,
+ Literal,
Optional,
Union,
)
@@ -147,16 +148,25 @@ api.mount("/static", StaticFiles(directory="public_website/static"))
@api.get(
- "/report/{phone_number}",
- description="Display the history of calls in a web page.",
- name="Get call history in the browser",
+ "/report",
+ description="Display the calls history for all phone numbers in a web page.",
+ name="Search for reports (browser)",
)
-async def report_history_get(phone_number: PhoneNumber) -> HTMLResponse:
- calls = await _db.call_asearch_all(phone_number) or []
-
- template = _jinja.get_template("history.html.jinja")
+async def report_get(
+ phone_number: Optional[Union[PhoneNumber, Literal[""]]] = None,
+) -> HTMLResponse:
+ count = 100
+ calls = (
+ await _db.call_asearch_all(
+ count=count,
+ phone_number=phone_number or None,
+ )
+ or []
+ )
+ template = _jinja.get_template("list.html.jinja")
render = await template.render_async(
- calls=calls,
+ calls=calls or [],
+ count=count,
phone_number=phone_number,
version=CONFIG.version,
)
@@ -164,19 +174,18 @@ async def report_history_get(phone_number: PhoneNumber) -> HTMLResponse:
@api.get(
- "/report/{phone_number}/{call_id}",
+ "/report/{call_id}",
description="Display the call report in a web page.",
- name="Get call report in the browser",
+ name="Get a report (browser)",
)
-async def report_call_get(phone_number: PhoneNumber, call_id: UUID) -> HTMLResponse:
+async def report_single_get(call_id: UUID) -> HTMLResponse:
call = await _db.call_aget(call_id)
- if not call or call.phone_number != phone_number:
+ if not call:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Call {call_id} for phone number {phone_number} not found",
+ detail=f"Call {call_id} not found",
)
-
- template = _jinja.get_template("report.html.jinja")
+ template = _jinja.get_template("single.html.jinja")
render = await template.render_async(
bot_company=CONFIG.workflow.bot_company,
bot_name=CONFIG.workflow.bot_name,
@@ -193,7 +202,7 @@ async def report_call_get(phone_number: PhoneNumber, call_id: UUID) -> HTMLRespo
name="Search calls",
)
async def call_search_get(phone_number: PhoneNumber) -> list[CallGetModel]:
- calls = await _db.call_asearch_all(phone_number) or []
+ calls = await _db.call_asearch_all(phone_number=phone_number, count=1) or []
output = [CallGetModel.model_validate(call) for call in calls]
return output
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index d6aac39..d3fecae 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -133,19 +133,25 @@ class CosmosDbStore(IStore):
return call
async def call_asearch_all(
- self, phone_number: str
+ self,
+ count: int,
+ phone_number: Optional[str] = None,
) -> Optional[list[CallStateModel]]:
- _logger.debug(f"Loading all calls for {phone_number}")
- calls = []
+ _logger.debug(f"Searching calls, for {phone_number} and count {count}")
+ calls: list[CallStateModel] = []
try:
async with self._use_db() as db:
items = db.query_items(
- query="SELECT * FROM c WHERE STRINGEQUALS(c.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true) ORDER BY c.created_at DESC",
+ query=f"SELECT * FROM c {"WHERE STRINGEQUALS(c.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""} ORDER BY c.created_at DESC OFFSET 0 LIMIT @count",
parameters=[
{
"name": "@phone_number",
"value": phone_number,
},
+ {
+ "name": "@count",
+ "value": count,
+ },
],
)
async for raw in items:
@@ -157,7 +163,7 @@ class CosmosDbStore(IStore):
_logger.debug(f"Parsing error: {e.errors()}")
except CosmosHttpResponseError as e:
_logger.error(f"Error accessing CosmosDB, {e}")
- return calls or None
+ return calls
@asynccontextmanager
async def _use_db(self) -> AsyncGenerator[ContainerProxy, None]:
diff --git a/persistence/istore.py b/persistence/istore.py
index 3ef5d43..ba74d75 100644
--- a/persistence/istore.py
+++ b/persistence/istore.py
@@ -25,6 +25,8 @@ class IStore(ABC):
@abstractmethod
async def call_asearch_all(
- self, phone_number: str
+ self,
+ count: int,
+ phone_number: Optional[str] = None,
) -> Optional[list[CallStateModel]]:
pass
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index d96c107..15d7ea5 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -93,16 +93,19 @@ class SqliteStore(IStore):
return call
async def call_asearch_all(
- self, phone_number: str
+ self,
+ count: int,
+ phone_number: Optional[str] = None,
) -> Optional[list[CallStateModel]]:
- _logger.debug(f"Loading all {self._config.table} for {phone_number}")
- calls = []
+ _logger.debug(f"Searching calls, for {phone_number} and count {count}")
+ calls: list[CallStateModel] = []
async with self._use_db() as db:
cursor = await db.execute(
- f"SELECT data FROM {self._config.table} WHERE JSON_EXTRACT(data, '$.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ? ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC",
+ f"SELECT data FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""} ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT ?",
(
phone_number, # data.phone_number
phone_number, # data.claim.policyholder_phone
+ count, # limit
),
)
rows = await cursor.fetchall()
@@ -113,7 +116,7 @@ class SqliteStore(IStore):
calls.append(CallStateModel.model_validate_json(row[0]))
except ValidationError as e:
_logger.debug(f"Parsing error: {e.errors()}")
- return calls or None
+ return calls
async def _init_db(self, db: SQLiteConnection):
"""
diff --git a/public_website/history.html.jinja b/public_website/history.html.jinja
deleted file mode 100644
index 071657a..0000000
--- a/public_website/history.html.jinja
+++ /dev/null
@@ -1,21 +0,0 @@
-{% extends "templates/base.html.jinja" %}
-
-{% block title %}
-Historique des appels pour {{ phone_number }}
-{% endblock %}
-
-{% block content %}
-<!-- History of calls -->
-<div class="col-span-full space-y-4">
- <div class="p-4 space-y-4 rounded-md lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60">
- <h2 class="text-lg">📞 Historique des appels pour {{ phone_number }}</h2>
- {% for call in calls %}
- <div>
- <a class="hover:underline" href="/report/{{ call.phone_number | quote_plus }}/{{ call.call_id | quote_plus }}"><span class="font-mono">#{{ call.claim.claim_id }}</span> ({{ call.created_at.astimezone(call.tz()).strftime('%d %b %Y, %H:%M') }})</a>
- </div>
- {% else %}
- <p class="text-neutral-600 dark:text-neutral-400">Aucun appel pour l'instant.</p>
- {% endfor %}
- </div>
-</div>
-{% endblock %}
diff --git a/public_website/list.html.jinja b/public_website/list.html.jinja
new file mode 100644
index 0000000..8396063
--- /dev/null
+++ b/public_website/list.html.jinja
@@ -0,0 +1,33 @@
+{% extends "templates/base.html.jinja" %}
+
+{% block title %}
+Historique des appels pour {{ phone_number }}
+{% endblock %}
+
+{% block content %}
+<!-- Search bar for phone number -->
+<div class="p-4 col-span-full lg:grid lg:grid-cols-6">
+ <div class="lg:col-start-2 lg:col-end-6">
+ <form action="/report" method="GET" class="flex space-x-4">
+ <input type="text" name="phone_number" placeholder="Restrict search to a phone number (E164, e.g. +33612345678)" value="{{ phone_number }}" class="p-4 grow rounded-full bg-neutral-200/60 dark:bg-neutral-700/60">
+ <button type="submit" class="p-4 rounded-full bg-gradient-to-r from-pink-300/30 dark:from-pink-700/30 to-violet-300/30 dark:to-violet-700/30">Search</button>
+ </form>
+ </div>
+</div>
+<!-- History of calls -->
+<div class="col-span-full rounded-md lg:ring-1 ring-neutral-200/60 dark:ring-neutral-700/60">
+ <a class="grid grid-cols-4 border-b border-neutral-200/60 dark:border-neutral-700/60 text-neutral-600 dark:text-neutral-400">
+ <div class="p-4">Téléphone</div>
+ <div class="p-4">Date</div>
+ <div class="col-span-2 p-4">Synthèse</div>
+ </a>
+ {% for call in calls %}
+ <a href="/report/{{ call.call_id }}" class="grid grid-cols-4 border-b border-neutral-200/60 dark:border-neutral-700/60 hover:underline">
+ <div class="p-4 truncate">{{ call.phone_number }}</div>
+ <div class="p-4 truncate">{{ call.created_at.astimezone(call.tz()).strftime('%d %b %Y, %H:%M') }}</div>
+ <div class="col-span-2 p-4 truncate">{{ call.synthesis.short | lower }}</div>
+ </a>
+ {% endfor %}
+</div>
+<div class="px-4 text-neutral-600 dark:text-neutral-400">Top {{ count }} calls are shown.</div>
+{% endblock %}
diff --git a/public_website/report.html.jinja b/public_website/single.html.jinja
similarity index 96%
rename from public_website/report.html.jinja
rename to public_website/single.html.jinja
index aa850ee..56e8c10 100644
--- a/public_website/report.html.jinja
+++ b/public_website/single.html.jinja
@@ -6,9 +6,9 @@ Déclaration de sinistre {{ call.claim.claim_id }}
{% block content %}
<!-- Top introduction -->
-<header class="col-span-full my-8 px-4">
+<header class="col-span-full mx-4 mb-4">
<div class="mb-4 text-neutral-600 dark:text-neutral-400">
- <a class="hover:underline" href="/report/{{ call.phone_number | quote_plus }}">
+ <a class="hover:underline" href="/report?phone_number={{ call.phone_number | quote_plus }}">
⬅ Go back to your call history
</a>
</div>
@@ -161,7 +161,7 @@ Déclaration de sinistre {{ call.claim.claim_id }}
},
{
'title': 'Contact',
- 'value': ((call.claim.policyholder_email | lower) or 'N/A') ~ ', ' ~ (call.claim.policyholder_phone or 'N/A')
+ 'value': (call.claim.policyholder_email or 'N/A') ~ ', ' ~ (call.claim.policyholder_phone or 'N/A')
},
{
'title': 'Téléphone utilisé',
diff --git a/public_website/templates/base.html.jinja b/public_website/templates/base.html.jinja
index 736322e..dbb38bd 100644
--- a/public_website/templates/base.html.jinja
+++ b/public_website/templates/base.html.jinja
@@ -8,7 +8,7 @@
<title>{% block title %}{% endblock %}</title>
{% endblock %}
</head>
- <body class="lg:container overflow-x-hidden mx-auto lg:p-8 text-black dark:text-white bg-white dark:bg-neutral-900 text-sm">
+ <body class="lg:container overflow-x-hidden mx-auto py-4 lg:px-4 text-black dark:text-white bg-white dark:bg-neutral-900 text-sm">
<!-- Main content -->
<div class="flex flex-col lg:grid lg:grid-cols-6 gap-4">
@@ -16,7 +16,7 @@
</div>
<!-- Footer -->
- <footer class="my-16 space-y-2 text-center text-neutral-600 dark:text-neutral-400">
+ <footer class="my-8 space-y-2 text-center text-neutral-600 dark:text-neutral-400">
{% block footer %}
<p>
Call Center AI<br>
diff --git a/tests/store.py b/tests/store.py
index c85c69c..17b6ee4 100644
--- a/tests/store.py
+++ b/tests/store.py
@@ -39,7 +39,12 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> No
# Check not exists
assume(not await db.call_aget(call.call_id))
assume(await db.call_asearch_one(call.phone_number) != call)
- assume(call not in (await db.call_asearch_all(call.phone_number) or []))
+ assume(
+ call
+ not in (
+ await db.call_asearch_all(phone_number=call.phone_number, count=1) or []
+ )
+ )
# Insert test call
await db.call_aset(call)
@@ -49,4 +54,7 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> No
# Check search one
assume(await db.call_asearch_one(call.phone_number) == call)
# Check search all
- assume(call in (await db.call_asearch_all(call.phone_number) or []))
+ assume(
+ call
+ in (await db.call_asearch_all(phone_number=call.phone_number, count=1) or [])
+ )