Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
fix: Fix intermitent LLM API errors
Clémence Lesnée01dd2359206
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex 9e58d71..c1434b0 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -6,13 +6,12 @@ from azure.ai.contentsafety.models import (TextCategory,)from azure.core.credentials import AzureKeyCredential-from azure.core.exceptions import HttpResponseError+from azure.core.exceptions import HttpResponseError, ServiceRequestErrorfrom helpers.config import CONFIGfrom contextlib import asynccontextmanagerfrom helpers.logging import build_logger, TRACERfrom openai import (APIConnectionError,- APIError,APIResponseValidationError,AsyncAzureOpenAI,AsyncOpenAI,@@ -43,14 +42,14 @@ from tenacity import (stop_after_attempt,wait_random_exponential,)-from typing import AsyncGenerator, Optional, Tuple, Type, TypeVar, Union+from functools import lru_cache+from helpers.config_models.llm import AbstractPlatformModel as LlmAbstractPlatformModelfrom models.message import MessageModel-import tiktoken-import jsonfrom opentelemetry.instrumentation.openai import OpenAIInstrumentorfrom os import environ-from helpers.config_models.llm import AbstractPlatformModel as LlmAbstractPlatformModel-from functools import lru_cache+from typing import AsyncGenerator, Optional, Tuple, Type, TypeVar, Union+import json+import tiktoken# Instrument OpenAI@@ -74,6 +73,7 @@ _retried_exceptions = [RateLimitError,]+class SafetyCheckError(Exception):message: str@@ -148,9 +148,12 @@ async def _completion_stream_worker(cache_key = f"{__name__}-completion_stream-{_llm_key(is_backup)}-{system}-{tools}-{messages}-{max_tokens}"cached = await _cache.aget(cache_key)if cached:- for chunck in TypeAdapter(list[ChoiceDelta]).validate_json(cached):- yield chunck- return+ try:+ for chunck in TypeAdapter(list[ChoiceDelta]).validate_json(cached):+ yield chunck+ return+ except ValidationError as e:+ _logger.debug(f"Parsing error: {e.errors()}")# Try liveto_cache: list[ChoiceDelta] = []@@ -407,45 +410,51 @@ async def safety_check(text: str) -> None:Text can be returned both safe and censored, before containing unsafe content."""- if not text:+ if not text: # Empty text is safereturn+try:res = await _contentsafety_analysis(text)- except HttpResponseError as e:- _logger.error(f"Failed to run safety check: {e}")+ except ServiceRequestError as e:+ _logger.error(f"Request error: {e}")return # Assume safe-- if not res:- _logger.error("Failed to run safety check: No result")+ except HttpResponseError as e:+ _logger.error(f"Response error: {e}")return # Assume safe+ # Replace blocklist items with censored textfor 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 categoryhate_result = _contentsafety_category_test(res.categories_analysis,TextCategory.HATE,CONFIG.content_safety.category_hate_score,)+ # Check self harm categoryself_harm_result = _contentsafety_category_test(res.categories_analysis,TextCategory.SELF_HARM,CONFIG.content_safety.category_self_harm_score,)+ # Check sexual categorysexual_result = _contentsafety_category_test(res.categories_analysis,TextCategory.SEXUAL,CONFIG.content_safety.category_sexual_score,)+ # Check violence categoryviolence_result = _contentsafety_category_test(res.categories_analysis,TextCategory.VIOLENCE,CONFIG.content_safety.category_violence_score,)+ # True if all categories are safesafety = hate_result and self_harm_result and sexual_result and violence_result_logger.debug(f'Text safety "{safety}" for text: {text}')