Repository: Significant-Gravitas/Auto-GPT
File: autogpt_platform/backend/backend/api/features/chat/service.py (Python)

Code before:
    except Exception as e:
        logger.error(f"Failed to generate LLM continuation: {e}", exc_info=True)


def _log_api_error(
    error: Exception,
    session_id: str | None = None,
    message_count: int | None = None,
    model: str | None = None,
    retry_count: int = 0,
) -> None:
    """Log detailed API error information for debugging."""
    details = _extract_api_error_details(error)
    details["session_id"] = session_id
    details["message_count"] = message_count
    details["model"] = model
    details["retry_count"] = retry_count

    if isinstance(error, RateLimitError):
        logger.warning(f"Rate limit error: {details}")
    elif isinstance(error, APIConnectionError):
        logger.warning(f"API connection error: {details}")
    elif isinstance(error, APIStatusError) and error.status_code >= 500:
        logger.error(f"API server error (5xx): {details}")
    else:
        logger.error(f"API error: {details}")


def _extract_api_error_details(error: Exception) -> dict[str, Any]:
    """Extract detailed information from OpenAI/OpenRouter API errors."""
    error_msg = str(error)
    details: dict[str, Any] = {
        "error_type": type(error).__name__,
        "error_message": error_msg[:500] + "..." if len(error_msg) > 500 else error_msg,
    }

    if hasattr(error, "code"):
        details["code"] = getattr(error, "code", None)
    if hasattr(error, "param"):
        details["param"] = getattr(error, "param", None)

    if isinstance(error, APIStatusError):
        details["status_code"] = error.status_code
        details["request_id"] = getattr(error, "request_id", None)

        if hasattr(error, "body") and error.body:
            details["response_body"] = _sanitize_error_body(error.body)

        if hasattr(error, "response") and error.response:
            headers = error.response.headers
            details["openrouter_provider"] = headers.get("x-openrouter-provider")

Review comment (suggestion):
```suggestion
    if isinstance(error, RateLimitError):
        logger.warning(f"Rate limit error: {details}", exc_info=error)
    elif isinstance(error, APIConnectionError):
        logger.warning(f"API connection error: {details}", exc_info=error)
    elif isinstance(error, APIStatusError) and error.status_code >= 500:
        logger.error(f"API server error (5xx): {details}", exc_info=error)
    else:
        logger.error(f"API error: {details}", exc_info=error)
```

Code after:
            )
        else:
            logger.warning(f"LLM continuation returned empty response for {session_id}")

    except Exception as e:
        logger.error(f"Failed to generate LLM continuation: {e}", exc_info=True)


def _log_api_error(
    error: Exception,
    context: str,
    session_id: str | None = None,
    message_count: int | None = None,
    model: str | None = None,
    retry_count: int = 0,
) -> None:
    """Log detailed API error information for debugging."""
    details = _extract_api_error_details(error)
    details["context"] = context
    details["session_id"] = session_id
    details["message_count"] = message_count
    details["model"] = model
    details["retry_count"] = retry_count

    if isinstance(error, RateLimitError):
        logger.warning(f"Rate limit error in {context}: {details}", exc_info=error)
    elif isinstance(error, APIConnectionError):
        logger.warning(f"API connection error in {context}: {details}", exc_info=error)
    elif isinstance(error, APIStatusError) and error.status_code >= 500:
        logger.error(f"API server error (5xx) in {context}: {details}", exc_info=error)
    else:
        logger.error(f"API error in {context}: {details}", exc_info=error)


def _extract_api_error_details(error: Exception) -> dict[str, Any]:
    """Extract detailed information from OpenAI/OpenRouter API errors."""
    error_msg = str(error)
    details: dict[str, Any] = {
        "error_type": type(error).__name__,
        "error_message": error_msg[:500] + "..." if len(error_msg) > 500 else error_msg,
    }

    if hasattr(error, "code"):
        details["code"] = getattr(error, "code", None)
    if hasattr(error, "param"):
        details["param"] = getattr(error, "param", None)

    if isinstance(error, APIStatusError):
        details["status_code"] = error.status_code
        details["request_id"] = getattr(error, "request_id", None)