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

db: Async Cosmos DB

Clémence Lesné1aab71633da5
diff --git a/.gitignore b/.gitignore
index 7a014ec..8111a06 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,7 +2,7 @@
.version.cache
# Temporary database
-.local.sqlite*
+*.sqlite*
# Local app config file
config.yaml
diff --git a/README.md b/README.md
index 044608b..25d1390 100644
--- a/README.md
+++ b/README.md
@@ -209,6 +209,7 @@ api:
database:
# mode: cosmos_db
# cosmos_db:
+ # access_key: xxx
# container: calls
# database: claim-ai
# endpoint: https://xxx.documents.azure.com:443
diff --git a/bicep/app.bicep b/bicep/app.bicep
index f1c4272..e6edbf4 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -86,6 +86,10 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {
name: 'DATABASE_MODE'
value: 'cosmos_db'
}
+ {
+ name: 'DATABASE_COSMOS_DB_ACCESS_KEY'
+ value: cosmos.listKeys().primaryMasterKey
+ }
{
name: 'DATABASE_COSMOS_DB_ENDPOINT'
value: cosmos.properties.documentEndpoint
@@ -373,37 +377,6 @@ resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15
}
}
-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'
@@ -423,6 +396,16 @@ resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/container
}
]
}
+ {
+ path: '/claim/policyholder_phone/?'
+ indexes: [
+ {
+ dataType: 'String'
+ kind: 'Hash'
+ precision: -1
+ }
+ ]
+ }
]
excludedPaths: [
{
diff --git a/helpers/config_models/database.py b/helpers/config_models/database.py
index 182e6c0..b16fb46 100644
--- a/helpers/config_models/database.py
+++ b/helpers/config_models/database.py
@@ -1,5 +1,5 @@
from enum import Enum
-from pydantic import validator
+from pydantic import validator, SecretStr, Field
from pydantic_settings import BaseSettings
from typing import Optional
@@ -10,15 +10,25 @@ class Mode(str, Enum):
class CosmosDbModel(BaseSettings, env_prefix="database_cosmos_db_"):
+ access_key: SecretStr
container: str
database: str
endpoint: str
class SqliteModel(BaseSettings, env_prefix="database_sqlite_"):
- path: str = ".local.sqlite"
+ path: str = ".local"
+ schema_version: int = Field(default=3, frozen=True)
table: str = "calls"
+ def full_path(self) -> str:
+ """
+ Returns the full path to the sqlite database file.
+
+ Formatted as: `{path}-v{schema_version}.sqlite`.
+ """
+ return f"{self.path}-v{self.schema_version}.sqlite"
+
class DatabaseModel(BaseSettings, env_prefix="database_"):
cosmos_db: Optional[CosmosDbModel] = None
diff --git a/persistence/cosmos.py b/persistence/cosmos.py
index e597074..b7a445f 100644
--- a/persistence/cosmos.py
+++ b/persistence/cosmos.py
@@ -1,6 +1,5 @@
-from azure.cosmos import CosmosClient, ContainerProxy
+from azure.cosmos.aio import CosmosClient, ContainerProxy
from azure.cosmos.exceptions import CosmosHttpResponseError
-from azure.identity import DefaultAzureCredential
from contextlib import asynccontextmanager
from datetime import datetime, timedelta
from fastapi.encoders import jsonable_encoder
@@ -15,47 +14,40 @@ from uuid import UUID
_logger = build_logger(__name__)
-AZ_CREDENTIAL = DefaultAzureCredential()
class CosmosStore(IStore):
- _db: ContainerProxy
+ _config: CosmosDbModel
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)
+ self._config = config
async def call_aget(self, call_id: UUID) -> Optional[CallModel]:
_logger.debug(f"Loading call {call_id}")
try:
async with self._use_db() as db:
items = db.query_items(
- enable_cross_partition_query=True,
- query="SELECT * FROM c WHERE c.id = @id",
+ query="SELECT * FROM c WHERE STRINGEQUALS(c.id, @id)",
parameters=[{"name": "@id", "value": str(call_id)}],
)
- except CosmosHttpResponseError as e:
- _logger.error(f"Error accessing CosmosDB, {e.message}")
- return None
- try:
- raw = next(items)
- try:
- return CallModel(**raw)
- except ValidationError as e:
+ raw = await anext(items)
+ try:
+ return CallModel(**raw)
+ except ValidationError as e:
_logger.warn(f"Error parsing call, {e.message}")
- except StopIteration:
+ except StopAsyncIteration:
return None
+ except CosmosHttpResponseError as e:
+ _logger.error(f"Error accessing CosmosDB, {e.message}")
async def call_aset(self, call: CallModel) -> bool:
- data = jsonable_encoder(call, exclude_none=True)
+ data = jsonable_encoder(call.model_dump(), 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)
+ async with self._use_db() as db:
+ await db.upsert_item(body=data)
return True
except CosmosHttpResponseError as e:
_logger.error(f"Error accessing CosmosDB: {e.message}")
@@ -67,9 +59,12 @@ class CosmosStore(IStore):
async with self._use_db() as db:
items = db.query_items(
max_item_count=1,
- partition_key=phone_number,
- query="SELECT * FROM c WHERE c.created_at < @date_limit ORDER BY c.created_at DESC",
+ query="SELECT * FROM c WHERE (STRINGEQUALS(c.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)) AND c.created_at < @date_limit ORDER BY c.created_at DESC",
parameters=[
+ {
+ "name": "@phone_number",
+ "value": phone_number,
+ },
{
"name": "@date_limit",
"value": str(
@@ -78,20 +73,18 @@ class CosmosStore(IStore):
hours=CONFIG.workflow.conversation_timeout_hour
)
),
- }
+ },
],
)
- except CosmosHttpResponseError as e:
- _logger.error(f"Error accessing CosmosDB: {e.message}")
- return None
- try:
- raw = next(items)
- try:
- return CallModel(**raw)
- except ValidationError as e:
+ raw = await anext(items)
+ try:
+ return CallModel(**raw)
+ except ValidationError as e:
_logger.warn(f"Error parsing call, {e.message}")
- except StopIteration:
+ except StopAsyncIteration:
return None
+ except CosmosHttpResponseError as e:
+ _logger.error(f"Error accessing CosmosDB: {e.message}")
async def call_asearch_all(self, phone_number: str) -> Optional[List[CallModel]]:
_logger.debug(f"Loading all calls for {phone_number}")
@@ -99,21 +92,31 @@ class CosmosStore(IStore):
try:
async with self._use_db() as db:
items = db.query_items(
- partition_key=phone_number,
- query="SELECT * FROM c ORDER BY c.created_at DESC",
+ 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",
+ parameters=[
+ {
+ "name": "@phone_number",
+ "value": phone_number,
+ },
+ ],
)
+ async for raw in items:
+ if not raw:
+ continue
+ try:
+ calls.append(CallModel(**raw))
+ except ValidationError as e:
+ _logger.warn(f"Error parsing call, {e.message}")
except CosmosHttpResponseError as e:
_logger.error(f"Error accessing CosmosDB, {e.message}")
- 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.message}")
return calls or None
@asynccontextmanager
async def _use_db(self) -> AsyncGenerator[ContainerProxy, None]:
- yield self._db
+ async with CosmosClient(
+ connection_timeout=5,
+ credential=self._config.access_key.get_secret_value(),
+ url=self._config.endpoint,
+ ) as client:
+ database = client.get_database_client(self._config.database)
+ yield database.get_container_client(self._config.container)
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index 9db662d..e1ed968 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -14,6 +14,7 @@ import os
_logger = build_logger(__name__)
+SCHEMA_VERSION = "3"
class SqliteStore(IStore):
@@ -42,16 +43,14 @@ class SqliteStore(IStore):
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)
+ data = jsonable_encoder(call.model_dump(), 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 (?, ?, ?, ?)",
+ 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()
@@ -61,8 +60,11 @@ class SqliteStore(IStore):
_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,),
+ f"SELECT data FROM {self._config.table} WHERE (JSON_EXTRACT(data, '$.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?) AND DATETIME(JSON_EXTRACT(data, '$.created_at')) < DATETIME('now', '{CONFIG.workflow.conversation_timeout_hour} hours') ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT 1",
+ (
+ phone_number, # data.phone_number
+ phone_number, # data.claim.policyholder_phone
+ ),
)
row = await cursor.fetchone()
if row:
@@ -77,8 +79,11 @@ class SqliteStore(IStore):
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,),
+ 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",
+ (
+ phone_number, # data.phone_number
+ phone_number, # data.claim.policyholder_phone
+ ),
)
rows = await cursor.fetchall()
for row in rows:
@@ -101,22 +106,26 @@ class SqliteStore(IStore):
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)"
+ f"CREATE TABLE IF NOT EXISTS {self._config.table} (id VARCHAR(36) PRIMARY KEY, data TEXT)"
)
# Create indexes
await db.execute(
- f"CREATE INDEX IF NOT EXISTS {self._config.table}_phone_number ON {self._config.table} (phone_number)"
+ f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_phone_number ON {self._config.table} (JSON_EXTRACT(data, '$.phone_number'))"
)
await db.execute(
- f"CREATE INDEX IF NOT EXISTS {self._config.table}_created_at ON {self._config.table} (created_at)"
+ f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_created_at ON {self._config.table} (DATETIME(JSON_EXTRACT(data, '$.created_at')))"
)
+ await db.execute(
+ f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_claim_policyholder_phone ON {self._config.table} (JSON_EXTRACT(data, '$.claim.policyholder_phone'))"
+ )
+
# Write changes to disk
await db.commit()
@asynccontextmanager
async def _use_db(self) -> AsyncGenerator[SQLiteConnection, None]:
# Create folder
- db_path = self._config.path
+ db_path = self._config.full_path()
first_run = False
if not os.path.isfile(db_path):
db_folder = db_path[: db_path.rfind("/")]