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

chore: Remove explicit Content Safety usage

Clémence Lesnéa9841c3d457e
diff --git a/README.md b/README.md
index 9fe57b9..fd985e0 100644
--- a/README.md
+++ b/README.md
@@ -144,7 +144,6 @@ graph LR
ada["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 LR
app -- Get cached data --> redis
app -- Save conversation --> db
app -- Send SMS report --> communication_services
- app -- Test for profanity --> constent_safety
app -. Watch .-> queues
communication_services -- Generate voice --> tts
@@ -196,7 +194,6 @@ sequenceDiagram
actor Human agent
participant Event Grid
participant Communication Services
- participant Content Safety
participant App
participant Cosmos DB
participant OpenAI GPT
@@ -223,10 +220,6 @@ sequenceDiagram
loop Over buffer
loop Over multiple tools
alt 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
- end
App->>Cosmos DB: Update claim data
else Does the user want the human agent?
App->>Communication Services: Send static SSML text
@@ -237,14 +230,6 @@ sequenceDiagram
App->>Communication Services: End the call
end
end
- 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
- end
end
App->>Cosmos DB: Persist conversation
end
@@ -344,10 +329,6 @@ ai_search:
endpoint: https://xxx.search.windows.net
index: trainings
-content_safety:
- access_key: xxx
- endpoint: https://xxx.cognitiveservices.azure.com
-
ai_translation:
access_key: xxx
endpoint: 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: 180
answer_soft_timeout_sec: 30
callback_timeout_hour: 72
- content_safety_for_chat: true
phone_silence_timeout_sec: 1
slow_llm_for_chat: true
voice_recognition_retry_max: 2
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 8f63308..f23a1d0 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -15,7 +15,6 @@ param llmSlowModel string
param llmSlowQuota int
param llmSlowVersion string
param location string
-param moderationBlocklists array
param openaiLocation string
param searchLocation string
param 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.llm
tts: 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 Contributor
resource roleOpenaiContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {
name: 'a001fd3d-188f-4b5d-821b-7da978bf7442'
diff --git a/bicep/main.bicep b/bicep/main.bicep
index e591405..dfb8d64 100644
--- a/bicep/main.bicep
+++ b/bicep/main.bicep
@@ -63,7 +63,6 @@ module app 'app.bicep' = {
llmSlowQuota: llmSlowQuota
llmSlowVersion: llmSlowVersion
location: location
- moderationBlocklists: []
openaiLocation: openaiLocation
searchLocation: searchLocation
tags: tags
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 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 = False
await asyncio.gather(
handle_recognize_text(
diff --git a/helpers/config_models/content_safety.py b/helpers/config_models/content_safety.py
deleted file mode 100644
index 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: str
diff --git a/helpers/config_models/conversation.py b/helpers/config_models/conversation.py
index 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 retries
serialization_alias="max_voice_recognition_retry", # Compatibility with v7
)
- content_safety_for_chat: bool = True
def _fields_to_pydantic(name: str, fields: list[ClaimFieldModel]) -> type[BaseModel]:
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index 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 AiTranslationModel
from helpers.config_models.cache import CacheModel
from helpers.config_models.cognitive_service import CognitiveServiceModel
from helpers.config_models.communication_services import CommunicationServicesModel
-from helpers.config_models.content_safety import ContentSafetyModel
from helpers.config_models.database import DatabaseModel
from helpers.config_models.llm import LlmModel
from 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: ContentSafetyModel
database: DatabaseModel = DatabaseModel() # Object is fully defined by default
llm: LlmModel
monitoring: MonitoringModel = (
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 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, ServiceRequestError
from helpers.config import CONFIG
from helpers.logging import logger, tracer
from openai import (
@@ -44,7 +35,6 @@ from tenacity import (
)
from functools import lru_cache
from helpers.config_models.llm import AbstractPlatformModel as LlmAbstractPlatformModel
-from helpers.http import azure_transport
from helpers.resources import resources_dir
from models.message import MessageModel
from 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] = None
class 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 content
def _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_client
diff --git a/requirements.txt b/requirements.txt
index 54acd84..cc8fbe9 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,5 @@
aiohttp==3.9.5 # Required for all Azure SDKs
aiosqlite==0.20.0
-azure-ai-contentsafety==1.0.0
azure-ai-translation-text==1.0.0
azure-communication-callautomation==1.2.0
azure-communication-sms==1.0.1