fix: 增强错误日志,修复API调用诊断
This commit is contained in:
@@ -232,7 +232,7 @@ class LLMService:
|
||||
temperature: float = 0.7
|
||||
) -> str:
|
||||
"""调用API"""
|
||||
url = f"{api_base}/chat/completions"
|
||||
url = f"{api_base.rstrip('/')}/chat/completions"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
@@ -244,13 +244,33 @@ class LLMService:
|
||||
"max_tokens": max_tokens
|
||||
}
|
||||
|
||||
# 打印请求详情(调试)
|
||||
logger.info(f"调用LLM: url={url}, model={model}")
|
||||
logger.info(f"消息数量: {len(messages)}, 第一条消息类型: {type(messages[0].get('content'))}")
|
||||
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
response = await client.post(url, headers=headers, json=payload)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return data['choices'][0]['message']['content']
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||
response = await client.post(url, headers=headers, json=payload)
|
||||
|
||||
# 检查HTTP状态
|
||||
if response.status_code != 200:
|
||||
logger.error(f"API返回错误: status={response.status_code}, body={response.text[:500]}")
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
|
||||
# 检查响应格式
|
||||
if 'choices' not in data or len(data['choices']) == 0:
|
||||
logger.error(f"API响应格式错误: {data}")
|
||||
raise ValueError("API响应格式错误:缺少choices")
|
||||
|
||||
return data['choices'][0]['message']['content']
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"HTTP错误: {e.response.status_code}, {e.response.text}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"API调用异常: {type(e).__name__}: {e}")
|
||||
raise
|
||||
|
||||
async def chat_stream(
|
||||
self,
|
||||
|
||||
Reference in New Issue
Block a user