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

perf: Using a cache in front of AI Search

Clémence Lesné8e38fa0d17bb
diff --git a/README.md b/README.md
index b9d243f..51402f9 100644
--- a/README.md
+++ b/README.md
@@ -59,6 +59,7 @@ Extract of the data stored during the call:
- [x] Follow a specific data schema for the claim
- [x] Has access to a documentation database (few-shot training / RAG)
- [x] Help the user to find the information needed to complete the claim
+- [x] Lower AI Search cost by usign a Redis cache
- [x] Responses are streamed from the LLM to the user, to avoid long pauses
- [x] Send a SMS report after the call
- [x] Take back a conversation after a disengagement
@@ -107,6 +108,7 @@ graph LR
db[("Conversations and claims\n(Cosmos DB or SQLite)")]
event_grid[("Broker\n(Event Grid)")]
gpt["GPT-4 Turbo\n(OpenAI)"]
+ redis["Cache\n(Redis)"]
translation["Translation\n(Cognitive Services)"]
end
@@ -114,6 +116,7 @@ graph LR
api -- Ask for translation --> translation
api -- Few-shot training --> ai_search
api -- Generate completion --> gpt
+ api -- Get cached data --> redis
api -- Save conversation --> db
api -- Send SMS report --> communication_service_sms
api -- Test for profanity --> constent_safety
@@ -256,6 +259,13 @@ database:
# endpoint: https://xxx.documents.azure.com:443
sqlite: {}
+cache:
+ # mode: redis
+ # redis:
+ # host: claim-ai.redis.cache.windows.net
+ # password: xxx
+ memory: {}
+
resources:
public_url: "https://xxx.blob.core.windows.net/public"
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 3d12bc2..1a1a04e 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -71,6 +71,14 @@ var config = {
access_key: translate.listKeys().key1
endpoint: 'https://${translate.name}.cognitiveservices.azure.com/'
}
+ cache: {
+ mode: 'redis'
+ redis: {
+ host: redis.properties.hostName
+ password: redis.listKeys().primaryKey
+ port: redis.properties.sslPort
+ }
+ }
}
output appUrl string = appUrl
@@ -490,3 +498,16 @@ resource translate 'Microsoft.CognitiveServices/accounts@2023-10-01-preview' = {
customSubDomainName: '${prefix}-translate'
}
}
+
+resource redis 'Microsoft.Cache/redis@2023-08-01' = {
+ name: prefix
+ location: location
+ tags: tags
+ properties: {
+ sku: {
+ capacity: 0
+ family: 'C'
+ name: 'Basic'
+ }
+ }
+}
diff --git a/helpers/config_models/cache.py b/helpers/config_models/cache.py
new file mode 100644
index 0000000..534df08
--- /dev/null
+++ b/helpers/config_models/cache.py
@@ -0,0 +1,39 @@
+from enum import Enum
+from pydantic import validator, SecretStr
+from pydantic_settings import BaseSettings
+from typing import Optional
+
+
+class ModeEnum(str, Enum):
+ MEMORY = "memory"
+ REDIS = "redis"
+
+
+class MemoryModel(BaseSettings):
+ max_size: int = 100
+
+
+class RedisModel(BaseSettings):
+ database: int = 0
+ host: str
+ password: SecretStr
+ port: int = 6379
+ ssl: bool = True
+
+
+class CacheModel(BaseSettings):
+ memory: Optional[MemoryModel] = None
+ mode: ModeEnum = ModeEnum.MEMORY
+ redis: Optional[RedisModel] = None
+
+ @validator("redis", always=True)
+ def check_sqlite(cls, v, values, **kwargs):
+ if not v and values.get("mode", None) == ModeEnum.REDIS:
+ raise ValueError("Redis config required")
+ return v
+
+ @validator("memory", always=True)
+ def check_memory(cls, v, values, **kwargs):
+ if not v and values.get("mode", None) == ModeEnum.MEMORY:
+ raise ValueError("Memory config required")
+ return v
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index 3176044..356a424 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -1,6 +1,7 @@
from helpers.config_models.ai_search import AiSearchModel
from helpers.config_models.ai_translation import AiTranslationModel
from helpers.config_models.api import ApiModel
+from helpers.config_models.cache import CacheModel
from helpers.config_models.cognitive_service import CognitiveServiceModel
from helpers.config_models.communication_service import CommunicationServiceModel
from helpers.config_models.content_safety import ContentSafetyModel
@@ -21,6 +22,7 @@ class RootModel(BaseSettings, env_prefix=""):
ai_search: AiSearchModel
ai_translation: AiTranslationModel
api: ApiModel
+ cache: CacheModel
cognitive_service: CognitiveServiceModel
communication_service: CommunicationServiceModel
content_safety: ContentSafetyModel
diff --git a/main.py b/main.py
index 69d6dbd..f690b94 100644
--- a/main.py
+++ b/main.py
@@ -39,6 +39,7 @@ from enum import Enum
from fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks, Response
from fastapi.responses import JSONResponse, HTMLResponse
from helpers.config_models.database import ModeEnum as DatabaseMode
+from helpers.config_models.cache import ModeEnum as CacheMode
from helpers.logging import build_logger
from jinja2 import Environment, FileSystemLoader, select_autoescape
from models.action import ActionModel, IndentEnum as IndentAction
@@ -59,6 +60,8 @@ from openai.types.chat import (
)
from persistence.ai_search import AiSearchSearch, TrainingModel as AiSearchTrainingModel
from persistence.cosmos import CosmosStore
+from persistence.memory import MemoryCache
+from persistence.redis import RedisCache
from persistence.sqlite import SqliteStore
from urllib.parse import quote_plus
import asyncio
@@ -111,12 +114,17 @@ sms_client = SmsClient(
)
# Persistence
+cache = (
+ MemoryCache(CONFIG.cache.memory)
+ if CONFIG.cache.mode == CacheMode.MEMORY
+ else RedisCache(CONFIG.cache.redis)
+)
db = (
SqliteStore(CONFIG.database.sqlite)
if CONFIG.database.mode == DatabaseMode.SQLITE
else CosmosStore(CONFIG.database.cosmos_db)
)
-search = AiSearchSearch(CONFIG.ai_search)
+search = AiSearchSearch(cache, CONFIG.ai_search)
# FastAPI
_logger.info(f'Using root path "{CONFIG.api.root_path}"')
diff --git a/persistence/ai_search.py b/persistence/ai_search.py
index 38e4bf8..8450023 100644
--- a/persistence/ai_search.py
+++ b/persistence/ai_search.py
@@ -8,7 +8,9 @@ from helpers.config_models.ai_search import AiSearchModel
from helpers.logging import build_logger
from models.call import CallModel
from models.training import TrainingModel
+from persistence.icache import ICache
from persistence.isearch import ISearch
+from pydantic import TypeAdapter
from pydantic import ValidationError
from typing import AsyncGenerator, List, Optional
@@ -19,12 +21,13 @@ _logger = build_logger(__name__)
class AiSearchSearch(ISearch):
_config: AiSearchModel
- def __init__(self, config: AiSearchModel):
+ def __init__(self, cache: ICache, config: AiSearchModel):
_logger.info(f"Using AI Search {config.endpoint} with index {config.index}")
_logger.info(
f"Note: At 300 characters per document, each LLM call will use approx {300 * config.top_k * config.expansion_k / 4} tokens."
)
self._config = config
+ super().__init__(cache)
async def training_asearch_all(
self, text: str, call: CallModel
@@ -32,7 +35,19 @@ class AiSearchSearch(ISearch):
_logger.debug(f'Searching training data for "{text}"')
if not text:
return None
- trainings = []
+
+ # Try cache
+ cache_key = f"{self.__class__.__name__}:training_asearch_all:{text}"
+ cached = await self._cache.aget(cache_key)
+ if cached:
+ try:
+ return TypeAdapter(List[TrainingModel]).validate_json(cached)
+ except ValidationError:
+ _logger.warn(f"Error parsing cached training: {cached}")
+ pass
+
+ # Try live
+ trainings: List[TrainingModel] = []
try:
async with self._use_db() as db:
results = await db.search(
@@ -83,6 +98,17 @@ class AiSearchSearch(ISearch):
_logger.error(f"Error requesting AI Search, {e}")
except ServiceRequestError as e:
_logger.error(f"Error connecting to AI Search, {e}")
+
+ # Update cache
+ await self._cache.aset(
+ cache_key,
+ (
+ TypeAdapter(List[TrainingModel]).dump_json(trainings)
+ if trainings
+ else None
+ ),
+ )
+
return trainings or None
@asynccontextmanager
diff --git a/persistence/icache.py b/persistence/icache.py
new file mode 100644
index 0000000..e55ad7f
--- /dev/null
+++ b/persistence/icache.py
@@ -0,0 +1,12 @@
+from abc import ABC, abstractmethod
+from typing import Optional, Union
+
+
+class ICache(ABC):
+ @abstractmethod
+ async def aget(self, key: str) -> Optional[bytes]:
+ pass
+
+ @abstractmethod
+ async def aset(self, key: str, value: Union[str, bytes, None]) -> None:
+ pass
diff --git a/persistence/isearch.py b/persistence/isearch.py
index 55f728c..9590b22 100644
--- a/persistence/isearch.py
+++ b/persistence/isearch.py
@@ -1,10 +1,16 @@
from abc import ABC, abstractmethod
from models.call import CallModel
from models.training import TrainingModel
+from persistence.icache import ICache
from typing import List, Optional
class ISearch(ABC):
+ _cache: ICache
+
+ def __init__(self, cache: ICache):
+ self._cache = cache
+
@abstractmethod
async def training_asearch_all(
self, text: str, call: CallModel
diff --git a/persistence/memory.py b/persistence/memory.py
new file mode 100644
index 0000000..ea54a18
--- /dev/null
+++ b/persistence/memory.py
@@ -0,0 +1,34 @@
+from helpers.config_models.cache import MemoryModel
+from helpers.logging import build_logger
+from persistence.icache import ICache
+from typing import Dict, Optional, Union
+
+
+_logger = build_logger(__name__)
+
+
+class MemoryCache(ICache):
+ _config: MemoryModel
+ _cache: Dict[str, Union[bytes, None]] = {}
+
+ def __init__(self, config: MemoryModel):
+ _logger.info(f"Using memory cache with {config.max_size} size limit")
+ self._config = config
+
+ async def aget(self, key: str) -> Optional[bytes]:
+ """
+ Get a value from the cache.
+
+ If the key does not exist, return `None`.
+ """
+ return self._cache.get(key, None)
+
+ async def aset(self, key: str, value: Union[str, bytes, None]) -> None:
+ """
+ Set a value in the cache.
+
+ If the value is `None`, set an empty string. If the cache is full, delete the cache and start over.
+ """
+ if len(self._cache) >= self._config.max_size:
+ self._cache = {}
+ self._cache[key] = value.encode() if isinstance(value, str) else value
diff --git a/persistence/redis.py b/persistence/redis.py
new file mode 100644
index 0000000..eef9ae3
--- /dev/null
+++ b/persistence/redis.py
@@ -0,0 +1,63 @@
+from contextlib import asynccontextmanager
+from helpers.config_models.cache import RedisModel
+from helpers.logging import build_logger
+from persistence.icache import ICache
+from redis.asyncio import Redis
+from redis.asyncio.retry import Retry
+from redis.backoff import ExponentialBackoff
+from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError
+from typing import AsyncGenerator, Optional, Union
+
+
+_logger = build_logger(__name__)
+_retry = Retry(ExponentialBackoff(), 3)
+
+
+class RedisCache(ICache):
+ _config: RedisModel
+
+ def __init__(self, config: RedisModel):
+ _logger.info(f"Using Redis cache {config.host}:{config.port}")
+ self._config = config
+
+ async def aget(self, key: str) -> Optional[bytes]:
+ """
+ Get a value from the cache.
+
+ If the key does not exist or if the key exists but the value is empty, return `None`.
+
+ Catch errors for a maximum of 3 times, then raise the error.
+ """
+ async with self._use_db() as db:
+ res = await db.get(key)
+ return res if res else None
+
+ async def aset(self, key: str, value: Union[str, bytes, None]) -> None:
+ """
+ Set a value in the cache.
+
+ If the value is `None`, set an empty string.
+
+ Catch errors for a maximum of 3 times, then raise the error.
+ """
+ async with self._use_db() as db:
+ await db.set(key, value if value else "")
+
+ @asynccontextmanager
+ async def _use_db(self) -> AsyncGenerator[Redis, None]:
+ client = Redis(
+ # Database location
+ db=self._config.database,
+ # Reliability
+ retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError],
+ retry=_retry,
+ socket_connect_timeout=5,
+ # Azure deployment
+ host=self._config.host,
+ port=self._config.port,
+ ssl=self._config.ssl,
+ # Authentication with password
+ password=self._config.password.get_secret_value(),
+ )
+ yield client
+ await client.aclose()
diff --git a/requirements.txt b/requirements.txt
index c7ce4b3..dc6fa68 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -18,5 +18,6 @@ pydantic-extra-types==2.5.0 # Required for pydantic
pydantic-settings==2.1.0
python-dotenv==1.0.1
pyyaml==6.0.1
+redis==5.0.1
tenacity==8.2.3
uvicorn==0.25.0