77 lines
2.7 KiB
Python
77 lines
2.7 KiB
Python
"""LLM 连通性诊断脚本。
|
||
直接运行:cd backend && python -m scripts.test_llm
|
||
不依赖 logging 配置,所有输出直接 print。
|
||
"""
|
||
import json
|
||
import sys
|
||
from urllib import request, error
|
||
|
||
from app.core.config import get_settings
|
||
|
||
settings = get_settings()
|
||
|
||
api_key = settings.llm_parse_api_key or settings.aliyun_ai_access_key_id
|
||
api_url = settings.llm_parse_api_url
|
||
model = settings.llm_parse_model
|
||
|
||
print("=" * 60)
|
||
print("LLM 连通性诊断")
|
||
print("=" * 60)
|
||
print(f"API URL: {api_url}")
|
||
print(f"Model: {model}")
|
||
print(f"API Key: {api_key[:8]}...{api_key[-4:] if len(api_key) > 12 else '(太短或为空)'}")
|
||
print(f"Key 来源: {'llm_parse_api_key' if settings.llm_parse_api_key else 'aliyun_ai_access_key_id (fallback)'}")
|
||
print()
|
||
|
||
if not api_key or api_key == "xxx":
|
||
print("[FATAL] API Key 未配置或为默认值 'xxx'!")
|
||
print("请在 .env 中设置 LLM_PARSE_API_KEY=sk-xxxxx")
|
||
sys.exit(1)
|
||
|
||
payload = json.dumps({
|
||
"model": model,
|
||
"messages": [
|
||
{"role": "system", "content": "你是测试助手。只回复 JSON。"},
|
||
{"role": "user", "content": '请返回:{"status": "ok"}'},
|
||
],
|
||
"temperature": 0.1,
|
||
"max_tokens": 64,
|
||
}).encode("utf-8")
|
||
|
||
headers = {
|
||
"Content-Type": "application/json",
|
||
"Authorization": f"Bearer {api_key}",
|
||
}
|
||
|
||
print("正在发送测试请求到 DashScope...")
|
||
req = request.Request(url=api_url, data=payload, headers=headers, method="POST")
|
||
|
||
try:
|
||
with request.urlopen(req, timeout=15) as resp:
|
||
body = resp.read().decode("utf-8")
|
||
result = json.loads(body)
|
||
print(f"[OK] HTTP {resp.status}")
|
||
print(f"完整响应:\n{json.dumps(result, indent=2, ensure_ascii=False)}")
|
||
content = result.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||
print(f"\nLLM 回复内容: {content}")
|
||
print("\n[结论] LLM 连通正常!如果页面仍然失败,请检查服务器是否重启。")
|
||
except error.HTTPError as exc:
|
||
body = exc.read().decode("utf-8", errors="ignore")
|
||
print(f"[FAIL] HTTP {exc.code}")
|
||
print(f"错误响应: {body}")
|
||
if exc.code == 401:
|
||
print("\n[结论] API Key 无效!请检查 LLM_PARSE_API_KEY 是否正确。")
|
||
elif exc.code == 403:
|
||
print("\n[结论] API Key 权限不足!请检查 DashScope 账户状态。")
|
||
elif exc.code == 429:
|
||
print("\n[结论] 请求频率超限!稍后重试。")
|
||
else:
|
||
print(f"\n[结论] HTTP 错误 {exc.code},请检查 API 配置。")
|
||
except error.URLError as exc:
|
||
print(f"[FAIL] 网络错误: {exc.reason}")
|
||
print("\n[结论] 无法连接到 DashScope,请检查网络。")
|
||
except Exception as exc:
|
||
print(f"[FAIL] 未知错误: {type(exc).__name__}: {exc}")
|
||
import traceback
|
||
traceback.print_exc()
|