AI提到后端
This commit is contained in:
+2
-1
@@ -14,7 +14,7 @@ from loguru import logger
|
||||
|
||||
from .config import settings
|
||||
from .database import engine
|
||||
from .routers import register, resumes, sessions, jobs, blacklist, rpa, templates
|
||||
from .routers import register, resumes, sessions, jobs, blacklist, rpa, templates, ai
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -51,6 +51,7 @@ app.include_router(jobs.router)
|
||||
app.include_router(blacklist.router)
|
||||
app.include_router(rpa.router)
|
||||
app.include_router(templates.router)
|
||||
app.include_router(ai.router)
|
||||
|
||||
|
||||
@app.get("/", tags=["健康检查"])
|
||||
|
||||
@@ -242,3 +242,59 @@ class ApplyTemplate(Base):
|
||||
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="templates")
|
||||
|
||||
|
||||
class AIConfig(Base):
|
||||
"""
|
||||
AI 模型配置(全局单行,id=1)
|
||||
OpenAI 兼容接口,由管理页面(/view)在线维护,
|
||||
客户端不再持有任何模型密钥。
|
||||
"""
|
||||
__tablename__ = "ai_config"
|
||||
|
||||
id = Column(Integer, primary_key=True, default=1)
|
||||
# OpenAI 兼容接口地址,如 https://api.siliconflow.cn/v1
|
||||
base_url = Column(String(255), nullable=True)
|
||||
api_key = Column(String(255), nullable=True)
|
||||
model = Column(String(128), nullable=True)
|
||||
# 服务端调用大模型的超时(秒)
|
||||
timeout_s = Column(Integer, default=300, nullable=False)
|
||||
# 是否启用 AI 代理(关闭后客户端评分请求直接返回未配置)
|
||||
enabled = Column(Boolean, default=True, nullable=False)
|
||||
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow)
|
||||
|
||||
|
||||
class AIScoreTask(Base):
|
||||
"""
|
||||
AI 打分任务(客户端异步评分)
|
||||
客户端发起打分 → 服务端后台调用大模型 → 结果落表 → 客户端轮询取结果。
|
||||
request_key 为客户端生成的幂等键(uuid1 hex,MAC+时间戳,32 位),
|
||||
重复提交同键直接返回已有任务,不会重复调用大模型。
|
||||
"""
|
||||
__tablename__ = "ai_score_task"
|
||||
__table_args__ = (
|
||||
# 同一用户内幂等键唯一(防重复调用大模型)
|
||||
UniqueConstraint("user_id", "request_key", name="uq_user_request_key"),
|
||||
Index("idx_user_created", "user_id", "created_at"),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
# 幂等键:客户端 uuid1().hex,32 位十六进制字符串,故 VARCHAR(32)
|
||||
request_key = Column(String(32), nullable=False)
|
||||
resume_id = Column(Integer, ForeignKey("resumes.id", ondelete="SET NULL"), nullable=True)
|
||||
# 客户端职位标识(Boss job_id,仅审计追踪用)
|
||||
job_ref = Column(String(64), nullable=True)
|
||||
# 职位 JD 全文(评分输入)
|
||||
jd_text = Column(Text, nullable=False)
|
||||
# 投递条件 JSON:keywords/city/salary_min/salary_max/prompt
|
||||
conditions = Column(Text, nullable=True)
|
||||
# pending / running / success / failed
|
||||
status = Column(String(20), default="pending", nullable=False)
|
||||
score = Column(Integer, nullable=True)
|
||||
# 成功时一句话评价;失败时失败原因(客户端据此跳岗)
|
||||
reason = Column(String(512), nullable=True)
|
||||
# 详细错误信息(调试用)
|
||||
error = Column(Text, nullable=True)
|
||||
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||
finished_at = Column(DateTime, nullable=True)
|
||||
|
||||
@@ -8,3 +8,4 @@ pydantic>=2.7.0
|
||||
pydantic-settings>=2.3.0
|
||||
python-jose[cryptography]>=3.3.0
|
||||
loguru>=0.7.2
|
||||
requests>=2.31.0
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
"""
|
||||
AI 代理路由:模型配置管理 + 异步打分任务 + 简历整理
|
||||
- 客户端发起打分(POST /api/ai/score/start)→ 服务端后台线程调用大模型 → 结果落表
|
||||
- 客户端轮询结果(GET /api/ai/score/result/{request_key}):
|
||||
成功返回 score+reason;失败返回 reason(客户端跳过该岗位);处理中则继续等待
|
||||
- request_key 为客户端生成的幂等键(本机 MAC+时间戳的 uuid1 hex,32 位),
|
||||
重复提交同键直接返回已有任务,绝不重复调用大模型
|
||||
- 模型配置(OpenAI 兼容)由 /view 管理页在线维护,客户端不持有任何密钥
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import requests
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from loguru import logger
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..auth import get_current_user
|
||||
from ..database import get_db, SessionLocal
|
||||
from ..models import AIConfig, AIScoreTask, Resume, User, utcnow
|
||||
from ..schemas import AIConfigIn, CleanResumeIn, ScoreStartIn
|
||||
|
||||
router = APIRouter(prefix="/api/ai", tags=["AI代理"])
|
||||
|
||||
# 简易限额:每用户每日允许发起的打分次数(内存计数,重启清零)
|
||||
DAILY_QUOTA = 2000
|
||||
# 处理中任务超过该时长仍无结果 → 判定失败(防悬空等待,5 分钟)
|
||||
TASK_TIMEOUT_S = 300
|
||||
|
||||
_quota_lock = threading.Lock()
|
||||
_quota: dict = {} # {(user_id, 北京日期): 已用次数}
|
||||
|
||||
_SCORE_SYSTEM_PROMPT = (
|
||||
"你是专业招聘顾问。根据职位描述(JD)和候选人简历,输出 JSON 评估结果,"
|
||||
"不要输出 JSON 以外的内容。\n"
|
||||
'格式:{"score": <0-100整数>, "reason": "<一句话评价>"}\n'
|
||||
"评分标准:80-100 高度匹配;60-79 基本匹配;40-59 部分匹配;0-39 不匹配。"
|
||||
)
|
||||
_CLEAN_SYSTEM_PROMPT = (
|
||||
"你是简历整理助手。将下面抓取的杂乱简历文本整理为清晰、结构化的纯文本简历,"
|
||||
"保留所有关键信息(姓名可省略,联系方式可保留),去除广告和无关内容。"
|
||||
"直接输出整理后的文本,不要加任何解释。"
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 工具函数
|
||||
# ------------------------------------------------------------------
|
||||
def _today_bj() -> str:
|
||||
"""北京日期(限额按天清零)"""
|
||||
return datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _quota_ok(user_id: int) -> bool:
|
||||
with _quota_lock:
|
||||
return _quota.get((user_id, _today_bj()), 0) < DAILY_QUOTA
|
||||
|
||||
|
||||
def _quota_inc(user_id: int) -> None:
|
||||
with _quota_lock:
|
||||
key = (user_id, _today_bj())
|
||||
_quota[key] = _quota.get(key, 0) + 1
|
||||
|
||||
|
||||
def _get_config(db: Session) -> AIConfig | None:
|
||||
return db.query(AIConfig).filter(AIConfig.id == 1).first()
|
||||
|
||||
|
||||
def _llm_chat(cfg: AIConfig, system: str, user_text: str,
|
||||
max_tokens: int, temperature: float) -> str:
|
||||
"""直接 HTTP 调用 OpenAI 兼容 chat/completions(服务端不引入 openai SDK)"""
|
||||
url = (cfg.base_url or "").rstrip("/") + "/chat/completions"
|
||||
messages = []
|
||||
if system:
|
||||
messages.append({"role": "system", "content": system})
|
||||
messages.append({"role": "user", "content": user_text})
|
||||
resp = requests.post(
|
||||
url,
|
||||
headers={"Authorization": f"Bearer {cfg.api_key}"},
|
||||
json={"model": cfg.model, "messages": messages,
|
||||
"temperature": temperature, "max_tokens": max_tokens},
|
||||
timeout=cfg.timeout_s or 300,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return (data["choices"][0]["message"]["content"] or "").strip()
|
||||
|
||||
|
||||
def parse_score(raw: str) -> tuple[int, str]:
|
||||
"""解析模型返回的评分 JSON(纯函数,便于单测)"""
|
||||
raw = (raw or "").strip()
|
||||
if raw.startswith("```"):
|
||||
raw = raw.split("```")[1]
|
||||
if raw.startswith("json"):
|
||||
raw = raw[4:]
|
||||
data = json.loads(raw)
|
||||
return int(data.get("score", 50)), str(data.get("reason", ""))[:500]
|
||||
|
||||
|
||||
def build_score_user_prompt(jd_text: str, resume_content: str,
|
||||
conditions: dict | None) -> str:
|
||||
"""拼装评分用户提示词(纯函数,便于单测)"""
|
||||
user_prompt = f"【职位描述】\n{jd_text}\n\n【候选人简历】\n{resume_content}"
|
||||
conds = []
|
||||
if conditions:
|
||||
if conditions.get("keywords"):
|
||||
conds.append(f"搜索关键词:{conditions['keywords']}")
|
||||
if conditions.get("city"):
|
||||
conds.append(f"目标城市:{conditions['city']}")
|
||||
if conditions.get("salary_min") or conditions.get("salary_max"):
|
||||
conds.append(f"期望薪资:{conditions.get('salary_min') or '?'}"
|
||||
f"-{conditions.get('salary_max') or '?'}K")
|
||||
if conds:
|
||||
user_prompt += "\n\n【本次投递条件】\n" + "\n".join(conds)
|
||||
if conditions and conditions.get("prompt"):
|
||||
user_prompt += f"\n\n【用户额外偏好/引导词】\n{conditions['prompt']}"
|
||||
return user_prompt
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 异步打分:开始 + 查询结果
|
||||
# ------------------------------------------------------------------
|
||||
@router.post("/score/start")
|
||||
def score_start(
|
||||
req: ScoreStartIn,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""开始打分任务(幂等:同 request_key 重复提交直接返回已有任务)"""
|
||||
task = db.query(AIScoreTask).filter(
|
||||
AIScoreTask.user_id == current_user.id,
|
||||
AIScoreTask.request_key == req.request_key,
|
||||
).first()
|
||||
if task:
|
||||
logger.debug(f"幂等命中,直接返回已有打分任务:{req.request_key}")
|
||||
return {"request_key": task.request_key, "status": task.status}
|
||||
|
||||
cfg = _get_config(db)
|
||||
if not cfg or not cfg.enabled or not cfg.api_key:
|
||||
raise HTTPException(status_code=400, detail="服务端未配置 AI 模型,请联系管理员")
|
||||
resume = db.query(Resume).filter(
|
||||
Resume.id == req.resume_id,
|
||||
Resume.user_id == current_user.id,
|
||||
).first()
|
||||
if not resume or not (resume.content or "").strip():
|
||||
raise HTTPException(status_code=404, detail="简历不存在或内容为空")
|
||||
if not _quota_ok(current_user.id):
|
||||
raise HTTPException(status_code=429, detail="今日 AI 打分次数已用完")
|
||||
|
||||
_quota_inc(current_user.id)
|
||||
conditions = req.conditions.model_dump() if req.conditions else {}
|
||||
task = AIScoreTask(
|
||||
user_id=current_user.id,
|
||||
request_key=req.request_key,
|
||||
resume_id=resume.id,
|
||||
job_ref=req.job_ref,
|
||||
jd_text=req.jd_text,
|
||||
conditions=json.dumps(conditions, ensure_ascii=False),
|
||||
status="pending",
|
||||
)
|
||||
db.add(task)
|
||||
db.commit()
|
||||
db.refresh(task)
|
||||
|
||||
threading.Thread(target=_run_score_task, args=(task.id,), daemon=True).start()
|
||||
logger.info(f"AI 打分任务已受理:task={task.id} user={current_user.id} "
|
||||
f"job_ref={req.job_ref}")
|
||||
return {"request_key": task.request_key, "status": task.status}
|
||||
|
||||
|
||||
def _run_score_task(task_id: int) -> None:
|
||||
"""后台执行打分:独立 DB 会话,成功/失败结果一律落表"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
task = db.query(AIScoreTask).filter(AIScoreTask.id == task_id).first()
|
||||
if not task:
|
||||
return
|
||||
task.status = "running"
|
||||
db.commit()
|
||||
|
||||
cfg = _get_config(db)
|
||||
if not cfg or not cfg.api_key:
|
||||
raise RuntimeError("AI 模型配置缺失或已停用")
|
||||
resume = (db.query(Resume).filter(Resume.id == task.resume_id).first()
|
||||
if task.resume_id else None)
|
||||
resume_content = ((resume.content if resume else "") or "")
|
||||
|
||||
try:
|
||||
conditions = json.loads(task.conditions or "{}")
|
||||
except Exception:
|
||||
conditions = {}
|
||||
|
||||
user_prompt = build_score_user_prompt(task.jd_text, resume_content, conditions)
|
||||
raw = _llm_chat(cfg, _SCORE_SYSTEM_PROMPT, user_prompt,
|
||||
max_tokens=256, temperature=0.2)
|
||||
score, reason = parse_score(raw)
|
||||
|
||||
task.status = "success"
|
||||
task.score = score
|
||||
task.reason = reason
|
||||
task.finished_at = utcnow()
|
||||
db.commit()
|
||||
logger.success(f"AI 打分完成:task={task_id} score={score}")
|
||||
except Exception as e:
|
||||
logger.error(f"AI 打分任务失败 task={task_id}:{e}")
|
||||
try:
|
||||
db.rollback()
|
||||
task = db.query(AIScoreTask).filter(AIScoreTask.id == task_id).first()
|
||||
if task and task.status in ("pending", "running"):
|
||||
task.status = "failed"
|
||||
task.reason = f"模型调用失败:{str(e)[:200]}"
|
||||
task.error = str(e)[:2000]
|
||||
task.finished_at = utcnow()
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.get("/score/result/{request_key}")
|
||||
def score_result(
|
||||
request_key: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""查询打分结果(客户端轮询)
|
||||
status:pending/running=处理中(客户端继续等待下一次轮询);
|
||||
success=返回 score+reason;failed=返回 reason(客户端跳过该岗位)。
|
||||
处理中的任务若超 5 分钟仍无结果,判定为失败(防悬空)。
|
||||
"""
|
||||
task = db.query(AIScoreTask).filter(
|
||||
AIScoreTask.user_id == current_user.id,
|
||||
AIScoreTask.request_key == request_key,
|
||||
).first()
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="打分任务不存在")
|
||||
if task.status in ("pending", "running") and \
|
||||
(utcnow() - task.created_at).total_seconds() > TASK_TIMEOUT_S:
|
||||
task.status = "failed"
|
||||
task.reason = "打分超时(超过 5 分钟无结果)"
|
||||
task.finished_at = utcnow()
|
||||
db.commit()
|
||||
return {"status": task.status, "score": task.score, "reason": task.reason}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 简历整理(低频同步调用,简历抓取时用)
|
||||
# ------------------------------------------------------------------
|
||||
@router.post("/clean-resume")
|
||||
def clean_resume(
|
||||
req: CleanResumeIn,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
cfg = _get_config(db)
|
||||
if not cfg or not cfg.enabled or not cfg.api_key:
|
||||
raise HTTPException(status_code=400, detail="服务端未配置 AI 模型")
|
||||
try:
|
||||
text = _llm_chat(cfg, _CLEAN_SYSTEM_PROMPT, req.raw_text,
|
||||
max_tokens=2048, temperature=0.3)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=502, detail=f"AI 整理失败:{str(e)[:200]}")
|
||||
return {"content": text}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 模型配置(管理页面在线维护)
|
||||
# ------------------------------------------------------------------
|
||||
def _config_out(cfg: AIConfig, with_key: bool) -> dict:
|
||||
return {
|
||||
"base_url": cfg.base_url or "",
|
||||
"api_key": cfg.api_key if with_key else "",
|
||||
"model": cfg.model or "",
|
||||
"timeout_s": cfg.timeout_s,
|
||||
"enabled": cfg.enabled,
|
||||
"updated_at": cfg.updated_at,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/config")
|
||||
def get_ai_config(
|
||||
with_key: bool = False,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""获取模型配置(默认不回显密钥;编辑时带 with_key=true 回显)"""
|
||||
cfg = _get_config(db)
|
||||
if not cfg:
|
||||
return {"base_url": "", "api_key": "", "model": "",
|
||||
"timeout_s": 300, "enabled": False, "updated_at": None}
|
||||
return _config_out(cfg, with_key=with_key)
|
||||
|
||||
|
||||
@router.put("/config")
|
||||
def save_ai_config(
|
||||
req: AIConfigIn,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""保存模型配置(OpenAI 兼容接口)"""
|
||||
cfg = _get_config(db)
|
||||
if not cfg:
|
||||
cfg = AIConfig(id=1)
|
||||
db.add(cfg)
|
||||
cfg.base_url = (req.base_url or "").strip()
|
||||
cfg.api_key = (req.api_key or "").strip()
|
||||
cfg.model = (req.model or "").strip()
|
||||
cfg.timeout_s = req.timeout_s
|
||||
cfg.enabled = req.enabled
|
||||
db.commit()
|
||||
db.refresh(cfg)
|
||||
logger.info(f"AI 模型配置已更新(by user {current_user.id}):"
|
||||
f"{cfg.base_url} / {cfg.model} / enabled={cfg.enabled}")
|
||||
return _config_out(cfg, with_key=False)
|
||||
|
||||
|
||||
@router.post("/config/test")
|
||||
def test_ai_config(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""连通测试:用当前已保存配置发起一次最小请求"""
|
||||
cfg = _get_config(db)
|
||||
if not cfg or not cfg.api_key:
|
||||
return {"ok": False, "detail": "尚未配置 API Key"}
|
||||
try:
|
||||
_llm_chat(cfg, "", "回复1", max_tokens=5, temperature=0)
|
||||
return {"ok": True, "detail": "连通正常"}
|
||||
except Exception as e:
|
||||
return {"ok": False, "detail": str(e)[:300]}
|
||||
@@ -239,6 +239,43 @@ class Message(BaseModel):
|
||||
msg: str
|
||||
|
||||
|
||||
# =======================================================
|
||||
# AI 代理(异步打分 + 模型配置)
|
||||
# =======================================================
|
||||
class ScoreConditions(BaseModel):
|
||||
"""本次投递所用条件(客户端每次随打分请求上送)"""
|
||||
keywords: Optional[str] = None
|
||||
city: Optional[str] = None
|
||||
salary_min: Optional[int] = None
|
||||
salary_max: Optional[int] = None
|
||||
# AI 评分引导词(用户自定义额外偏好)
|
||||
prompt: Optional[str] = None
|
||||
|
||||
|
||||
class ScoreStartIn(BaseModel):
|
||||
# 幂等键:客户端用本机 MAC+时间戳生成的 uuid1 hex(32 位十六进制)
|
||||
request_key: str = Field(..., min_length=32, max_length=32,
|
||||
pattern=r"^[0-9a-fA-F]{32}$",
|
||||
description="uuid1().hex,32 位十六进制")
|
||||
resume_id: int = Field(..., description="主简历 ID,服务端从库中取内容")
|
||||
jd_text: str = Field(..., min_length=1, description="职位 JD 全文")
|
||||
job_ref: Optional[str] = Field(None, max_length=64, description="Boss 职位 ID(审计用)")
|
||||
conditions: Optional[ScoreConditions] = None
|
||||
|
||||
|
||||
class CleanResumeIn(BaseModel):
|
||||
raw_text: str = Field(..., min_length=1, description="抓取到的原始简历文本")
|
||||
|
||||
|
||||
class AIConfigIn(BaseModel):
|
||||
"""模型配置(OpenAI 兼容接口,/view 管理页维护)"""
|
||||
base_url: str = Field("", max_length=255, description="如 https://api.siliconflow.cn/v1")
|
||||
api_key: str = Field("", max_length=255)
|
||||
model: str = Field("", max_length=128)
|
||||
timeout_s: int = Field(300, ge=10, le=600, description="服务端调用大模型超时(秒)")
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class StatsOut(BaseModel):
|
||||
total_applied: int
|
||||
total_chat: int
|
||||
|
||||
+59
-1
@@ -112,6 +112,7 @@
|
||||
<div class="menu-item active" data-page="data">投递数据</div>
|
||||
<div class="menu-item" data-page="blacklist">公司黑名单</div>
|
||||
<div class="menu-item" data-page="remote">远程控制</div>
|
||||
<div class="menu-item" data-page="aiConfig">模型配置</div>
|
||||
</aside>
|
||||
|
||||
<!-- 右侧内容 -->
|
||||
@@ -244,6 +245,25 @@
|
||||
</table>
|
||||
<div class="empty hidden" id="taskEmpty">暂无远程任务</div>
|
||||
</div>
|
||||
|
||||
<!-- 模型配置(AI 代理:客户端评分统一经服务端转发) -->
|
||||
<div id="pageAiConfig" class="hidden">
|
||||
<div class="bl-tip">客户端的 AI 评分/简历整理统一由服务端代理调用大模型(OpenAI 兼容接口),客户端不再保存任何模型密钥。</div>
|
||||
<div class="bl-add" style="flex-wrap:wrap;align-items:flex-end;">
|
||||
<div style="flex:2;min-width:260px;"><label style="font-size:12px;color:#666;">Base URL(OpenAI 兼容)</label>
|
||||
<input type="text" id="aiBaseUrl" placeholder="如:https://api.siliconflow.cn/v1" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||
<div style="flex:2;min-width:260px;"><label style="font-size:12px;color:#666;">API Key</label>
|
||||
<input type="text" id="aiApiKey" placeholder="sk-..." style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||
<div style="min-width:220px;"><label style="font-size:12px;color:#666;">模型名</label>
|
||||
<input type="text" id="aiModel" placeholder="如:deepseek-ai/DeepSeek-V3" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||
<div style="width:150px;"><label style="font-size:12px;color:#666;">调用超时(秒,10-600)</label>
|
||||
<input type="number" id="aiTimeout" value="300" min="10" max="600" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||
<label style="display:flex;align-items:center;gap:4px;font-size:13px;padding-bottom:10px;"><input type="checkbox" id="aiEnabled" checked> 启用 AI 代理</label>
|
||||
<button id="btnAiSave" style="background:#1890ff;">保存配置</button>
|
||||
<button id="btnAiTest">连通测试</button>
|
||||
</div>
|
||||
<div class="bl-tip" id="aiConfigTip">更新时间:-</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -445,6 +465,40 @@ async function sendTask(taskType, params) {
|
||||
} catch (e) { alert('下发失败:' + (e.message || '')); }
|
||||
}
|
||||
|
||||
/* ---------- 模型配置(AI 代理) ---------- */
|
||||
async function loadAiConfig() {
|
||||
try {
|
||||
const d = await api('/api/ai/config?with_key=true');
|
||||
document.getElementById('aiBaseUrl').value = d.base_url || '';
|
||||
document.getElementById('aiApiKey').value = d.api_key || '';
|
||||
document.getElementById('aiModel').value = d.model || '';
|
||||
document.getElementById('aiTimeout').value = d.timeout_s || 300;
|
||||
document.getElementById('aiEnabled').checked = !!d.enabled;
|
||||
document.getElementById('aiConfigTip').textContent = '更新时间:' + (d.updated_at || '-');
|
||||
} catch (e) { /* 401 已在 api 内处理 */ }
|
||||
}
|
||||
|
||||
async function saveAiConfig() {
|
||||
try {
|
||||
await api('/api/ai/config', { method: 'PUT', body: JSON.stringify({
|
||||
base_url: document.getElementById('aiBaseUrl').value.trim(),
|
||||
api_key: document.getElementById('aiApiKey').value.trim(),
|
||||
model: document.getElementById('aiModel').value.trim(),
|
||||
timeout_s: parseInt(document.getElementById('aiTimeout').value, 10) || 300,
|
||||
enabled: document.getElementById('aiEnabled').checked,
|
||||
})});
|
||||
alert('模型配置已保存');
|
||||
await loadAiConfig();
|
||||
} catch (e) { alert('保存失败:' + (e.message || '')); }
|
||||
}
|
||||
|
||||
async function testAiConfig() {
|
||||
try {
|
||||
const d = await api('/api/ai/config/test', { method: 'POST' });
|
||||
alert(d.ok ? '连通测试通过' : '连通失败:' + d.detail);
|
||||
} catch (e) { alert('测试失败:' + (e.message || '')); }
|
||||
}
|
||||
|
||||
/* ---------- 页面切换 ---------- */
|
||||
function switchPage(page) {
|
||||
document.querySelectorAll('aside .menu-item').forEach(el =>
|
||||
@@ -452,7 +506,9 @@ function switchPage(page) {
|
||||
document.getElementById('pageData').classList.toggle('hidden', page !== 'data');
|
||||
document.getElementById('pageBlacklist').classList.toggle('hidden', page !== 'blacklist');
|
||||
document.getElementById('pageRemote').classList.toggle('hidden', page !== 'remote');
|
||||
if (page === 'data') load(); else if (page === 'blacklist') loadBlacklist(); else loadRemote();
|
||||
document.getElementById('pageAiConfig').classList.toggle('hidden', page !== 'aiConfig');
|
||||
if (page === 'data') load(); else if (page === 'blacklist') loadBlacklist();
|
||||
else if (page === 'aiConfig') loadAiConfig(); else loadRemote();
|
||||
}
|
||||
|
||||
/* ---------- 事件绑定 ---------- */
|
||||
@@ -525,6 +581,8 @@ document.getElementById('btnStopRemote').onclick = () => {
|
||||
if (!confirm('确认远程结束投递任务?')) return;
|
||||
sendTask('stop_apply', null);
|
||||
};
|
||||
document.getElementById('btnAiSave').onclick = saveAiConfig;
|
||||
document.getElementById('btnAiTest').onclick = testAiConfig;
|
||||
document.getElementById('blTbody').addEventListener('click', e => {
|
||||
const btn = e.target.closest('.bl-remove');
|
||||
if (btn) removeBlacklist(btn.dataset.id);
|
||||
|
||||
Reference in New Issue
Block a user