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: LLM option are now separated between fast and slow

Clémence Lesné2b6821755944
diff --git a/README.md b/README.md
index a0eb866..9250324 100644
--- a/README.md
+++ b/README.md
@@ -319,7 +319,7 @@ cognitive_service:
endpoint: https://xxx.cognitiveservices.azure.com
llm:
- backup:
+ fast:
mode: azure_openai
azure_openai:
api_key: xxx
@@ -328,7 +328,7 @@ llm:
endpoint: https://xxx.openai.azure.com
model: gpt-35-turbo
streaming: true
- primary:
+ slow:
mode: azure_openai
azure_openai:
api_key: xxx
@@ -525,7 +525,7 @@ Then, add the following in the `config.yaml` file:
[...]
llm:
- backup:
+ fast:
mode: openai
openai:
api_key: xxx
@@ -533,7 +533,7 @@ llm:
endpoint: https://api.openai.com
model: gpt-35-turbo
streaming: true
- primary:
+ slow:
mode: openai
openai:
api_key: xxx
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 19e8206..a670c1b 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -1,13 +1,16 @@
-param adaModel string
-param adaVersion string
param cognitiveCommunicationLocation string
+param embeddingModel string
+param embeddingQuota int
+param embeddingVersion string
param functionappLocation string
-param gptBackupContext int
-param gptBackupModel string
-param gptBackupVersion string
-param gptContext int
-param gptModel string
-param gptVersion string
+param llmFastContext int
+param llmFastModel string
+param llmFastQuota int
+param llmFastVersion string
+param llmSlowContext int
+param llmSlowModel string
+param llmSlowQuota int
+param llmSlowVersion string
param location string
param moderationBlocklists array
param openaiLocation string
@@ -19,9 +22,9 @@ var appName = 'call-center-ai'
var prefix = deployment().name
var functionAppName = '${prefix}-${appName}'
var appUrl = 'https://${functionAppName}.azurewebsites.net'
-var gptBackupModelFullName = toLower('${gptBackupModel}-${gptBackupVersion}')
-var gptModelFullName = toLower('${gptModel}-${gptVersion}')
-var adaModelFullName = toLower('${adaModel}-${adaVersion}')
+var llmFastModelFullName = toLower('${llmFastModel}-${llmFastVersion}')
+var llmSlowModelFullName = toLower('${llmSlowModel}-${llmSlowVersion}')
+var embeddingModelFullName = toLower('${embeddingModel}-${embeddingVersion}')
var cosmosContainerName = 'calls-v3' // Third schema version
var localConfig = loadYamlContent('../config.yaml')
var phonenumberSanitized = replace(localConfig.communication_services.phone_number, '+', '')
@@ -61,23 +64,23 @@ var config = {
endpoint: cognitiveCommunication.properties.endpoint
}
llm: {
- backup: {
+ fast: {
mode: 'azure_openai'
azure_openai: {
- context: gptBackupContext
- deployment: gptBackup.name
+ context: llmFastContext
+ deployment: llmFast.name
endpoint: cognitiveOpenai.properties.endpoint
- model: gptBackupModel
+ model: llmFastModel
streaming: true
}
}
- primary: {
+ slow: {
mode: 'azure_openai'
azure_openai: {
- context: gptContext
- deployment: gpt.name
+ context: llmSlowContext
+ deployment: llmSlow.name
endpoint: cognitiveOpenai.properties.endpoint
- model: gptModel
+ model: llmSlowModel
streaming: true
}
}
@@ -526,12 +529,12 @@ resource cognitiveOpenai 'Microsoft.CognitiveServices/accounts@2023-10-01-previe
}
}
-resource gpt 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
+resource llmSlow 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
parent: cognitiveOpenai
- name: gptModelFullName
+ name: llmSlowModelFullName
tags: tags
sku: {
- capacity: 40 // Keep it small, will be scaled up if needed with "dynamicThrottlingEnabled"
+ capacity: llmSlowQuota
name: 'Standard' // Pay-as-you-go
}
properties: {
@@ -540,18 +543,18 @@ resource gpt 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-previe
versionUpgradeOption: 'NoAutoUpgrade'
model: {
format: 'OpenAI'
- name: gptModel
- version: gptVersion
+ name: llmSlowModel
+ version: llmSlowVersion
}
}
}
-resource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
+resource llmFast 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
parent: cognitiveOpenai
- name: gptBackupModelFullName
+ name: llmFastModelFullName
tags: tags
sku: {
- capacity: 40 // Keep it small, will be scaled up if needed with "dynamicThrottlingEnabled"
+ capacity: llmFastQuota
name: 'Standard' // Pay-as-you-go
}
properties: {
@@ -560,8 +563,8 @@ resource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-
versionUpgradeOption: 'NoAutoUpgrade'
model: {
format: 'OpenAI'
- name: gptBackupModel
- version: gptBackupVersion
+ name: llmFastModel
+ version: llmFastVersion
}
}
}
@@ -628,10 +631,10 @@ resource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-
resource ada 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
parent: cognitiveOpenai
- name: adaModelFullName
+ name: embeddingModelFullName
tags: tags
sku: {
- capacity: 40 // Keep it small, will be scaled up if needed with "dynamicThrottlingEnabled"
+ capacity: embeddingQuota
name: 'Standard' // Pay-as-you-go
}
properties: {
@@ -640,8 +643,8 @@ resource ada 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-previe
versionUpgradeOption: 'NoAutoUpgrade'
model: {
format: 'OpenAI'
- name: adaModel
- version: adaVersion
+ name: embeddingModel
+ version: embeddingVersion
}
}
}
diff --git a/bicep/main.bicep b/bicep/main.bicep
index bf52431..c548323 100644
--- a/bicep/main.bicep
+++ b/bicep/main.bicep
@@ -1,14 +1,17 @@
-param adaModel string = 'text-embedding-ada-002'
-param adaVersion string = '2'
param cognitiveCommunicationLocation string
+param embeddingModel string = 'text-embedding-ada-002'
+param embeddingQuota int = 40 // Keep it small, will be scaled up if regional quota remains
+param embeddingVersion string = '2'
param functionappLocation string
-param gptBackupContext int = 16385
-param gptBackupModel string = 'gpt-35-turbo'
-param gptBackupVersion string = '0125'
-param gptContext int = 128000
-param gptModel string = 'gpt-4o'
-param gptVersion string = '2024-05-13'
param instance string = deployment().name
+param llmFastContext int = 16385
+param llmFastModel string = 'gpt-35-turbo'
+param llmFastQuota int = 40 // Keep it small, will be scaled up if regional quota remains
+param llmFastVersion string = '0125'
+param llmSlowContext int = 128000
+param llmSlowModel string = 'gpt-4o'
+param llmSlowQuota int = 40 // Keep it small, will be scaled up if regional quota remains
+param llmSlowVersion string = '2024-05-13'
param location string = deployment().location
param openaiLocation string
param searchLocation string
@@ -40,16 +43,19 @@ module app 'app.bicep' = {
name: instance
scope: sub
params: {
- adaModel: adaModel
- adaVersion: adaVersion
cognitiveCommunicationLocation: cognitiveCommunicationLocation
+ embeddingModel: embeddingModel
+ embeddingQuota: embeddingQuota
+ embeddingVersion: embeddingVersion
functionappLocation: functionappLocation
- gptBackupContext: gptBackupContext
- gptBackupModel: gptBackupModel
- gptBackupVersion: gptBackupVersion
- gptContext: gptContext
- gptModel: gptModel
- gptVersion: gptVersion
+ llmFastContext: llmFastContext
+ llmFastModel: llmFastModel
+ llmFastQuota: llmFastQuota
+ llmFastVersion: llmFastVersion
+ llmSlowContext: llmSlowContext
+ llmSlowModel: llmSlowModel
+ llmSlowQuota: llmSlowQuota
+ llmSlowVersion: llmSlowVersion
location: location
moderationBlocklists: []
openaiLocation: openaiLocation
diff --git a/helpers/config_models/llm.py b/helpers/config_models/llm.py
index b703db8..c50aaca 100644
--- a/helpers/config_models/llm.py
+++ b/helpers/config_models/llm.py
@@ -1,7 +1,7 @@
from azure.identity import ManagedIdentityCredential, get_bearer_token_provider
from enum import Enum
from openai import AsyncAzureOpenAI, AsyncOpenAI
-from pydantic import field_validator, SecretStr, BaseModel, ValidationInfo
+from pydantic import field_validator, SecretStr, BaseModel, ValidationInfo, Field
from typing import Any, Optional, Tuple, Union
@@ -102,11 +102,15 @@ class SelectedPlatformModel(BaseModel):
class LlmModel(BaseModel):
- backup: SelectedPlatformModel
- primary: SelectedPlatformModel
+ fast: SelectedPlatformModel = Field(
+ serialization_alias="backup", # Backwards compatibility with v6
+ )
+ slow: SelectedPlatformModel = Field(
+ serialization_alias="primary", # Backwards compatibility with v6
+ )
def selected(
- self, is_backup: bool
+ self, is_fast: bool
) -> Union[AzureOpenaiPlatformModel, OpenaiPlatformModel]:
- platform = self.backup if is_backup else self.primary
+ platform = self.fast if is_fast else self.slow
return platform.selected()
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index b0daa6a..17695d2 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -59,7 +59,7 @@ environ["TRACELOOP_TRACE_CONTENT"] = str(
OpenAIInstrumentor(enrich_token_usage=True).instrument()
logger.info(
- f"Using LLM models {CONFIG.llm.selected(False).model} (primary) and {CONFIG.llm.selected(True).model} (backup)"
+ f"Using LLM models {CONFIG.llm.selected(False).model} (slow) and {CONFIG.llm.selected(True).model} (fast)"
)
logger.info(f"Using Content Safety {CONFIG.content_safety.endpoint}")
@@ -98,47 +98,52 @@ async def completion_stream(
"""
Returns a stream of completions.
- Catch errors for a maximum of 3 times (internal + `RateLimitError`). If the error persists, try with the backup LLM. If it fails again, raise the error.
+ Completion is first made with the fast LLM, then the slow LLM if the previous fails. Catch errors for a maximum of 3 times (internal + `RateLimitError`). If it fails again, raise the error.
"""
- # Try a first time with primary LLM
+ # Try a three time with fast LLM
try:
- async for chunck in _completion_stream_worker(
- is_backup=False,
- max_tokens=max_tokens,
- messages=messages,
- system=system,
- tools=tools,
- ):
- yield chunck
- return
+ retryed = AsyncRetrying(
+ reraise=True,
+ retry=retry_any(
+ *[
+ retry_if_exception_type(exception)
+ for exception in _retried_exceptions
+ ]
+ ),
+ stop=stop_after_attempt(
+ 3
+ ), # Usage is short-lived, so stop after 3 attempts
+ wait=wait_random_exponential(multiplier=0.5, max=30),
+ )
+ async for attempt in retryed:
+ with attempt:
+ async for chunck in _completion_stream_worker(
+ is_fast=True,
+ max_tokens=max_tokens,
+ messages=messages,
+ system=system,
+ tools=tools,
+ ):
+ yield chunck
+ return
except Exception as e:
if not any(isinstance(e, exception) for exception in _retried_exceptions):
raise e
- logger.warning(f"{e.__class__.__name__} error, trying with backup LLM")
+ logger.warning(f"{e.__class__.__name__} error, trying with slow LLM")
- # Try more times with backup LLM, if it fails again, raise the error
- retryed = AsyncRetrying(
- reraise=True,
- retry=retry_any(
- *[retry_if_exception_type(exception) for exception in _retried_exceptions]
- ),
- stop=stop_after_attempt(3), # Usage is short-lived, so stop after 3 attempts
- wait=wait_random_exponential(multiplier=0.5, max=30),
- )
- async for attempt in retryed:
- with attempt:
- async for chunck in _completion_stream_worker(
- is_backup=True,
- max_tokens=max_tokens,
- messages=messages,
- system=system,
- tools=tools,
- ):
- yield chunck
+ # Try a last time with slow LLM, if it fails again, raise the error
+ async for chunck in _completion_stream_worker(
+ is_fast=False,
+ max_tokens=max_tokens,
+ messages=messages,
+ system=system,
+ tools=tools,
+ ):
+ yield chunck
async def _completion_stream_worker(
- is_backup: bool,
+ is_fast: bool,
max_tokens: int,
messages: list[MessageModel],
system: list[ChatCompletionSystemMessageParam],
@@ -148,7 +153,7 @@ async def _completion_stream_worker(
Returns a stream of completions.
"""
# Try cache
- cache_key = f"{__name__}-completion_stream-{_llm_key(is_backup)}-{system}-{tools}-{messages}-{max_tokens}"
+ cache_key = f"{__name__}-completion_stream-{_llm_key(is_fast)}-{system}-{tools}-{messages}-{max_tokens}"
cached = await _cache.aget(cache_key)
if cached:
try:
@@ -160,7 +165,7 @@ async def _completion_stream_worker(
# Try live
to_cache: list[ChoiceDelta] = []
- client, platform = _use_llm(is_backup)
+ client, platform = _use_llm(is_fast)
extra = {}
if tools:
extra["tools"] = tools # Add tools if any
@@ -245,12 +250,12 @@ async def completion_sync(
"""
Returns a completion.
- Catch errors for a maximum of 10 times (internal + `RateLimitError`). If the error persists, try with the backup LLM. If it fails again, raise the error.
+ Catch errors for a maximum of 10 times (internal + `RateLimitError`). If the error persists, try with the fast LLM. If it fails again, raise the error.
"""
- # Try a first time with primary LLM
+ # Try a first time with slow LLM
try:
return await _completion_sync_worker(
- is_backup=False,
+ is_fast=False,
max_tokens=max_tokens,
system=system,
json_output=json_output,
@@ -258,9 +263,9 @@ async def completion_sync(
except Exception as e:
if not any(isinstance(e, exception) for exception in _retried_exceptions):
raise e
- logger.warning(f"{e.__class__.__name__} error, trying with backup LLM")
+ logger.warning(f"{e.__class__.__name__} error, trying with fast LLM")
- # Try more times with backup LLM, if it fails again, raise the error
+ # Try more times with fast LLM, if it fails again, raise the error
retryed = AsyncRetrying(
reraise=True,
retry=retry_any(
@@ -274,7 +279,7 @@ async def completion_sync(
async for attempt in retryed:
with attempt:
return await _completion_sync_worker(
- is_backup=True,
+ is_fast=True,
max_tokens=max_tokens,
system=system,
json_output=json_output,
@@ -282,7 +287,7 @@ async def completion_sync(
async def _completion_sync_worker(
- is_backup: bool,
+ is_fast: bool,
max_tokens: int,
system: list[ChatCompletionSystemMessageParam],
json_output: bool = False,
@@ -298,7 +303,7 @@ async def _completion_sync_worker(
# Try live
content = None
- client, platform = _use_llm(is_backup)
+ client, platform = _use_llm(is_fast)
extra = {}
if json_output:
extra["response_format"] = {"type": "json_object"}
@@ -553,20 +558,20 @@ def _count_tokens(content: str, model: str) -> int:
return len(tiktoken.get_encoding(encoding_name).encode(content))
-def _llm_key(is_backup: bool) -> str:
- platform = CONFIG.llm.selected(is_backup)
+def _llm_key(is_fast: bool) -> str:
+ platform = CONFIG.llm.selected(is_fast)
return f"{platform.model}-{platform.context}"
def _use_llm(
- is_backup: bool,
+ is_fast: bool,
) -> Tuple[Union[AsyncAzureOpenAI, AsyncOpenAI], LlmAbstractPlatformModel]:
"""
Returns an LLM client and platform model.
The client is either an Azure OpenAI or an OpenAI client, depending on the configuration.
"""
- return CONFIG.llm.selected(is_backup).instance()
+ return CONFIG.llm.selected(is_fast).instance()
async def _use_contentsafety() -> ContentSafetyClient:
diff --git a/tests/conftest.py b/tests/conftest.py
index b6cca29..ead5b41 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -99,7 +99,7 @@ class DeepEvalAzureOpenAI(GPTModel):
cache: pytest.Cache,
**kwargs,
):
- platform = CONFIG.llm.backup.azure_openai
+ platform = CONFIG.llm.fast.azure_openai
assert platform
_langchain_kwargs = {