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: Allow non Azure OpenAI LLM platform

Clémence Lesné24beb49b1b9b
diff --git a/README.md b/README.md
index 856105f..0d702cc 100644
--- a/README.md
+++ b/README.md
@@ -269,15 +269,25 @@ cognitive_service:
# Must be of type "AI services multi-service account"
endpoint: https://xxx.cognitiveservices.azure.com
-openai:
- api_key: xxx
- endpoint: https://xxx.openai.azure.com
- gpt_backup_context: 16385
- gpt_backup_deployment: gpt-35-turbo-1106
- gpt_backup_model: gpt-35-turbo-1106
- gpt_context: 128000
- gpt_deployment: gpt-4-1106-preview
- gpt_model: gpt-4-1106-preview
+llm:
+ backup:
+ mode: azure_openai
+ azure_openai:
+ api_key: xxx
+ context: 16385
+ deployment: gpt-35-turbo-0125
+ endpoint: https://xxx.openai.azure.com
+ model: gpt-35-turbo
+ streaming: true
+ primary:
+ mode: azure_openai
+ azure_openai:
+ api_key: xxx
+ context: 128000
+ deployment: gpt-4-0125-preview
+ endpoint: https://xxx.openai.azure.com
+ model: gpt-4
+ streaming: true
ai_search:
access_key: xxx
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 6a9d6a7..45318cf 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -57,14 +57,27 @@ var config = {
cognitive_service: {
endpoint: cognitiveCommunication.properties.endpoint
}
- 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
+ llm: {
+ backup: {
+ mode: 'azure_openai'
+ azure_openai: {
+ context: gptBackupContext
+ deployment: gptBackup.name
+ endpoint: cognitiveOpenai.properties.endpoint
+ model: gptBackupModel
+ streaming: true
+ }
+ }
+ primary: {
+ mode: 'azure_openai'
+ azure_openai: {
+ context: gptContext
+ deployment: gpt.name
+ endpoint: cognitiveOpenai.properties.endpoint
+ model: gptModel
+ streaming: true
+ }
+ }
}
ai_search: {
access_key: search.listAdminKeys().primaryKey
diff --git a/helpers/config_models/llm.py b/helpers/config_models/llm.py
new file mode 100644
index 0000000..9791685
--- /dev/null
+++ b/helpers/config_models/llm.py
@@ -0,0 +1,120 @@
+from azure.identity import DefaultAzureCredential, get_bearer_token_provider
+from contextlib import asynccontextmanager
+from enum import Enum
+from openai import AsyncAzureOpenAI, AsyncOpenAI
+from pydantic import field_validator, SecretStr, BaseModel, ValidationInfo
+from typing import Any, AsyncGenerator, Optional, Tuple, Union
+
+
+class ModeEnum(str, Enum):
+ AZURE_OPENAI = "azure_openai"
+ OPENAI = "openai"
+
+
+class AbstractPlatformModel(BaseModel, frozen=True):
+ _client_kwargs: dict[str, Any] = {
+ # Reliability
+ "max_retries": 3,
+ "timeout": 60,
+ }
+ context: int
+ model: str
+ streaming: bool
+
+
+class AzureOpenaiPlatformModel(AbstractPlatformModel, frozen=True):
+ api_key: Optional[SecretStr] = None
+ deployment: str
+ endpoint: str
+
+ @asynccontextmanager
+ async def instance(
+ self,
+ ) -> AsyncGenerator[Tuple[AsyncAzureOpenAI, AbstractPlatformModel], None]:
+ api_key = self.api_key.get_secret_value() if self.api_key else None
+ token_func = (
+ get_bearer_token_provider(
+ DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
+ )
+ if not self.api_key
+ else None
+ )
+ client = AsyncAzureOpenAI(
+ **self._client_kwargs,
+ # Azure deployment
+ api_version="2023-12-01-preview",
+ azure_deployment=self.deployment,
+ azure_endpoint=self.endpoint,
+ # Authentication, either RBAC or API key
+ api_key=api_key,
+ azure_ad_token_provider=token_func,
+ )
+ try:
+ yield client, self
+ finally:
+ await client.close()
+
+
+class OpenaiPlatformModel(AbstractPlatformModel, frozen=True):
+ api_key: SecretStr
+ endpoint: str
+
+ @asynccontextmanager
+ async def instance(
+ self,
+ ) -> AsyncGenerator[Tuple[AsyncOpenAI, AbstractPlatformModel], None]:
+ client = AsyncOpenAI(
+ **self._client_kwargs,
+ # OpenAI deployment
+ base_url=self.endpoint,
+ # Authentication, either API key or no auth
+ api_key=self.api_key.get_secret_value(),
+ )
+ try:
+ yield client, self
+ finally:
+ await client.close()
+
+
+class SelectedPlatformModel(BaseModel, frozen=True):
+ azure_openai: Optional[AzureOpenaiPlatformModel] = None
+ mode: ModeEnum
+ openai: Optional[OpenaiPlatformModel] = None
+
+ @field_validator("azure_openai")
+ def validate_azure_openai(
+ cls,
+ azure_openai: Optional[AzureOpenaiPlatformModel],
+ info: ValidationInfo,
+ ) -> Optional[AzureOpenaiPlatformModel]:
+ if not azure_openai and info.data.get("mode", None) == ModeEnum.AZURE_OPENAI:
+ raise ValueError("Azure OpenAI config required")
+ return azure_openai
+
+ @field_validator("openai")
+ def validate_openai(
+ cls,
+ openai: Optional[OpenaiPlatformModel],
+ info: ValidationInfo,
+ ) -> Optional[OpenaiPlatformModel]:
+ if not openai and info.data.get("mode", None) == ModeEnum.OPENAI:
+ raise ValueError("OpenAI config required")
+ return openai
+
+ def selected(self) -> Union[AzureOpenaiPlatformModel, OpenaiPlatformModel]:
+ platform = (
+ self.azure_openai if self.mode == ModeEnum.AZURE_OPENAI else self.openai
+ )
+ assert platform
+ return platform
+
+
+class LlmModel(BaseModel):
+ backup: SelectedPlatformModel
+ primary: SelectedPlatformModel
+
+ def selected(
+ self, is_backup: bool
+ ) -> Union[AzureOpenaiPlatformModel, OpenaiPlatformModel]:
+ platform = self.backup if is_backup else self.primary
+ return platform.selected()
diff --git a/helpers/config_models/openai.py b/helpers/config_models/openai.py
deleted file mode 100644
index 361b9cc..0000000
--- a/helpers/config_models/openai.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from pydantic import SecretStr, BaseModel
-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/config_models/root.py b/helpers/config_models/root.py
index 33ec121..a77438a 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -7,7 +7,7 @@ from helpers.config_models.communication_service import CommunicationServiceMode
from helpers.config_models.content_safety import ContentSafetyModel
from helpers.config_models.database import DatabaseModel
from helpers.config_models.monitoring import MonitoringModel
-from helpers.config_models.openai import OpenAiModel
+from helpers.config_models.llm import LlmModel
from helpers.config_models.prompts import PromptsModel
from helpers.config_models.resources import ResourcesModel
from helpers.config_models.workflow import WorkflowModel
@@ -34,8 +34,8 @@ class RootModel(BaseSettings):
communication_service: CommunicationServiceModel
content_safety: ContentSafetyModel
database: DatabaseModel = DatabaseModel() # Object is fully defined by default
+ llm: LlmModel
monitoring: MonitoringModel
- openai: OpenAiModel
prompts: PromptsModel = PromptsModel() # Object is fully defined by default
resources: ResourcesModel
workflow: WorkflowModel
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 28df019..d6bf00e 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -7,12 +7,12 @@ from azure.ai.contentsafety.models import (
)
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
-from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from helpers.config import CONFIG
from contextlib import asynccontextmanager
from helpers.logging import build_logger, TRACER
-from openai import AsyncAzureOpenAI, AsyncStream, RateLimitError, APIError
+from openai import AsyncAzureOpenAI, AsyncStream, RateLimitError, APIError, AsyncOpenAI
from openai.types.chat import (
+ ChatCompletion,
ChatCompletionAssistantMessageParam,
ChatCompletionChunk,
ChatCompletionSystemMessageParam,
@@ -20,7 +20,11 @@ from openai.types.chat import (
ChatCompletionToolParam,
ChatCompletionUserMessageParam,
)
-from openai.types.chat.chat_completion_chunk import ChoiceDelta
+from openai.types.chat.chat_completion_chunk import (
+ ChoiceDelta,
+ ChoiceDeltaToolCall,
+ ChoiceDeltaToolCallFunction,
+)
from pydantic import BaseModel, ValidationError, TypeAdapter
from tenacity import (
retry,
@@ -34,6 +38,8 @@ import tiktoken
import json
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from os import environ
+from helpers.config_models.llm import AbstractPlatformModel as LlmAbstractPlatformModel
+from functools import lru_cache
# Instrument OpenAI
@@ -43,7 +49,7 @@ environ["TRACELOOP_TRACE_CONTENT"] = str(
OpenAIInstrumentor(enrich_token_usage=True).instrument()
_logger = build_logger(__name__)
-_logger.info(f"Using OpenAI GPT model {CONFIG.openai.gpt_model}")
+# _logger.info(f"Using OpenAI GPT model {CONFIG.llm.gpt_model}") # TODO: Re-enable
_logger.info(f"Using Content Safety {CONFIG.content_safety.endpoint}")
_cache = CONFIG.cache.instance()
@@ -81,7 +87,7 @@ async def completion_stream(
Catch errors for a maximum of 3 times (internal + `RateLimitError`), then raise the error.
"""
# Try cache
- cache_key = f"{__name__}-completion_stream-{is_backup}-{system}-{tools}-{messages}-{max_tokens}"
+ cache_key = f"{__name__}-completion_stream-{_llm_key(is_backup)}-{system}-{tools}-{messages}-{max_tokens}"
cached = await _cache.aget(cache_key)
if cached:
for chunck in TypeAdapter(list[ChoiceDelta]).validate_json(cached):
@@ -90,36 +96,65 @@ async def completion_stream(
# Try live
to_cache: list[ChoiceDelta] = []
- async with _use_oai(is_backup) as (client, model, context):
+ async with _use_llm(is_backup) as (client, platform):
extra = {}
if tools:
- extra["tools"] = tools
+ extra["tools"] = tools # Add tools if any
- prompt = _prepare_messages(
- context=context,
+ prompt = _limit_messages(
+ context=platform.context,
max_messages=20, # Quick response
messages=messages,
- model=model,
+ model=platform.model,
system=system,
tools=tools,
- )
-
- stream: AsyncStream[ChatCompletionChunk] = await client.chat.completions.create(
- max_tokens=max_tokens,
- messages=prompt,
- model=model,
- seed=42, # Reproducible results
- stream=True,
- temperature=0, # Most focused and deterministic
+ ) # Limit to 20 messages for quick response and avoid hallucinations
+ chat_kwargs = {
+ "max_tokens": max_tokens,
+ "messages": prompt,
+ "model": platform.model,
+ "seed": 42, # Reproducible results
+ "temperature": 0, # Most focused and deterministic
**extra,
- )
- async for chunck in stream:
- choices = chunck.choices
- if choices: # Skip empty chunks, happens with GPT-4 Turbo
+ } # Shared kwargs for both streaming and non-streaming
+
+ if platform.streaming: # Streaming
+ stream: AsyncStream[ChatCompletionChunk] = (
+ await client.chat.completions.create(
+ **chat_kwargs,
+ stream=True,
+ )
+ )
+ async for chunck in stream:
+ choices = chunck.choices
delta = choices[0].delta
yield delta
to_cache.append(delta)
+ else: # Non-streaming, emulate streaming with a single completion
+ completion: ChatCompletion = await client.chat.completions.create(
+ **chat_kwargs
+ )
+ message = completion.choices[0].message
+ delta = ChoiceDelta(
+ content=message.content,
+ role=message.role,
+ tool_calls=[
+ ChoiceDeltaToolCall(
+ id=tool.id,
+ index=0,
+ type=tool.type,
+ function=ChoiceDeltaToolCallFunction(
+ arguments=tool.function.arguments,
+ name=tool.function.name,
+ ),
+ )
+ for tool in message.tool_calls or []
+ ],
+ )
+ yield delta
+ to_cache.append(delta)
+
# Update cache
await _cache.aset(cache_key, TypeAdapter(list[ChoiceDelta]).dump_json(to_cache))
@@ -154,22 +189,22 @@ async def completion_sync(
# Try live
content = None
- async with _use_oai(False) as (client, model, context):
+ async with _use_llm(False) as (client, platform):
extra = {}
if json_output:
extra["response_format"] = {"type": "json_object"}
- prompt = _prepare_messages(
- context=context,
+ prompt = _limit_messages(
+ context=platform.context,
messages=messages,
- model=model,
+ model=platform.model,
system=system,
)
res = await client.chat.completions.create(
max_tokens=max_tokens,
messages=prompt,
- model=model,
+ model=platform.model,
seed=42, # Reproducible results
temperature=0, # Most focused and deterministic
**extra,
@@ -216,7 +251,7 @@ async def completion_model_sync(
return model.model_validate_json(res)
-def _prepare_messages(
+def _limit_messages(
context: int,
messages: list[MessageModel],
model: str,
@@ -231,6 +266,11 @@ def _prepare_messages(
ChatCompletionUserMessageParam,
]
]:
+ """
+ Returns a list of messages limited by the context size.
+
+ The context size is the maximum number of tokens allowed by the model. The messages are selected from the newest to the oldest, until the context or the maximum number of messages is reached.
+ """
counter = 0
selected_messages = []
tokens = 0
@@ -238,17 +278,17 @@ def _prepare_messages(
# Add system messages
for message in system:
- tokens += count_tokens(json.dumps(message), model)
+ tokens += _count_tokens(json.dumps(message), model)
counter += 1
# Add tools
for tool in tools or []:
- tokens += count_tokens(json.dumps(tool), model)
+ tokens += _count_tokens(json.dumps(tool), model)
# Add user messages until the context is reached, from the newest to the oldest
for message in messages[::-1]:
openai_message = message.to_openai()
- new_tokens = count_tokens(
+ new_tokens = _count_tokens(
"".join([json.dumps(x) for x in openai_message]), model
)
if tokens + new_tokens >= context:
@@ -328,6 +368,11 @@ async def safety_check(text: str) -> None:
wait=wait_random_exponential(multiplier=0.5, max=30),
)
async def _contentsafety_analysis(text: str) -> AnalyzeTextResult:
+ """
+ Returns the result of the content safety analysis.
+
+ Catch errors for a maximum of 3 times (internal + `HttpResponseError`), then raise the error.
+ """
async with _use_contentsafety() as client:
return await client.analyze_text(
AnalyzeTextOptions(
@@ -358,54 +403,46 @@ 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))
+@lru_cache # Cache results in memory as token count is done many times on the same content
+def _count_tokens(content: str, model: str) -> int:
+ """
+ Returns the number of tokens in the content, using the model's encoding.
+
+ If the model is unknown to TikToken, it uses the GPT-3.5 encoding.
+ """
+ try:
+ encoding_name = tiktoken.encoding_name_for_model(model)
+ except KeyError:
+ encoding_name = tiktoken.encoding_name_for_model("gpt-3.5")
+ _logger.warning(f"Unknown model {model}, using {encoding_name} encoding")
+ return len(tiktoken.get_encoding(encoding_name).encode(content))
+
+
+def _llm_key(is_backup: bool) -> str:
+ platform = CONFIG.llm.selected(is_backup)
+ return f"{platform.model}-{platform.context}"
@asynccontextmanager
-async def _use_oai(
+async def _use_llm(
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
- )
- key = CONFIG.openai.api_key.get_secret_value() if CONFIG.openai.api_key else None
- token_func = (
- get_bearer_token_provider(
- DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
- )
- if not CONFIG.openai.api_key
- else None
- )
-
- client = AsyncAzureOpenAI(
- # Reliability
- max_retries=3,
- timeout=60,
- # Azure deployment
- api_version="2023-12-01-preview",
- azure_deployment=deployment,
- azure_endpoint=CONFIG.openai.endpoint,
- # Authentication, either RBAC or API key
- api_key=key,
- azure_ad_token_provider=token_func,
- )
+) -> AsyncGenerator[
+ Tuple[Union[AsyncAzureOpenAI, AsyncOpenAI], LlmAbstractPlatformModel], None
+]:
+ """
+ Returns an LLM client and platform model.
- try:
- yield client, model, context
- finally:
- await client.close()
+ The client is either an Azure OpenAI or an OpenAI client, depending on the configuration.
+ """
+ async with CONFIG.llm.selected(is_backup).instance() as (client, platform):
+ yield client, platform
@asynccontextmanager
async def _use_contentsafety() -> AsyncGenerator[ContentSafetyClient, None]:
+ """
+ Returns a Content Safety client.
+ """
client = ContentSafetyClient(
# Azure deployment
endpoint=CONFIG.content_safety.endpoint,
diff --git a/tests/conftest.py b/tests/conftest.py
index 2ea580f..803b30b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -48,36 +48,40 @@ class DeepEvalAzureOpenAI(DeepEvalBaseLLM):
All calls are cached at best effort with Pytest implementation. Thread safe, can be used across processes.
"""
+ _langchain_kwargs: dict[str, Any]
_cache: pytest.Cache
_model: BaseChatModel
- _langchain_kwargs: dict[str, Any] = {
- # Repeatability
- "model_kwargs": {
- "seed": 42,
- },
- "temperature": 0,
- # Reliability
- "max_retries": 3,
- "timeout": 60,
- # Azure deployment
- "api_version": "2023-12-01-preview",
- "azure_deployment": CONFIG.openai.gpt_backup_deployment,
- "azure_endpoint": CONFIG.openai.endpoint,
- "model": CONFIG.openai.gpt_backup_model,
- # Authentication, either RBAC or API
- "api_key": CONFIG.openai.api_key.get_secret_value() if CONFIG.openai.api_key else None, # type: ignore
- "azure_ad_token_provider": (
- get_bearer_token_provider(
- DefaultAzureCredential(),
- "https://cognitiveservices.azure.com/.default",
- )
- if not CONFIG.openai.api_key
- else None
- ),
- }
def __init__(self, cache: pytest.Cache):
+ platform = CONFIG.llm.backup.azure_openai
+ assert platform
+
self._cache = cache
+ self._langchain_kwargs = {
+ # Repeatability
+ "model_kwargs": {
+ "seed": 42,
+ },
+ "temperature": 0,
+ # Reliability
+ "max_retries": 3,
+ "timeout": 60,
+ # Azure deployment
+ "api_version": "2023-12-01-preview",
+ "azure_deployment": platform.deployment,
+ "azure_endpoint": platform.endpoint,
+ "model": platform.model,
+ # Authentication, either RBAC or API
+ "api_key": platform.api_key.get_secret_value() if platform.api_key else None, # type: ignore
+ "azure_ad_token_provider": (
+ get_bearer_token_provider(
+ DefaultAzureCredential(),
+ "https://cognitiveservices.azure.com/.default",
+ )
+ if not platform.api_key
+ else None
+ ),
+ }
self._model = AzureChatOpenAI(**self._langchain_kwargs)
def load_model(self) -> BaseChatModel:
@@ -123,9 +127,9 @@ class DeepEvalAzureOpenAI(DeepEvalBaseLLM):
return "Azure OpenAI"
def _cache_key(self, prompt: str) -> str:
- langchain_hash = self._model._get_llm_string(**self._langchain_kwargs)
+ langchain_config = self._model._get_llm_string(**self._langchain_kwargs)
suffix = hashlib.sha256(
- f"{langchain_hash}-{prompt}".encode(),
+ f"{langchain_config}-{prompt}".encode(),
usedforsecurity=False,
).digest() # Arguments contain secrets, so hash them
return f"claim-ai/{suffix}"