333 lines
13 KiB
Python
333 lines
13 KiB
Python
"""
|
||
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]}
|