Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Detect jailbreaks attempts during LLM generation
Clémence Lesnéea4a19f5551a
diff --git a/README.md b/README.mdindex 40d79b5..2cc0485 100644--- a/README.md+++ b/README.md@@ -63,6 +63,7 @@ curl \- [x] Follow a specific data schema for the claim- [x] Has access to a documentation database (few-shot training / RAG)- [x] Help the user to find the information needed to complete the claim+- [x] Jailbreak detection- [x] Lower AI Search cost by usign a Redis cache- [x] Monitoring and tracing with Application Insights- [x] Receive SMS during a conversation for explicit wordingsdiff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex 77795ea..9de2d41 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -4,6 +4,7 @@ from helpers.config import CONFIGfrom helpers.logging import loggerfrom models.call import CallStateModelfrom models.message import (+ ActionEnum as MessageAction,extract_message_style,MessageModel,PersonaEnum as MessagePersonaEnum,@@ -59,7 +60,7 @@ async def llm_completion(text: Optional[str], call: CallStateModel) -> Optional[except APIError as e:logger.warning(f"OpenAI API call error: {e}")except SafetyCheckError as e:- logger.warning(f"OpenAI safety check error: {e}")+ logger.warning(f"Safety Check error: {e}")return content@@ -412,12 +413,25 @@ async def _execute_llm_chat():content_buffer_pointer += len(sentence)plugins.style = await _content_callback(sentence, plugins.style)- except MaximumTokensReachedError:+ except MaximumTokensReachedError: # Retry on maximum tokens reachedlogger.warning("Maximum tokens reached for this completion, retry asked")maximum_tokens_reached = True- except APIError as e:+ except APIError as e: # Retry on API errorlogger.warning(f"OpenAI API call error: {e}")return True, True, call # Error, retry+ except SafetyCheckError as e: # Last user message is trash, remove it+ logger.warning(f"Safety Check error: {e}")+ if last_message := next(+ (+ call+ for call in reversed(call.messages)+ if call.persona == MessagePersonaEnum.HUMAN+ and call.action in [MessageAction.SMS, MessageAction.TALK]+ ),+ None,+ ): # Remove last user message+ call.messages.remove(last_message)+ return True, False, call # Error, no retry# Flush the remaining bufferif content_buffer_pointer < len(content_full):diff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex ce3f42c..c996872 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -15,6 +15,7 @@ from openai import (AsyncAzureOpenAI,AsyncOpenAI,AsyncStream,+ BadRequestError,InternalServerError,RateLimitError,)@@ -84,7 +85,6 @@ _retried_exceptions = [APIResponseValidationError,InternalServerError,RateLimitError,- SafetyCheckError,]@@ -173,54 +173,69 @@ async def _completion_stream_worker(} # Shared kwargs for both streaming and non-streamingmaximum_tokens_reached = False- if platform.streaming: # Streaming- stream: AsyncStream[ChatCompletionChunk] = await client.chat.completions.create(- **chat_kwargs,- stream=True,- )- async for chunck in stream:- choices = chunck.choices- if not choices: # Skip empty choices, happens sometimes with GPT-4 Turbo- continue- choice = choices[0]+ try:+ if platform.streaming: # Streaming+ stream: AsyncStream[ChatCompletionChunk] = (+ await client.chat.completions.create(+ **chat_kwargs,+ stream=True,+ )+ )+ async for chunck in stream:+ choices = chunck.choices+ if (+ not choices+ ): # Skip empty choices, happens sometimes with GPT-4 Turbo+ continue+ choice = choices[0]+ if (+ choice.finish_reason == "content_filter"+ ): # Azure OpenAI content filter+ raise SafetyCheckError(+ f"Issue detected in text: {choice.delta.content}"+ )+ if choice.finish_reason == "length":+ logger.warning(+ f"Maximum tokens reached {max_tokens}, should be fixed"+ )+ maximum_tokens_reached = True+ delta = choice.delta+ yield delta++ else: # Non-streaming, emulate streaming with a single completion+ completion: ChatCompletion = await client.chat.completions.create(+ **chat_kwargs+ )+ choice = completion.choices[0]if choice.finish_reason == "content_filter": # Azure OpenAI content filterraise SafetyCheckError(- f"Content filter detected for text: {choice.delta.content}"+ f"Issue detected in generation: {choice.message.content}")if choice.finish_reason == "length":logger.warning(f"Maximum tokens reached {max_tokens}, should be fixed")maximum_tokens_reached = True- delta = choice.delta- yield delta-- else: # Non-streaming, emulate streaming with a single completion- completion: ChatCompletion = await client.chat.completions.create(**chat_kwargs)- choice = completion.choices[0]- if choice.finish_reason == "content_filter": # Azure OpenAI content filter- raise SafetyCheckError(- f"Content filter detected for text: {choice.message.content}"+ message = choice.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 []+ ],)- if choice.finish_reason == "length":- logger.warning(f"Maximum tokens reached {max_tokens}, should be fixed")- maximum_tokens_reached = True- message = choice.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+ yield delta+ except BadRequestError as e:+ if e.code == "content_filter":+ raise SafetyCheckError("Issue detected in prompt")+ raise eif maximum_tokens_reached:raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")@@ -294,18 +309,23 @@ async def _completion_sync_worker(system=system,)- res = await client.chat.completions.create(- max_tokens=max_tokens,- messages=prompt,- model=platform.model,- seed=42, # Reproducible results- temperature=0, # Most focused and deterministic- **extra,- )+ try:+ res = await client.chat.completions.create(+ max_tokens=max_tokens,+ messages=prompt,+ model=platform.model,+ seed=42, # Reproducible results+ temperature=0, # Most focused and deterministic+ **extra,+ )+ except BadRequestError as e:+ if e.code == "content_filter":+ raise SafetyCheckError("Issue detected in prompt")+ raise echoice = res.choices[0]if choice.finish_reason == "content_filter": # Azure OpenAI content filterraise SafetyCheckError(- f"Content filter detected for text: {choice.message.content}"+ f"Issue detected in generation: {choice.message.content}")if choice.finish_reason == "length":raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")