From 0c4cc96106c17e90f357817b26cc01d7fc9cd30e Mon Sep 17 00:00:00 2001 From: hubian <908234780@qq.com> Date: Tue, 14 Apr 2026 09:28:28 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=A2=9E=E5=BC=BA=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E6=97=A5=E5=BF=97=EF=BC=8C=E4=BF=AE=E5=A4=8DAPI=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/llm_service.py | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/services/llm_service.py b/services/llm_service.py index 36d2b6b..76a20d6 100644 --- a/services/llm_service.py +++ b/services/llm_service.py @@ -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,