How to handle this gracefully with live kit agent ...
# ask-ai
r
How to handle this gracefully with live kit agent when using AzureOpenAI BadRequestError
Copy code
Error code: 400 - {'error': {'message': "The response was filtered due to the prompt triggering Azure OpenAI's content management policy. Please modify your prompt and retry. To learn more about our content filtering policies please read our documentation: https://go.microsoft.com/fwlink/?linkid=2198766", 'type': None, 'param': 'prompt', 'code': 'content_filter', 'status': 400, 'innererror': {'code': 'ResponsibleAIPolicyViolation', 'content_filter_result': {'hate': {'filtered': False, 'severity': 'safe'}, 'jailbreak': {'filtered': True, 'detected': True}, 'self_harm': {'filtered': False, 'severity': 'safe'}, 'sexual': {'filtered': False, 'severity': 'safe'}, 'violence': {'filtered': False, 'severity': 'safe'}}}}}
t
Thanks for reaching out, pritesh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! The BadRequestError 400 you ran into happens because Azure OpenAI’s content management policy flagged some inputs or outputs. Basically, if the content trips Azure’s filters, you’ll see this error, as the details explain. Here’s how you can smoothly handle this in LiveKit: • Set up error handling in your app to spot when you get null or empty response chunks. For instance, in Python, you can check if the
chat_chunk
from the LLM stream is
None
. That means the content was filtered, and you can gently let your user know with a generic message. • Check out this simple Python example for handling it:
Copy code
async for chat_chunk in llm.chat(chat_ctx=chat_context):
    if chat_chunk is None:
        # Azure OpenAI filtered the content
        # Handle this by, say, sending a friendly message to the user
        continue
    # Process the valid chat_chunk
• Also, take a moment to review and tweak what you’re sending to the model to make sure it fits within Azure OpenAI’s content guidelines—avoiding anything harmful, offensive, or inappropriate. With these tips, you’ll be able to handle filtered responses smoothly and keep things running nicely without hitting policy snags. Sources: plugins/openai/src/realtime/realtime_model.ts | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/stt.py
r
But it throwse 400 error immediately BadRequestError
Copy code
Error code: 400 - {'error': {'message': "The response was filtered due to the prompt triggering Azure OpenAI's content management policy. Please modify your prompt and retry. To learn more about our content filtering policies please read our documentation: https://go.microsoft.com/fwlink/?linkid=2198766", 'type': None, 'param': 'prompt', 'code': 'content_filter', 'status': 400, 'innererror': {'code': 'ResponsibleAIPolicyViolation', 'content_filter_result': {'hate': {'filtered': False, 'severity': 'safe'}, 'jailbreak': {'filtered': True, 'detected': True}, 'self_harm': {'filtered': False, 'severity': 'safe'}, 'sexual': {'filtered': False, 'severity': 'safe'}, 'violence': {'filtered': False, 'severity': 'safe'}}}}}
So, where we can catch this errir and handle
t
Hey there! If you’re running into that pesky BadRequestError 400 right away, don’t worry—we can catch and handle it smoothly in your app. Here’s a friendly guide on how to do it: 1. Catching Errors When Setting Up the Service:
Copy code
from livekit.plugins import openai
from livekit.agents import APIConnectionError, APIStatusError

try:
    azure_llm = openai.LLM.with_azure(
        azure_deployment="my-deployment",
        api_version="2024-10-01-preview",
    )
except (APIConnectionError, APIStatusError) as e:
    print(f"Oops, an API error popped up: {e.message}")
except ValueError as e:
    print(f"Looks like there was a validation error: {e}")
2. Catching Errors During Your Realtime API Session:
Copy code
realtime_model = openai.LLM.with_dial_api(azure_deployment="your-deployment", api_version="your-version")

def on_error(model_event):
    if hasattr(model_event.error, 'status_code') and model_event.error.status_code == 400:
        print("Heads up! Caught an Azure OpenAI BadRequestError (400):", model_event.error.message)

realtime_model.on("error", on_error)
3. Catching Errors While Chatting with the LLM:
Copy code
async def chat_with_llm():
    azure_llm = openai.LLM.with_azure(azure_deployment="your-deployment")
    chat_ctx = openai.ChatContext()
    chat_ctx.add_user_message("Hello!")

    try:
        stream = await azure_llm.chat(chat_ctx)
        async for chunk in stream:
            if chunk.usage:
                print(f"Tokens used: {chunk.usage.total_tokens}")
            elif chunk.text:
                print(chunk.text)
    except APIStatusError as e:
        if e.status_code == 400:
            print(f"Uh-oh, the LLM request failed with a bad request: {e.message}")
By adding these handy error-handling steps, you’ll be able to catch those 400 errors right when they happen, so you can give helpful feedback or tweak your inputs and try again. If you need a hand with anything else, just let me know! Sources: Azure OpenAI STT integration guide | LiveKit Docs | Azure OpenAI TTS integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/llm.py | plugins/openai/src/llm.ts | Azure OpenAI LLM integration guide | LiveKit Docs
r
Can we catch LLM error at ErrorEvent hook like we have other hooks @victorious-keyboard-18262.on("user_state_changed") def on_user_state_changed(_ev_: UserStateChangedEvent)
t
Absolutely! You can catch LLM errors using
ErrorEvent
hooks in LiveKit, just like you would with
user_state_changed
events. The
AgentSession
class sends out an
ErrorEvent
anytime something goes wrong during the session—whether that’s with LLM, STT, TTS, or RealtimeModel components. Here’s a friendly example to show you how to set this up in Python:
Copy code
from livekit.agents import AgentSession, ErrorEvent\n\nsession = AgentSession(\n    stt=deepgram.STT(),\n    llm=openai.LLM(),\n    tts=cartesia.TTS(),\n    vad=silero.VAD.load(),\n)\n\n@session.on("error")\ndef on_error(ev: ErrorEvent):\n    if ev.error.recoverable:\n        return  # No worries, we can ignore recoverable errors\n\n    print(f"Unrecoverable error occurred: {ev.error}")\n    # Here, you might want to let the user know or transfer the call\n    session.say(\n        "I'm having trouble connecting right now. Let me transfer your call.",\n        allow_interruptions=False,\n    )
The
ErrorEvent
gives you an
error
object with all the details you need, plus a handy
recoverable
flag to help you decide if you should try again or handle it differently. This way, you can log issues, retry, or gently inform the user. Using this method, you’ll be able to smoothly handle any LLM hiccups and keep the experience seamless for your users. Sources: Events and error handling | LiveKit Docs | examples/voice_agents/README.md | agents/src/llm/llm.ts