(message, request=request, response=self) httpx.HTTPStatusError: Client error '4...
🚨 错误信息
🤖 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 端点发送了无效请求。错误发生在:
第 240 行 时发现 HTTP 状态码为 400HTTP 400 错误表明服务器无法处理该请求,通常是因为:
根据您的代码结构,需要检查并修复 _transcribe_chunk 函数中的请求参数:
python
检查 _transcribe_chunk 函数的HTTP请求部分
import httpxasync 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` 而是正确的转录端点)