Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
chore: Remove explicit Content Safety usage
Clémence Lesnéa9841c3d457e
diff --git a/README.md b/README.mdindex 9fe57b9..fd985e0 100644--- a/README.md+++ b/README.md@@ -144,7 +144,6 @@ graph LRada["Embedding\n(ADA)"]app["App\n(Functions App)"]communication_services["Call & SMS gateway\n(Communication Services)"]- constent_safety["Moderation\n(Content Safety)"]db[("Conversations and claims\n(Cosmos DB / SQLite)")]eventgrid["Broker\n(Event Grid)"]gpt["LLM\n(GPT-4o)"]@@ -165,7 +164,6 @@ graph LRapp -- Get cached data --> redisapp -- Save conversation --> dbapp -- Send SMS report --> communication_services- app -- Test for profanity --> constent_safetyapp -. Watch .-> queuescommunication_services -- Generate voice --> tts@@ -196,7 +194,6 @@ sequenceDiagramactor Human agentparticipant Event Gridparticipant Communication Services- participant Content Safetyparticipant Appparticipant Cosmos DBparticipant OpenAI GPT@@ -223,10 +220,6 @@ sequenceDiagramloop Over bufferloop Over multiple toolsalt Is this a claim data update?- App->>Content Safety: Ask for safety test- alt Is the text safe?- App->>Communication Services: Send dynamic SSML text- endApp->>Cosmos DB: Update claim dataelse Does the user want the human agent?App->>Communication Services: Send static SSML text@@ -237,14 +230,6 @@ sequenceDiagramApp->>Communication Services: End the callendend- alt Is there a text?- alt Is there enough text to make a sentence?- App->>Content Safety: Ask for safety test- alt Is the text safe?- App->>Communication Services: Send dynamic SSML text- end- end- endendApp->>Cosmos DB: Persist conversationend@@ -344,10 +329,6 @@ ai_search:endpoint: https://xxx.search.windows.netindex: trainings-content_safety:- access_key: xxx- endpoint: https://xxx.cognitiveservices.azure.com-ai_translation:access_key: xxxendpoint: https://xxx.cognitiveservices.azure.com@@ -446,20 +427,7 @@ conversation:### Customize the moderation levels-Levels are defined for each category of Content Safety. The higher the score, the more strict the moderation is, from 0 to 7.--Moderation is applied on all bot data, including the web page and the conversation.--```yaml-# config.yaml-[...]--content_safety:- category_hate_score: 0- category_self_harm_score: 0- category_sexual_score: 2- category_violence_score: 0-```+Levels are defined for each category of Content Safety. The higher the score, the more strict the moderation is, from 0 to 7. Moderation is applied on all bot data, including the web page and the conversation. Configure them in Azure OpenAI Content Filters.### Customize the claim data schema@@ -533,7 +501,6 @@ conversation:answer_hard_timeout_sec: 180answer_soft_timeout_sec: 30callback_timeout_hour: 72- content_safety_for_chat: truephone_silence_timeout_sec: 1slow_llm_for_chat: truevoice_recognition_retry_max: 2diff --git a/bicep/app.bicep b/bicep/app.bicepindex 8f63308..f23a1d0 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -15,7 +15,6 @@ param llmSlowModel stringparam llmSlowQuota intparam llmSlowVersion stringparam location string-param moderationBlocklists arrayparam openaiLocation stringparam searchLocation stringparam tags object@@ -93,11 +92,6 @@ var config = {endpoint: 'https://${search.name}.search.windows.net'index: 'trainings'}- content_safety: {- access_key: cognitiveContentsafety.listKeys().key1- blocklists: moderationBlocklists- endpoint: cognitiveContentsafety.properties.endpoint- }prompts: {llm: localConfig.prompts.llmtts: localConfig.prompts.tts@@ -487,23 +481,6 @@ resource cognitiveDocument 'Microsoft.CognitiveServices/accounts@2024-04-01-prev}}-resource cognitiveContentsafety 'Microsoft.CognitiveServices/accounts@2024-04-01-preview' = {- name: '${prefix}-${location}-contentsafety'- location: location- tags: tags- sku: {- name: 'S0' // Pay-as-you-go- }- kind: 'ContentSafety'- properties: {- customSubDomainName: '${prefix}-${location}-contentsafety'- publicNetworkAccess: 'Enabled'- networkAcls: {- defaultAction: 'Allow'- }- }-}-// Cognitive Services OpenAI Contributorresource roleOpenaiContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {name: 'a001fd3d-188f-4b5d-821b-7da978bf7442'diff --git a/bicep/main.bicep b/bicep/main.bicepindex e591405..dfb8d64 100644--- a/bicep/main.bicep+++ b/bicep/main.bicep@@ -63,7 +63,6 @@ module app 'app.bicep' = {llmSlowQuota: llmSlowQuotallmSlowVersion: llmSlowVersionlocation: location- moderationBlocklists: []openaiLocation: openaiLocationsearchLocation: searchLocationtags: tagsdiff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex fa00b88..2afdeef 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -26,7 +26,6 @@ from helpers.llm_worker import (completion_sync,MaximumTokensReachedError,ModelType,- safety_check,SafetyCheckError,)from openai import APIError@@ -134,13 +133,6 @@ async def load_llm_chat("""nonlocal should_play_sound- if CONFIG.conversation.content_safety_for_chat:- try:- text = await safety_check(text)- except SafetyCheckError as e:- logger.warning(f"Unsafe text detected, not playing: {e}")- return-should_play_sound = Falseawait asyncio.gather(handle_recognize_text(diff --git a/helpers/config_models/content_safety.py b/helpers/config_models/content_safety.pydeleted file mode 100644index 0ec39dc..0000000--- a/helpers/config_models/content_safety.py+++ /dev/null@@ -1,11 +0,0 @@-from pydantic import SecretStr, Field, BaseModel---class ContentSafetyModel(BaseModel):- access_key: SecretStr- blocklists: list[str] = []- category_hate_score: int = Field(default=0, ge=0, le=7)- category_self_harm_score: int = Field(default=0, ge=0, le=7)- category_sexual_score: int = Field(default=2, ge=0, le=7)- category_violence_score: int = Field(default=0, ge=0, le=7)- endpoint: strdiff --git a/helpers/config_models/conversation.py b/helpers/config_models/conversation.pyindex c258683..573b321 100644--- a/helpers/config_models/conversation.py+++ b/helpers/config_models/conversation.py@@ -182,7 +182,6 @@ class ConversationModel(BaseModel):default=2, # 2 retriesserialization_alias="max_voice_recognition_retry", # Compatibility with v7)- content_safety_for_chat: bool = Truedef _fields_to_pydantic(name: str, fields: list[ClaimFieldModel]) -> type[BaseModel]:diff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex 0336ad2..10719e5 100644--- a/helpers/config_models/root.py+++ b/helpers/config_models/root.py@@ -3,7 +3,6 @@ from helpers.config_models.ai_translation import AiTranslationModelfrom helpers.config_models.cache import CacheModelfrom helpers.config_models.cognitive_service import CognitiveServiceModelfrom helpers.config_models.communication_services import CommunicationServicesModel-from helpers.config_models.content_safety import ContentSafetyModelfrom helpers.config_models.database import DatabaseModelfrom helpers.config_models.llm import LlmModelfrom helpers.config_models.monitoring import MonitoringModel@@ -34,7 +33,6 @@ class RootModel(BaseSettings):communication_services: CommunicationServicesModel = Field(serialization_alias="communication_service", # Compatibility with v5)- content_safety: ContentSafetyModeldatabase: DatabaseModel = DatabaseModel() # Object is fully defined by defaultllm: LlmModelmonitoring: MonitoringModel = (diff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex 99acc4d..2a9a2c0 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -1,12 +1,3 @@-from azure.ai.contentsafety.aio import ContentSafetyClient-from azure.ai.contentsafety.models import (- AnalyzeTextOptions,- AnalyzeTextResult,- TextCategoriesAnalysis,- TextCategory,-)-from azure.core.credentials import AzureKeyCredential-from azure.core.exceptions import HttpResponseError, ServiceRequestErrorfrom helpers.config import CONFIGfrom helpers.logging import logger, tracerfrom openai import (@@ -44,7 +35,6 @@ from tenacity import ()from functools import lru_cachefrom helpers.config_models.llm import AbstractPlatformModel as LlmAbstractPlatformModel-from helpers.http import azure_transportfrom helpers.resources import resources_dirfrom models.message import MessageModelfrom opentelemetry.instrumentation.openai import OpenAIInstrumentor@@ -65,11 +55,8 @@ environ["TIKTOKEN_CACHE_DIR"] = resources_dir("tiktoken")logger.info(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}")-_cache = CONFIG.cache.instance()ModelType = TypeVar("ModelType", bound=BaseModel)-_contentsafety_client: Optional[ContentSafetyClient] = Noneclass SafetyCheckError(Exception):@@ -332,8 +319,6 @@ async def _completion_sync_worker(if not content:return None- if not json_output:- return await safety_check(content)@retry(@@ -421,124 +406,6 @@ def _limit_messages(][email protected]_as_current_span("safety_check")-async def safety_check(text: str) -> str:- """- Raise `SafetyCheckError` if the text is safe, nothing otherwise.-- Text can be returned both safe and censored, before containing unsafe content.- """- safe_value = "safe"-- # Try cache- cache_key = f"{__name__}-safety_check-{text}"- cached = await _cache.aget(cache_key)- if cached:- decoded = cached.decode()- if decoded == safe_value:- return text # Return safe text- raise SafetyCheckError(decoded)-- try:- res = await _contentsafety_analysis(text)- except ServiceRequestError as e:- logger.error(f"Request error: {e}")- return text # Assume safe- except HttpResponseError as e:- logger.error(f"Response error: {e}")- return text # Assume safe-- # Replace blocklist items with censored text- for match in res.blocklists_match or []:- logger.debug(f"Matched blocklist item: {match.blocklist_item_text}")- text = text.replace(- match.blocklist_item_text, "*" * len(match.blocklist_item_text)- )-- # Check hate category- hate_result = _contentsafety_category_test(- res.categories_analysis,- TextCategory.HATE,- CONFIG.content_safety.category_hate_score,- )- # Check self harm category- self_harm_result = _contentsafety_category_test(- res.categories_analysis,- TextCategory.SELF_HARM,- CONFIG.content_safety.category_self_harm_score,- )- # Check sexual category- sexual_result = _contentsafety_category_test(- res.categories_analysis,- TextCategory.SEXUAL,- CONFIG.content_safety.category_sexual_score,- )- # Check violence category- violence_result = _contentsafety_category_test(- res.categories_analysis,- TextCategory.VIOLENCE,- CONFIG.content_safety.category_violence_score,- )-- # True if all categories are safe- safety = hate_result and self_harm_result and sexual_result and violence_result- logger.debug(f'Text safety "{safety}" for text: {text}')-- if not safety:- error_message = f"Unsafe content detected, hate={hate_result}, self_harm={self_harm_result}, sexual={sexual_result}, violence={violence_result}: {text}"- await _cache.aset(cache_key, error_message)- raise SafetyCheckError(error_message)-- await _cache.aset(cache_key, safe_value)- return text # Return updated text---@retry(- reraise=True,- retry=retry_if_exception_type(HttpResponseError),- stop=stop_after_attempt(3),- wait=wait_random_exponential(multiplier=0.8, max=8),-)-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.- """- client = await _use_contentsafety()- res = await client.analyze_text(- AnalyzeTextOptions(- blocklist_names=CONFIG.content_safety.blocklists,- halt_on_blocklist_hit=False,- output_type="EightSeverityLevels",- text=text,- )- )- return res---def _contentsafety_category_test(- res: list[TextCategoriesAnalysis],- category: TextCategory,- score: int,-) -> bool:- """- Returns `True` if the category is safe or the severity is low, `False` otherwise, meaning the category is unsafe.- """- if score == 0: # No need to check severity- return True-- if (- (detection := next((item for item in res if item.category == category), None))- and detection.severity- and detection.severity > score- ): # Unsafe category detected- logger.debug(f"Matched {category} with severity {detection.severity}")- return False-- return True # Default to safe--@lru_cache # Cache results in memory as token count is done many times on the same contentdef _count_tokens(content: str, model: str) -> int:"""@@ -554,11 +421,6 @@ def _count_tokens(content: str, model: str) -> int:return len(tiktoken.get_encoding(encoding_name).encode(content))-def _llm_key(is_fast: bool) -> str:- platform = CONFIG.llm.selected(is_fast)- return f"{platform.model}-{platform.context}"--def _use_llm(is_fast: bool,) -> Tuple[Union[AsyncAzureOpenAI, AsyncOpenAI], LlmAbstractPlatformModel]:@@ -568,22 +430,3 @@ def _use_llm(The client is either an Azure OpenAI or an OpenAI client, depending on the configuration."""return CONFIG.llm.selected(is_fast).instance()---async def _use_contentsafety() -> ContentSafetyClient:- """- Returns a Content Safety client.- """- global _contentsafety_client- if not isinstance(_contentsafety_client, ContentSafetyClient):- _contentsafety_client = ContentSafetyClient(- # Deployment- endpoint=CONFIG.content_safety.endpoint,- # Performance- transport=await azure_transport(),- # Authentication- credential=AzureKeyCredential(- CONFIG.content_safety.access_key.get_secret_value()- ),- )- return _contentsafety_clientdiff --git a/requirements.txt b/requirements.txtindex 54acd84..cc8fbe9 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,6 +1,5 @@aiohttp==3.9.5 # Required for all Azure SDKsaiosqlite==0.20.0-azure-ai-contentsafety==1.0.0azure-ai-translation-text==1.0.0azure-communication-callautomation==1.2.0azure-communication-sms==1.0.1