(message, request=request, response=self) httpx.HTTPStatusError: Client error '4...

2026年01月26日 17:36 状态: processing

🚨 错误信息

Traceback (most recent call last): File "/app/backend/app/services/whisper_services.py", line 80, in transcribe_audio segments = _transcribe_large_file(audio_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/backend/app/services/whisper_services.py", line 193, in _transcribe_large_file chunk_segments = _transcribe_chunk( ^^^^^^^^^^^^^^^^^^ File "/app/backend/app/services/whisper_services.py", line 240, in _transcribe_chunk response.raise_for_status() File "/usr/local/lib/python3.11/site-packages/httpx/_models.py", line 758, in raise_for_status raise HTTPStatusError(message, request=request, response=self) httpx.HTTPStatusError: Client error '400 Bad Request' for url 'https://www.dmxapi.com/v1/chat/completions' For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400⁠ 2026-01-26 09:30:02 [ERROR] app.api.file_parser - Recording task 4a442843-4c85-4252-9ade-2cbc6937d8f4 failed: Client error '400 Bad Request' for url 'https://www.dmxapi.com/v1/chat/completions' For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400⁠ [2026-01-26 09:30:02,386: INFO/ForkPoolWorker-1] Task process_recording[4a442843-4c85-4252-9ade-2cbc6937d8f4] succeeded in 98.15312454500236s: 'Recording task 4a442843-4c85-4252-9ade-2cbc6937d8f4 completed'

🤖 AI解决方案

代码糕手 - 专业报错分析助理


``
原文:httpx.HTTPStatusError: Client error '400 Bad Request' for url 'https://www.dmxapi.com/v1/chat/completions'
译文:HTTP状态错误:客户端错误 '400 请求错误',针对 URL 'https://www.dmxapi.com/v1/chat/completions'
原因分析

这是一个 HTTP 客户端请求错误,根本原因是 向 DMXAPI 的 /v1/chat/completions 端点发送了无效请求。错误发生在:

  • 文件:/app/backend/app/services/whisper_services.py 第 240 行

  • 函数:_transcribe_chunk

  • 具体操作:调用 response.raise_for_status() 时发现 HTTP 状态码为 400
  • HTTP 400 错误表明服务器无法处理该请求,通常是因为:

  • 请求格式不正确(缺少必需参数、参数类型错误等)

  • 请求内容过大(音频片段可能超过API限制)

  • 认证信息错误(API密钥无效或过期)

  • API端点URL或 解决方案
  • 根据您的代码结构,需要检查并修复 _transcribe_chunk 函数中的请求参数:

    python

    检查 _transcribe_chunk 函数的HTTP请求部分


    import httpx

    async def _transcribe_chunk(chunk_data: bytes, api_key: str) -> dict:
    """
    修复建议:添加详细的错误日志和参数验证
    """
    headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json", # 确保正确的内容类型
    }

    # 验证请求体格式
    payload = {
    "model": "whisper-large", # 确认模型名称正确
    "audio": base64.b64encode(chunk_data).decode('utf-8'),
    # 添加其他必需参数
    }

    try:
    async with httpx.AsyncClient(timeout=60.0) as client:
    response = await client.post(
    "https://www.dmxapi.com/v1/chat/completions",
    headers=headers,
    json=payload # 使用json而不是data
    )

    # 记录详细的响应信息便于调试
    print(f"Request payload: {payload}")
    print(f"Response status: {response.status_code}")
    print(f"Response body: {response.text[:500]}") # 截取前500字符

    response.raise_for_status()
    return response.json()

    except httpx.HTTPStatusError as e:
    # 捕获并记录更详细的错误信息
    print(f"HTTP Error Details:")
    print(f" URL: {e.request.url}")
    print(f" Method: {e.request.method}")
    print(f" Headers: {dict(e.request.headers)}")
    print(f" Status Code: {e.response.status_code}")
    print(f" Response: {e.response.text}")
    raise️ 预防措施

  • 请求参数验证

  • python
    # 在发送请求前验证参数
    def validate_transcribe_request(payload: dict) -> bool:
    required_keys = ["model", "audio"]
    return all(key in payload for key in required_keys)

    2.使用详细的错误日志记录
    - 记录完整的请求和响应信息(注意脱敏API密钥)
    - 使用结构化日志格式,便于搜索和分析

  • 调用测试

  • python
    # 创建单元测试验证API调用
    import pytest

    @pytest.mark.asyncio
    async def test_transcribe_chunk_valid():
    """测试有效的API调用"""
    # 使用模拟的小音频数据进行测试

  • ⚙️ 配置合理的超时和重试机制

  • python
    # 在httpx客户端中添加重试逻辑
    from tenacity import retry, stop_after_attempt, wait_exponential

    @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
    async def transcribe_with_retry(chunk_data: bytes, api_key: str):
    # 实现带有重试的转录函数
    `

    建议立即检查:

  • API密钥是否有效且具有适当权限

  • 请求体格式是否符合DMXAPI文档要求

  • 音频数据大小是否在API限制范围内

  • API端点URL是否正确(确保不是 /v1/chat/completions` 而是正确的转录端点)