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

feat: Filter out profanity and blocklist

Clémence Lesné757dce072677
diff --git a/README.md b/README.md
index d1f7283..02a5596 100644
--- a/README.md
+++ b/README.md
@@ -52,6 +52,7 @@ Extract of the data stored during the call:
- [x] Create by itself a todo list of tasks to complete the claim
- [x] Customizable prompts
- [x] Disengaging from a human agent when needed
+- [x] Filter out inappropriate content from the LLM, like profanity or concurrence company names
- [x] Fine understanding of the customer request with GPT-4 Turbo
- [x] Follow a specific data schema for the claim
- [x] Has access to a documentation database (few-shot training / RAG)
@@ -96,10 +97,11 @@ graph LR
user(["User"])
subgraph "Claim AI"
- api["API"]
ai_search[("RAG\n(AI Search)")]
+ api["API"]
communication_service_sms["SMS gateway\n(Communication Services)"]
communication_service["Call gateway\n(Communication Services)"]
+ constent_safety["Moderation\n(Content Safety)"]
db[("Conversations and claims\n(Cosmos DB or SQLite)")]
event_grid[("Broker\n(Event Grid)")]
gpt["GPT-4 Turbo\n(OpenAI)"]
@@ -110,6 +112,7 @@ graph LR
api -- Generate completion --> gpt
api -- Save conversation --> db
api -- Send SMS report --> communication_service_sms
+ api -- Test for profanity --> constent_safety
api -- Transfer to agent --> communication_service
api -. Watch .-> event_grid
@@ -170,6 +173,11 @@ ai_search:
endpoint: https://xxx.search.windows.net
index: trainings
semantic_configuration: default
+
+content_safety:
+ access_key: xxx
+ blocklists: []
+ endpoint: https://xxx.cognitiveservices.azure.com
```
If you want to use a Service Principal to authenticate to Azure, you can also add the following in a `.env` file:
@@ -243,6 +251,9 @@ openai: {}
ai_search:
index: trainings
semantic_configuration: default
+
+content_safety:
+ blocklists: []
```
Steps to deploy:
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 0017258..f1c4272 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -130,6 +130,14 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {
name: 'AI_SEARCH_ACCESS_KEY'
value: search.listAdminKeys().primaryKey
}
+ {
+ name: 'CONTENT_SAFETY_ENDPOINT'
+ value: cognitiveContentsafety.properties.endpoint
+ }
+ {
+ name: 'CONTENT_SAFETY_ACCESS_KEY'
+ value: cognitiveContentsafety.listKeys().key1
+ }
]
resources: {
cpu: 1
@@ -198,6 +206,23 @@ resource eventgridTopic 'Microsoft.EventGrid/systemTopics@2023-12-15-preview' =
}
}
+resource cognitiveContentsafety 'Microsoft.CognitiveServices/accounts@2023-10-01-preview' = {
+ name: '${prefix}-contentsafety'
+ location: location
+ tags: tags
+ sku: {
+ name: 'F0'
+ }
+ kind: 'ContentSafety'
+ properties: {
+ customSubDomainName: '${prefix}-contentsafety'
+ publicNetworkAccess: 'Enabled'
+ networkAcls: {
+ defaultAction: 'Allow'
+ }
+ }
+}
+
resource roleOpenaiContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {
name: 'a001fd3d-188f-4b5d-821b-7da978bf7442'
}
diff --git a/helpers/config_models/content_safety.py b/helpers/config_models/content_safety.py
new file mode 100644
index 0000000..13ea6ba
--- /dev/null
+++ b/helpers/config_models/content_safety.py
@@ -0,0 +1,9 @@
+from typing import List
+from pydantic import SecretStr
+from pydantic_settings import BaseSettings
+
+
+class ContentSafetyModel(BaseSettings, env_prefix="content_safety_"):
+ access_key: SecretStr
+ blocklists: List[str]
+ endpoint: str
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index bc75b38..49c3910 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -2,6 +2,7 @@ from helpers.config_models.ai_search import AiSearchModel
from helpers.config_models.api import ApiModel
from helpers.config_models.cognitive_service import CognitiveServiceModel
from helpers.config_models.communication_service import CommunicationServiceModel
+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
@@ -20,6 +21,7 @@ class RootModel(BaseSettings, env_prefix=""):
api: ApiModel
cognitive_service: CognitiveServiceModel
communication_service: CommunicationServiceModel
+ content_safety: ContentSafetyModel
database: DatabaseModel
monitoring: MonitoringModel = (
MonitoringModel()
diff --git a/helpers/llm.py b/helpers/llm.py
new file mode 100644
index 0000000..9cd2813
--- /dev/null
+++ b/helpers/llm.py
@@ -0,0 +1,142 @@
+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
+from azure.identity import DefaultAzureCredential, get_bearer_token_provider
+from helpers.config import CONFIG
+from helpers.logging import build_logger
+from openai import _types as openaiTypes
+from openai import AsyncAzureOpenAI, AsyncStream
+from openai.types.chat import ChatCompletionMessage, ChatCompletionChunk
+from openai.types.chat.chat_completion_chunk import ChoiceDelta
+from tenacity import retry, stop_after_attempt, wait_random_exponential
+from typing import Any, AsyncGenerator, List, Optional
+
+
+_logger = build_logger(__name__)
+
+_logger.info(f"Using OpenAI GPT model {CONFIG.openai.gpt_model}")
+_oai = AsyncAzureOpenAI(
+ api_version="2023-12-01-preview",
+ azure_deployment=CONFIG.openai.gpt_deployment,
+ azure_endpoint=CONFIG.openai.endpoint,
+ # Authentication, either RBAC or API key
+ api_key=CONFIG.openai.api_key.get_secret_value() if CONFIG.openai.api_key else None,
+ azure_ad_token_provider=(
+ get_bearer_token_provider(
+ DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
+ )
+ if not CONFIG.openai.api_key
+ else None
+ ),
+)
+
+_logger.info(f"Using Content Safety {CONFIG.content_safety.endpoint}")
+_contentsafety = ContentSafetyClient(
+ credential=AzureKeyCredential(CONFIG.content_safety.access_key.get_secret_value()),
+ endpoint=CONFIG.content_safety.endpoint,
+)
+
+
+@retry(stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30))
+async def completion_stream(
+ messages: List[dict[str, Any]],
+ max_tokens: int,
+ tools: Optional[List[dict[str, Any]]] = None,
+) -> AsyncGenerator[ChoiceDelta, None]:
+ stream: AsyncStream[ChatCompletionChunk] = await _oai.chat.completions.create(
+ max_tokens=max_tokens,
+ messages=messages,
+ model=CONFIG.openai.gpt_model,
+ stream=True,
+ temperature=0, # Most focused and deterministic
+ tools=tools or openaiTypes.NOT_GIVEN,
+ )
+ async for chunck in stream:
+ yield chunck.choices[0].delta
+
+
+@retry(stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30))
+async def completion_sync(
+ messages: List[dict[str, Any]],
+ max_tokens: int,
+ tools: Optional[List[dict[str, Any]]] = None,
+) -> ChatCompletionMessage:
+ res = await _oai.chat.completions.create(
+ max_tokens=max_tokens,
+ messages=messages,
+ model=CONFIG.openai.gpt_model,
+ temperature=0, # Most focused and deterministic
+ tools=tools or openaiTypes.NOT_GIVEN,
+ )
+ return res.choices[0].message
+
+
+async def safety_check(text: str) -> bool:
+ """
+ Returns True if the text is safe, False otherwise.
+
+ Text can be returned both safe and censored, before containing unsafe content.
+ """
+ try:
+ res = await _contentsafety_analysis(text)
+ except HttpResponseError as e:
+ _logger.error(f"Failed to run safety check: {e.message}")
+ return True # Assume safe
+
+ if not res:
+ _logger.error("Failed to run safety check: No result")
+ return True # Assume safe
+
+ 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)
+ )
+
+ hate_result = _contentsafety_category_test(
+ res.categories_analysis, TextCategory.HATE
+ )
+ self_harm_result = _contentsafety_category_test(
+ res.categories_analysis, TextCategory.SELF_HARM
+ )
+ sexual_result = _contentsafety_category_test(
+ res.categories_analysis, TextCategory.SEXUAL
+ )
+ violence_result = _contentsafety_category_test(
+ res.categories_analysis, TextCategory.VIOLENCE
+ )
+
+ safety = hate_result and self_harm_result and sexual_result and violence_result
+ _logger.debug(f'Text safety "{safety}" for text: {text}')
+
+ return safety
+
+
+@retry(stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30))
+async def _contentsafety_analysis(text: str) -> AnalyzeTextResult:
+ return await _contentsafety.analyze_text(
+ AnalyzeTextOptions(
+ text=text,
+ blocklist_names=CONFIG.content_safety.blocklists,
+ halt_on_blocklist_hit=False,
+ )
+ )
+
+
+def _contentsafety_category_test(
+ res: List[TextCategoriesAnalysis], category: TextCategory
+) -> bool:
+ """
+ Returns True if the category is safe or the severity is low. False otherwise, meaning the category is unsafe.
+ """
+ detection = next(item for item in res if item.category == category)
+ if detection and detection.severity and detection.severity > 2:
+ _logger.debug(f"Matched {category} with severity {detection.severity}")
+ return False
+ return True
diff --git a/main.py b/main.py
index 643f9f0..908ea08 100644
--- a/main.py
+++ b/main.py
@@ -23,7 +23,7 @@ from azure.core.exceptions import ClientAuthenticationError
from azure.core.exceptions import ResourceNotFoundError
from azure.core.messaging import CloudEvent
from azure.eventgrid import EventGridEvent, SystemEventNames
-from azure.identity import DefaultAzureCredential, get_bearer_token_provider
+from azure.identity import DefaultAzureCredential
from enum import Enum
from fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse, HTMLResponse
@@ -36,7 +36,6 @@ from models.synthesis import SynthesisModel
from persistence.ai_search import AiSearchSearch
from persistence.cosmos import CosmosStore
from persistence.sqlite import SqliteStore
-from tenacity import retry, stop_after_attempt, wait_random_exponential
from urllib.parse import quote_plus
import asyncio
import html
@@ -48,12 +47,9 @@ from models.message import (
ToolModel as MessageToolModel,
)
from models.claim import ClaimModel
-from openai import AsyncAzureOpenAI, AsyncStream
-from openai.types.chat import ChatCompletionMessage, ChatCompletionChunk
-from openai.types.chat.chat_completion_chunk import ChoiceDelta
-from openai import _types as openaiTypes
from uuid import UUID
import json
+from helpers.llm import completion_stream, completion_sync, safety_check
# Jinja templates
@@ -64,23 +60,6 @@ jinja = Environment(
)
jinja.filters["quote_plus"] = lambda x: quote_plus(str(x)) if x else ""
-# Azure OpenAI
-_logger.info(f"Using OpenAI GPT model {CONFIG.openai.gpt_model}")
-oai_gpt = AsyncAzureOpenAI(
- api_version="2023-12-01-preview",
- azure_deployment=CONFIG.openai.gpt_deployment,
- azure_endpoint=CONFIG.openai.endpoint,
- # Authentication, either RBAC or API key
- api_key=CONFIG.openai.api_key.get_secret_value() if CONFIG.openai.api_key else None,
- azure_ad_token_provider=(
- get_bearer_token_provider(
- DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
- )
- if not CONFIG.openai.api_key
- else None
- ),
-)
-
# Azure Communication Services
source_caller = PhoneNumberIdentifier(CONFIG.communication_service.phone_number)
_logger.info(f"Using phone number {str(CONFIG.communication_service.phone_number)}")
@@ -418,8 +397,12 @@ async def intelligence(
async def gpt_callback(text: str) -> None:
nonlocal has_started
- has_started = True
+ if not await safety_check(text):
+ _logger.warn(f"Unsafe text detected, not playing ({call.call_id})")
+ return
+
+ has_started = True
await handle_play(
call=call,
client=client,
@@ -586,7 +569,7 @@ async def gpt_completion(system: str, call: CallModel, max_tokens: int) -> str:
content = None
try:
- res = await _gpt_completion_sync(
+ res = await completion_sync(
max_tokens=max_tokens,
messages=messages,
)
@@ -799,8 +782,8 @@ async def gpt_chat(
buffer_content = ""
tool_calls = {}
try:
- async for delta in _gpt_completion_stream(
- max_tokens=300,
+ async for delta in completion_stream(
+ max_tokens=400,
messages=messages,
tools=tools,
):
@@ -1185,40 +1168,6 @@ async def post_call_synthesis(call: CallModel) -> None:
await db.call_aset(call)
-@retry(stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30))
-async def _gpt_completion_stream(
- messages: List[dict[str, Any]],
- max_tokens: int,
- tools: Optional[List[dict[str, Any]]] = None,
-) -> AsyncGenerator[ChoiceDelta, None]:
- stream: AsyncStream[ChatCompletionChunk] = await oai_gpt.chat.completions.create(
- max_tokens=max_tokens,
- messages=messages,
- model=CONFIG.openai.gpt_model,
- stream=True,
- temperature=0, # Most focused and deterministic
- tools=tools or openaiTypes.NOT_GIVEN,
- )
- async for chunck in stream:
- yield chunck.choices[0].delta
-
-
-@retry(stop=stop_after_attempt(3), wait=wait_random_exponential(multiplier=0.5, max=30))
-async def _gpt_completion_sync(
- messages: List[dict[str, Any]],
- max_tokens: int,
- tools: Optional[List[dict[str, Any]]] = None,
-) -> ChatCompletionMessage:
- res = await oai_gpt.chat.completions.create(
- max_tokens=max_tokens,
- messages=messages,
- model=CONFIG.openai.gpt_model,
- temperature=0, # Most focused and deterministic
- tools=tools or openaiTypes.NOT_GIVEN,
- )
- return res.choices[0].message
-
-
def _remove_message_actions(text: str) -> str:
"""
Remove action from content. AI often adds it by mistake event if explicitly asked not to.
diff --git a/requirements.txt b/requirements.txt
index 5d4e841..08b9e2b 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,5 +1,6 @@
aiohttp==3.9.1 # Required for azure-search-documents
aiosqlite==0.19.0
+azure-ai-contentsafety==1.0.0
azure-communication-callautomation==1.1.0
azure-communication-sms==1.0.1
azure-cosmos==4.5.1