From b0a8c6edb90b0e3646644ff7eead5971ec66e046 Mon Sep 17 00:00:00 2001 From: Yuuuu <1569752928@qq.com> Date: Sat, 21 Feb 2026 00:16:03 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20AI=20=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=20API=20=E5=90=AF=E5=8A=A8=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 pathlib.Path 导入 - 修复 OpenAICompatibleClient 延迟初始化 - 后端现在可以正常启动并响应配置请求 --- backend/app/main.py | 2 ++ backend/app/services/llm_client.py | 26 ++++++++++++++++++-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/backend/app/main.py b/backend/app/main.py index 52be530..66de186 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -5,8 +5,10 @@ from sqlalchemy.future import select from typing import List from pydantic import BaseModel from enum import Enum +from pathlib import Path import uuid import asyncio +import os from .database import get_db, engine, Base from .models import ContextNode, Experiment, Signal, SignalFeedback diff --git a/backend/app/services/llm_client.py b/backend/app/services/llm_client.py index 6fbf18a..72aa9e8 100644 --- a/backend/app/services/llm_client.py +++ b/backend/app/services/llm_client.py @@ -123,14 +123,24 @@ class OpenAICompatibleClient(LLMProvider): """OpenAI 兼容客户端 (适用于 DeepSeek, Qwen 等)""" def __init__(self, api_key: str, base_url: str, model: str): - if not api_key: - raise ValueError(f"请设置 {base_url} 的 API_KEY") self.model = model - self.client = httpx.Client( - base_url=base_url, - timeout=120.0, - headers={"Authorization": f"Bearer {api_key}"} - ) + self.base_url = base_url + self.api_key = api_key + # 延迟初始化客户端,在实际调用时才检查 API_KEY + self._client = None + + @property + def client(self): + """延迟初始化客户端""" + if self._client is None: + if not self.api_key: + raise ValueError(f"请设置 {self.base_url} 的 API_KEY") + self._client = httpx.Client( + base_url=self.base_url, + timeout=120.0, + headers={"Authorization": f"Bearer {self.api_key}"} + ) + return self._client def generate(self, prompt: str, **kwargs) -> str: response = self.client.post("/chat/completions", json={ @@ -154,7 +164,7 @@ class OpenAICompatibleClient(LLMProvider): def get_embedding(self, text: str) -> List[float]: # DeepSeek 不支持 embedding,使用替代方案或返回空 - if "deepseek" in self.client.base_url: + if "deepseek" in self.base_url: print("[WARNING] DeepSeek 不支持 embedding API,使用简化向量") # 简化方案:基于文本内容生成伪向量(实际使用时应该用其他服务) import hashlib