async def stream_chat_response(
    *,
    request: Request,
    db: AsyncSession = Depends(get_db),
    chat_id: UUID,
    user: schemas.User = Depends(get_user_from_token_param),
) -> StreamingResponse:
    """Stream an AI response for a chat message.

    Args:
    -----
        request: The request object.
        db: The database session.
        chat_id: The ID of the chat to stream the response for.
        user: The current user.

    Returns:
    -------
        StreamingResponse: The streaming response.
    """

    async def event_generator():
        try:
            async for entity in chat_service.generate_streaming_response(
                db=db, chat_id=chat_id, user=user
            ):
                if entity.choices[0].delta.content is not None:
                    content = entity.choices[0].delta.content
                    # Properly encode newlines for SSE
                    content = content.replace("\n", "\\n")
                    yield f"data: {content}\n\n"
            yield "data: [DONE]\n\n"
        except Exception as e:
            logger.error(f"Error in stream: {str(e)}")
            yield "data: [ERROR]\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",
    )
Stream an AI response for a chat message.

    Args:
    -----
        request: The request object.
        db: The database session.
        chat_id: The ID of the chat to stream the response for.
        user: The current user.

    Returns:
    -------
        StreamingResponse: The streaming response.
    
backend/airweave/api/v1/endpoints/chat.py