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

reliability: Backup model and max messages depending to the context

Clémence Lesné51569dcf54e3
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 1a1a04e..fdd0951 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -4,6 +4,10 @@ param agentPhoneNumber string
param botCompany string
param botName string
param botPhoneNumber string
+param gptBackupContext int
+param gptBackupModel string
+param gptBackupVersion string
+param gptContext int
param gptModel string
param gptVersion string
param imageVersion string
@@ -15,6 +19,7 @@ param tags object
var prefix = deployment().name
var appUrl = 'https://claim-ai.${acaEnv.properties.defaultDomain}'
+var gptBackupModelFullName = toLower('${gptBackupModel}-${gptBackupVersion}')
var gptModelFullName = toLower('${gptModel}-${gptVersion}')
var adaModelFullName = toLower('${adaModel}-${adaVersion}')
var config = {
@@ -49,6 +54,10 @@ var config = {
}
openai: {
endpoint: cognitiveOpenai.properties.endpoint
+ gpt_backup_context: gptBackupContext
+ gpt_backup_deployment: gptBackup.name
+ gpt_backup_model: gptBackupModel
+ gpt_context: gptContext
gpt_deployment: gpt.name
gpt_model: gptModel
}
@@ -314,6 +323,23 @@ resource gpt 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-previe
}
}
+resource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
+ parent: cognitiveOpenai
+ name: gptBackupModelFullName
+ sku: {
+ capacity: 50
+ name: 'Standard' // Pay-as-you-go
+ }
+ properties: {
+ // raiPolicyName: contentfilter.name
+ model: {
+ format: 'OpenAI'
+ name: gptBackupModel
+ version: gptBackupVersion
+ }
+ }
+}
+
// resource contentfilter 'Microsoft.CognitiveServices/accounts/raiPolicies@2023-06-01-preview' = {
// parent: cognitiveOpenai
// name: 'gpt'
diff --git a/bicep/main.bicep b/bicep/main.bicep
index d191438..b5d9dc3 100644
--- a/bicep/main.bicep
+++ b/bicep/main.bicep
@@ -4,6 +4,10 @@ param agentPhoneNumber string
param botCompany string
param botName string
param botPhoneNumber string
+param gptBackupContext int = 16385
+param gptBackupModel string = 'gpt-35-turbo'
+param gptBackupVersion string = '1106'
+param gptContext int = 128000
param gptModel string = 'gpt-4'
param gptVersion string = '1106-Preview'
param imageVersion string = 'main'
@@ -42,6 +46,10 @@ module app 'app.bicep' = {
botCompany: botCompany
botName: botName
botPhoneNumber: botPhoneNumber
+ gptBackupContext: gptBackupContext
+ gptBackupModel: gptBackupModel
+ gptBackupVersion: gptBackupVersion
+ gptContext: gptContext
gptModel: gptModel
gptVersion: gptVersion
imageVersion: imageVersion
diff --git a/helpers/config_models/openai.py b/helpers/config_models/openai.py
index 470f695..361b9cc 100644
--- a/helpers/config_models/openai.py
+++ b/helpers/config_models/openai.py
@@ -5,5 +5,9 @@ from typing import Optional
class OpenAiModel(BaseModel):
api_key: Optional[SecretStr] = None
endpoint: str
+ gpt_backup_context: int
+ gpt_backup_deployment: str
+ gpt_backup_model: str
+ gpt_context: int
gpt_deployment: str
gpt_model: str
diff --git a/helpers/llm_plugins.py b/helpers/llm_plugins.py
index 5ff3cab..7d69101 100644
--- a/helpers/llm_plugins.py
+++ b/helpers/llm_plugins.py
@@ -51,7 +51,7 @@ class LlmPlugins:
async def end_call(self) -> str:
"""
- Use this if the user wants to end the call, or if the user said goodbye in its last message. Be warnging that the call will be ended immediately. Never use this action directly after a recall. Example: 'I want to hang up', 'Good bye, see you soon', 'We are done here', 'We will talk again later'.
+ Use this if the user wants to end the call in its last message. Be warnging that the call will be ended immediately. Never use this action directly after a recall. Example: 'I want to hang up', 'Good bye, see you soon', 'We are done here', 'We will talk again later'.
"""
await self.cancellation_callback()
await handle_play(
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 3df73ce..3bed66c 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -11,15 +11,14 @@ from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from helpers.config import CONFIG
from contextlib import asynccontextmanager
from helpers.logging import build_logger
-from openai import (
- AsyncAzureOpenAI,
- AsyncStream,
- RateLimitError,
-)
+from openai import AsyncAzureOpenAI, AsyncStream, RateLimitError, APIError
from openai.types.chat import (
+ ChatCompletionAssistantMessageParam,
ChatCompletionChunk,
- ChatCompletionMessageParam,
+ ChatCompletionSystemMessageParam,
+ ChatCompletionToolMessageParam,
ChatCompletionToolParam,
+ ChatCompletionUserMessageParam,
)
from openai.types.chat.chat_completion_chunk import ChoiceDelta
from pydantic import BaseModel, ValidationError
@@ -29,8 +28,10 @@ from tenacity import (
wait_random_exponential,
retry_if_exception_type,
)
-from typing import AsyncGenerator, List, Optional, Type, TypeVar
+from typing import AsyncGenerator, List, Optional, Tuple, Type, TypeVar, Union
from httpx import ReadError
+from models.message import MessageModel
+import tiktoken
_logger = build_logger(__name__)
@@ -58,8 +59,10 @@ class SafetyCheckError(Exception):
wait=wait_random_exponential(multiplier=0.5, max=30),
)
async def completion_stream(
- messages: List[ChatCompletionMessageParam],
+ is_backup: bool,
max_tokens: int,
+ messages: List[MessageModel],
+ system: List[ChatCompletionSystemMessageParam],
tools: Optional[List[ChatCompletionToolParam]] = None,
) -> AsyncGenerator[ChoiceDelta, None]:
"""
@@ -72,11 +75,18 @@ async def completion_stream(
if tools:
extra["tools"] = tools
- async with _use_oai() as client:
+ async with _use_oai(is_backup) as (client, model, context):
+ prompt = _prepare_messages(
+ context=context,
+ messages=messages,
+ model=model,
+ system=system,
+ )
+
stream: AsyncStream[ChatCompletionChunk] = await client.chat.completions.create(
max_tokens=max_tokens,
- messages=messages,
- model=CONFIG.openai.gpt_model,
+ messages=prompt,
+ model=model,
stream=True,
temperature=0, # Most focused and deterministic
**extra,
@@ -90,6 +100,7 @@ async def completion_stream(
reraise=True,
retry=(
retry_if_exception_type(SafetyCheckError)
+ | retry_if_exception_type(APIError)
| retry_if_exception_type(RateLimitError)
| retry_if_exception_type(ReadError)
),
@@ -97,8 +108,9 @@ async def completion_stream(
wait=wait_random_exponential(multiplier=0.5, max=30),
)
async def completion_sync(
- messages: List[ChatCompletionMessageParam],
max_tokens: int,
+ messages: List[MessageModel],
+ system: List[ChatCompletionSystemMessageParam],
json_output: bool = False,
) -> Optional[str]:
"""
@@ -112,11 +124,18 @@ async def completion_sync(
extra["response_format"] = {"type": "json_object"}
content = None
- async with _use_oai() as client:
+ async with _use_oai(False) as (client, model, context):
+ prompt = _prepare_messages(
+ context=context,
+ messages=messages,
+ model=model,
+ system=system,
+ )
+
res = await client.chat.completions.create(
max_tokens=max_tokens,
- messages=messages,
- model=CONFIG.openai.gpt_model,
+ messages=prompt,
+ model=model,
temperature=0, # Most focused and deterministic
**extra,
)
@@ -137,21 +156,73 @@ async def completion_sync(
wait=wait_random_exponential(multiplier=0.5, max=30),
)
async def completion_model_sync(
- messages: List[ChatCompletionMessageParam],
max_tokens: int,
+ messages: List[MessageModel],
model: Type[ModelType],
+ system: List[ChatCompletionSystemMessageParam],
) -> Optional[ModelType]:
"""
Returns an object validated against a given model, from a completion result.
Catch errors for a maximum of 3 times, but not `SafetyCheckError`.
"""
- res = await completion_sync(messages, max_tokens, json_output=True)
+ res = await completion_sync(
+ json_output=True,
+ max_tokens=max_tokens,
+ messages=messages,
+ system=system,
+ )
if not res:
return None
return model.model_validate_json(res)
+def _prepare_messages(
+ context: int,
+ model: str,
+ system: List[ChatCompletionSystemMessageParam],
+ messages: List[MessageModel],
+ max_messages: int = 50,
+) -> List[
+ Union[
+ ChatCompletionAssistantMessageParam,
+ ChatCompletionSystemMessageParam,
+ ChatCompletionToolMessageParam,
+ ChatCompletionUserMessageParam,
+ ]
+]:
+ res: List[
+ Union[
+ ChatCompletionAssistantMessageParam,
+ ChatCompletionSystemMessageParam,
+ ChatCompletionToolMessageParam,
+ ChatCompletionUserMessageParam,
+ ]
+ ] = [*system]
+ counter = 0
+ total = min(len(system) + len(messages), max_messages)
+
+ # Add system messages
+ tokens = 0
+ for message in system:
+ tokens += count_tokens(message.get("content"), model)
+ counter += 1
+
+ # Add user messages until the context is reached
+ for message in messages:
+ tokens += count_tokens(message.content, model)
+ if tokens >= context:
+ break
+ if counter >= max_messages:
+ break
+ res += message.to_openai()
+ counter += 1
+
+ _logger.info(f"Took {counter}/{total} messages for the context")
+
+ return res
+
+
async def safety_check(text: str) -> None:
"""
Raise `SafetyCheckError` if the text is safe, nothing otherwise.
@@ -243,15 +314,32 @@ def _contentsafety_category_test(
return True
+def count_tokens(content: str, model: str) -> int:
+ enc = tiktoken.encoding_for_model(model)
+ return len(enc.encode(content))
+
+
@asynccontextmanager
-async def _use_oai() -> AsyncGenerator[AsyncAzureOpenAI, None]:
+async def _use_oai(
+ is_backup: bool,
+) -> AsyncGenerator[Tuple[AsyncAzureOpenAI, str, int], None]:
+ deployment = (
+ CONFIG.openai.gpt_deployment
+ if not is_backup
+ else CONFIG.openai.gpt_backup_deployment
+ )
+ model = CONFIG.openai.gpt_model if not is_backup else CONFIG.openai.gpt_backup_model
+ context = (
+ CONFIG.openai.gpt_context if not is_backup else CONFIG.openai.gpt_backup_context
+ )
+
client = AsyncAzureOpenAI(
# Reliability
max_retries=3,
timeout=60,
# Azure deployment
api_version="2023-12-01-preview",
- azure_deployment=CONFIG.openai.gpt_deployment,
+ azure_deployment=deployment,
azure_endpoint=CONFIG.openai.endpoint,
# Authentication, either RBAC or API key
api_key=(
diff --git a/main.py b/main.py
index 2cf545c..09d2599 100644
--- a/main.py
+++ b/main.py
@@ -46,10 +46,7 @@ from models.next import ActionEnum as NextActionEnum
from models.next import NextModel
from models.synthesis import SynthesisModel
from openai import APIError
-from openai.types.chat import (
- ChatCompletionMessageParam,
- ChatCompletionSystemMessageParam,
-)
+from openai.types.chat import ChatCompletionSystemMessageParam
from persistence.ai_search import AiSearchSearch
from persistence.cosmos import CosmosStore
from persistence.memory import MemoryCache
@@ -67,11 +64,11 @@ from models.message import (
ToolModel as MessageToolModel,
)
from helpers.llm_worker import (
+ completion_model_sync,
completion_stream,
completion_sync,
- safety_check,
- completion_model_sync,
ModelType,
+ safety_check,
SafetyCheckError,
)
from uuid import UUID
@@ -633,7 +630,7 @@ async def load_llm_chat(
return call
-async def llm_completion(system: Optional[str], call: CallModel) -> Optional[str]:
+async def llm_completion(text: Optional[str], call: CallModel) -> Optional[str]:
"""
Run LLM completion from a system prompt and a Call model.
@@ -641,16 +638,17 @@ async def llm_completion(system: Optional[str], call: CallModel) -> Optional[str
"""
_logger.debug(f"Running LLM completion ({call.call_id})")
- if not system:
+ if not text:
return None
- messages = _oai_completion_messages(system, call)
+ system = _llm_completion_system(text, call)
content = None
try:
content = await completion_sync(
max_tokens=1000,
- messages=messages,
+ messages=call.messages,
+ system=system,
)
except APIError:
_logger.warn(f"OpenAI API call error", exc_info=True)
@@ -661,7 +659,7 @@ async def llm_completion(system: Optional[str], call: CallModel) -> Optional[str
async def llm_model(
- system: Optional[str], call: CallModel, model: Type[ModelType]
+ text: Optional[str], call: CallModel, model: Type[ModelType]
) -> Optional[ModelType]:
"""
Run LLM completion from a system prompt, a Call model, and an expected model type as a return.
@@ -670,17 +668,18 @@ async def llm_model(
"""
_logger.debug(f"Running LLM model ({call.call_id})")
- if not system:
+ if not text:
return None
- messages = _oai_completion_messages(system, call)
+ system = _llm_completion_system(text, call)
res = None
try:
res = await completion_model_sync(
max_tokens=1000,
- messages=messages,
+ messages=call.messages,
model=model,
+ system=system,
)
except APIError:
_logger.warn(f"OpenAI API call error", exc_info=True)
@@ -688,10 +687,10 @@ async def llm_model(
return res
-def _oai_completion_messages(
+def _llm_completion_system(
system: str, call: CallModel
-) -> List[ChatCompletionMessageParam]:
- messages: List[ChatCompletionMessageParam] = [
+) -> List[ChatCompletionSystemMessageParam]:
+ messages = [
ChatCompletionSystemMessageParam(
content=CONFIG.prompts.llm.default_system(
phone_number=call.phone_number,
@@ -714,7 +713,7 @@ async def execute_llm_chat(
user_callback: Callable[[str, MessageStyleEnum], Awaitable],
_retry_remaining: int = 3,
) -> Tuple[bool, CallModel]:
- _logger.debug(f"Running LLM chat ({call.call_id})")
+ _logger.debug(f"Running LLM chat, remaining {_retry_remaining} ({call.call_id})")
should_continue_chat = True
async def _retry() -> Tuple[bool, CallModel]:
@@ -791,11 +790,11 @@ async def execute_llm_chat(
trainings = sorted(
set(training for trainings in trainings_tasks for training in trainings or [])
) # Flatten, remove duplicates, and sort by score
- _logger.info(f"Enhancing LLM chat with {len(trainings)} trainings ({call.call_id})")
+ _logger.info(f"Enhancing LLM chat with {len(trainings)} trainings")
_logger.debug(f"Trainings: {trainings}")
- # Build messages
- messages: List[ChatCompletionMessageParam] = [
+ # Build system prompts
+ system = [
ChatCompletionSystemMessageParam(
content=CONFIG.prompts.llm.default_system(
phone_number=call.phone_number,
@@ -810,9 +809,6 @@ async def execute_llm_chat(
role="system",
),
]
- for message in call.messages:
- messages += message.to_openai()
- _logger.debug(f"Messages: {messages}")
# Build plugins
plugins = LlmPlugins(
@@ -829,14 +825,21 @@ async def execute_llm_chat(
tools = plugins.to_openai()
_logger.debug(f"Tools: {tools}")
+ # Enable backup model if two retries are left, to maximize the chance of success
+ model_is_backup = _retry_remaining < 2
+ if model_is_backup:
+ _logger.warn(f"Using backup model ({call.call_id})")
+
# Execute LLM inference
content_buffer_pointer = 0
content_full = ""
tool_calls_buffer: dict[int, MessageToolModel] = {}
try:
async for delta in completion_stream(
+ is_backup=model_is_backup,
max_tokens=350,
- messages=messages,
+ messages=call.messages,
+ system=system,
tools=tools,
):
if not delta.content:
@@ -858,7 +861,7 @@ async def execute_llm_chat(
return await _retry()
except APIError:
_logger.warn(f"OpenAI API call error", exc_info=True)
- return await _error_response()
+ return await _retry()
# Flush the remaining buffer
if content_buffer_pointer < len(content_full):
@@ -954,7 +957,7 @@ async def post_call_sms(call: CallModel) -> None:
Send an SMS report to the customer.
"""
content = await llm_completion(
- system=CONFIG.prompts.llm.sms_summary_system(call),
+ text=CONFIG.prompts.llm.sms_summary_system(call),
call=call,
)
@@ -1023,15 +1026,15 @@ async def post_call_synthesis(call: CallModel) -> None:
short, long = await asyncio.gather(
llm_completion(
call=call,
- system=CONFIG.prompts.llm.synthesis_short_system(call),
+ text=CONFIG.prompts.llm.synthesis_short_system(call),
),
llm_completion(
call=call,
- system=CONFIG.prompts.llm.citations_system(
+ text=CONFIG.prompts.llm.citations_system(
call=call,
text=await llm_completion(
call=call,
- system=CONFIG.prompts.llm.synthesis_long_system(call),
+ text=CONFIG.prompts.llm.synthesis_long_system(call),
),
),
),
@@ -1058,7 +1061,7 @@ async def post_call_next(call: CallModel) -> None:
next = await llm_model(
call=call,
model=NextModel,
- system=CONFIG.prompts.llm.next_system(call),
+ text=CONFIG.prompts.llm.next_system(call),
)
if not next:
diff --git a/models/message.py b/models/message.py
index 214553b..d95df2d 100644
--- a/models/message.py
+++ b/models/message.py
@@ -90,14 +90,33 @@ class ToolModel(BaseModel):
logger = build_logger(__name__)
name = self.function_name
+ # Parse args
try:
- args = json.loads(self.function_arguments)
+ args: dict[str, Union[str, list[str], dict[str, str]]] = json.loads(
+ self.function_arguments
+ )
except json.JSONDecodeError:
logger.warn(
f"Error decoding JSON args for function {name}: {self.function_arguments}"
)
return f"Bad JSON format, impossible to execute function {name}"
+ # Unescape content (double backslash, HTML entities, ...) for str and list
+ # TODO: Is there more to unescape?
+ for key, arg in args.items():
+ if isinstance(arg, str):
+ args[key] = arg.encode("raw_unicode_escape").decode("unicode_escape")
+ elif isinstance(arg, list):
+ for i, v in enumerate(arg):
+ args[key][i] = v.encode("raw_unicode_escape").decode(
+ "unicode_escape"
+ )
+ elif isinstance(arg, dict):
+ for k, v in arg.items():
+ args[key][k] = v.encode("raw_unicode_escape").decode(
+ "unicode_escape"
+ )
+
try:
res = await getattr(plugins, name)(**args)
logger.info(f"Executing function {name} ({args}): {res[:50]}...")
diff --git a/requirements.txt b/requirements.txt
index d37426b..bac52a0 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -20,4 +20,5 @@ python-dotenv==1.0.1
pyyaml==6.0.1
redis==5.0.1
tenacity==8.2.3
+tiktoken==0.6.0
uvicorn[standard]==0.27.1