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.mdindex 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 LRuser(["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 LRapi -- Generate completion --> gptapi -- Save conversation --> dbapi -- Send SMS report --> communication_service_sms+ api -- Test for profanity --> constent_safetyapi -- Transfer to agent --> communication_serviceapi -. Watch .-> event_grid@@ -170,6 +173,11 @@ ai_search:endpoint: https://xxx.search.windows.netindex: trainingssemantic_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: trainingssemantic_configuration: default++content_safety:+ blocklists: []```Steps to deploy:diff --git a/bicep/app.bicep b/bicep/app.bicepindex 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.pynew file mode 100644index 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: strdiff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex 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 AiSearchModelfrom helpers.config_models.api import ApiModelfrom helpers.config_models.cognitive_service import CognitiveServiceModelfrom helpers.config_models.communication_service import CommunicationServiceModel+from helpers.config_models.content_safety import ContentSafetyModelfrom helpers.config_models.database import DatabaseModelfrom helpers.config_models.monitoring import MonitoringModelfrom helpers.config_models.openai import OpenAiModel@@ -20,6 +21,7 @@ class RootModel(BaseSettings, env_prefix=""):api: ApiModelcognitive_service: CognitiveServiceModelcommunication_service: CommunicationServiceModel+ content_safety: ContentSafetyModeldatabase: DatabaseModelmonitoring: MonitoringModel = (MonitoringModel()diff --git a/helpers/llm.py b/helpers/llm.pynew file mode 100644index 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 Truediff --git a/main.py b/main.pyindex 643f9f0..908ea08 100644--- a/main.py+++ b/main.py@@ -23,7 +23,7 @@ from azure.core.exceptions import ClientAuthenticationErrorfrom azure.core.exceptions import ResourceNotFoundErrorfrom azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNames-from azure.identity import DefaultAzureCredential, get_bearer_token_provider+from azure.identity import DefaultAzureCredentialfrom enum import Enumfrom fastapi import FastAPI, status, Request, HTTPException, BackgroundTasksfrom fastapi.responses import JSONResponse, HTMLResponse@@ -36,7 +36,6 @@ from models.synthesis import SynthesisModelfrom persistence.ai_search import AiSearchSearchfrom persistence.cosmos import CosmosStorefrom persistence.sqlite import SqliteStore-from tenacity import retry, stop_after_attempt, wait_random_exponentialfrom urllib.parse import quote_plusimport asyncioimport 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 openaiTypesfrom uuid import UUIDimport 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 Servicessource_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 = Trueawait handle_play(call=call,client=client,@@ -586,7 +569,7 @@ async def gpt_completion(system: str, call: CallModel, max_tokens: int) -> str:content = Nonetry:- 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.txtindex 5d4e841..08b9e2b 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,5 +1,6 @@aiohttp==3.9.1 # Required for azure-search-documentsaiosqlite==0.19.0+azure-ai-contentsafety==1.0.0azure-communication-callautomation==1.1.0azure-communication-sms==1.0.1azure-cosmos==4.5.1