- 新增 POST /ai-optimize/preview 轻量预检(KEY→同步状态校验与正式分析一致),返回商品数与预计秒区间 - 点击即弹「共 N 个商品,预计约 X~Y 秒」;分析中按钮两行进度(已耗时每秒刷新 + 预计区间) - 同步后分析补一次预检;预检失败降级不阻断 - 估算基于实测 12 件 28~55s 线性外推,宁宽勿窄,120s 封顶 端到端实测:14 件商品 toast 29~74s、按钮倒计时、结果报告正常;测试数据已还原。
282 lines
12 KiB
Python
282 lines
12 KiB
Python
"""AI 一键优化建议:检测账号商品情况,给出需要优化的商品清单。
|
|
|
|
判定顺序:先查模型 KEY(账号级优先、系统级回退),再查该账号是否已同步商品;
|
|
两者任一缺失都返回明确状态码,由前端提示用户先配置 KEY / 先同步商品。
|
|
有 KEY 且有商品时,把已同步的商品数据交给模型逐件分析,返回需要优化的清单。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import re
|
|
from typing import Any, Callable, Dict, List, Optional
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from openai import OpenAI
|
|
from pydantic import BaseModel
|
|
|
|
logger = logging.getLogger("ai_optimize")
|
|
|
|
MAX_ITEMS = 60 # 交给模型的商品上限,超出截断
|
|
DESC_LIMIT = 300 # 单件描述送模型的字数上限
|
|
DEFAULT_UA = "codex_cli_rs/0.0.0 (Hermes Agent)"
|
|
|
|
|
|
class AiOptimizeRequest(BaseModel):
|
|
cookie_id: str
|
|
|
|
|
|
def _extract_json(text: str) -> Dict[str, Any]:
|
|
"""模型偶尔裹 ```json 围栏或前后带废话,取首个 { 到末个 } 再解析。"""
|
|
cleaned = (text or "").strip()
|
|
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned)
|
|
cleaned = re.sub(r"\s*```$", "", cleaned)
|
|
start = cleaned.find("{")
|
|
end = cleaned.rfind("}")
|
|
if start == -1 or end <= start:
|
|
raise ValueError("模型未返回可解析的 JSON")
|
|
return json.loads(cleaned[start:end + 1])
|
|
|
|
|
|
def _price_num(raw: Any) -> Optional[float]:
|
|
match = re.search(r"(\d+(?:\.\d+)?)", str(raw or ""))
|
|
return float(match.group(1)) if match else None
|
|
|
|
|
|
def _brief(row: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""item_info 行 → 送模型的精简商品数据。"""
|
|
detail = row.get("item_detail_parsed") or {}
|
|
pics = ((detail.get("picInfo") or {}).get("picUrls")) or []
|
|
desc = (row.get("item_description") or "").strip()
|
|
return {
|
|
"item_id": str(row.get("item_id") or ""),
|
|
"title": (row.get("item_title") or "").strip()[:120],
|
|
"price": _price_num(row.get("item_price")),
|
|
"category": row.get("item_category") or "",
|
|
"description": desc[:DESC_LIMIT],
|
|
"image_count": len(pics) if pics else (1 if row.get("item_image") else 0),
|
|
"listing_status": row.get("listing_status") or "",
|
|
"updated_at": str(row.get("updated_at") or ""),
|
|
}
|
|
|
|
|
|
def _stats(briefs: List[Dict[str, Any]]) -> Dict[str, Any]:
|
|
prices = [b["price"] for b in briefs if b.get("price") is not None]
|
|
return {
|
|
"total": len(briefs),
|
|
"on_sale": sum(1 for b in briefs if b.get("listing_status") == "on_sale"),
|
|
"off_shelf": sum(1 for b in briefs if b.get("listing_status") not in ("", "on_sale")),
|
|
"no_desc": sum(1 for b in briefs if not b.get("description")),
|
|
"avg_price": round(sum(prices) / len(prices), 2) if prices else None,
|
|
}
|
|
|
|
|
|
SYSTEM_PROMPT = (
|
|
"你是闲鱼店铺运营优化专家,擅长商品标题、价格、描述与图片的优化。"
|
|
"你只输出 JSON,不输出任何其他文字。"
|
|
)
|
|
|
|
USER_TEMPLATE = """分析下面闲鱼账号的商品数据,找出需要优化的商品。
|
|
|
|
商品数据(JSON):
|
|
{payload}
|
|
|
|
只输出合法 JSON(双引号、单行字符串、无尾随逗号、无代码块标记):
|
|
{{"summary":"整体情况80字内","items":[{{"item_id":"商品ID","title":"标题原文","score":0到100整数,"priority":"high|medium|low","issues":["问题,40字内"],"suggestions":["做法,40字内"]}}]}}
|
|
|
|
规则:
|
|
- 只返回需要优化的商品,最多 12 件,score 升序
|
|
- 每件最多 2 条 issues、2 条 suggestions
|
|
- 没问题的商品不要返回
|
|
- priority: score<60 high, 60-79 medium, >=80 low
|
|
"""
|
|
|
|
|
|
def create_ai_optimize_router(
|
|
get_current_user: Callable[..., dict[str, Any]],
|
|
db_manager: Any,
|
|
) -> APIRouter:
|
|
router = APIRouter()
|
|
|
|
def require_account(cookie_id: str, current_user: dict[str, Any]) -> dict[str, Any]:
|
|
details = db_manager.get_cookie_details(cookie_id)
|
|
if not details or details.get("user_id") != current_user["user_id"]:
|
|
raise HTTPException(status_code=403, detail="无权限操作该账号")
|
|
return details
|
|
|
|
@router.post("/ai-optimize/preview")
|
|
def ai_optimize_preview(
|
|
req: AiOptimizeRequest,
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
):
|
|
"""轻量预检:返回该账号商品数与预计分析耗时,供前端点击后立刻展示给用户。
|
|
|
|
校验顺序与 suggest 一致(模型 KEY → 商品同步状态),保证提示口径统一。
|
|
"""
|
|
require_account(req.cookie_id, current_user)
|
|
|
|
settings = db_manager.get_ai_reply_settings(req.cookie_id)
|
|
if not (settings.get("api_key") or "").strip():
|
|
return {
|
|
"status": "need_api_key",
|
|
"message": "尚未配置模型 KEY,请先在 AI 设置中填写模型 KEY 再执行优化建议。",
|
|
}
|
|
|
|
rows = db_manager.get_items_by_cookie(req.cookie_id) or []
|
|
if not rows:
|
|
return {
|
|
"status": "need_sync",
|
|
"message": "该账号还没有同步商品,需要先同步商品才能执行优化分析。",
|
|
}
|
|
|
|
total = len(rows)
|
|
analyzed = min(total, MAX_ITEMS)
|
|
# 实测基准:12 件约 28~55 秒(一次批量模型调用,单次 130s 超时)。
|
|
# 输入商品越多 prompt 越长,线性外推;区间宁宽勿窄,120s 在超时线内封顶。
|
|
est_min = int(min(8 + 1.5 * analyzed, 60))
|
|
est_max = int(min(25 + 3.5 * analyzed, 120))
|
|
return {
|
|
"status": "ok",
|
|
"total": total,
|
|
"analyzed_count": analyzed,
|
|
"truncated": total > MAX_ITEMS,
|
|
"est_min_seconds": est_min,
|
|
"est_max_seconds": est_max,
|
|
}
|
|
|
|
@router.post("/ai-optimize/suggest")
|
|
def ai_optimize_suggest(
|
|
req: AiOptimizeRequest,
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
):
|
|
"""检测该账号商品并给出优化建议;KEY 未配 / 未同步商品时返回状态由前端引导。"""
|
|
require_account(req.cookie_id, current_user)
|
|
|
|
# 1) 模型 KEY:账号级优先、系统级回退(get_ai_reply_settings 已内置回退)
|
|
settings = db_manager.get_ai_reply_settings(req.cookie_id)
|
|
api_key = (settings.get("api_key") or "").strip()
|
|
if not api_key:
|
|
return {
|
|
"status": "need_api_key",
|
|
"message": "尚未配置模型 KEY,请先在 AI 设置中填写模型 KEY 再执行优化建议。",
|
|
}
|
|
|
|
# 2) 商品是否已同步
|
|
rows = db_manager.get_items_by_cookie(req.cookie_id) or []
|
|
if not rows:
|
|
return {
|
|
"status": "need_sync",
|
|
"message": "该账号还没有同步商品,需要先同步商品才能执行优化分析。",
|
|
}
|
|
|
|
briefs = [_brief(r) for r in rows]
|
|
stats = _stats(briefs)
|
|
truncated = len(briefs) > MAX_ITEMS
|
|
payload_items = briefs[:MAX_ITEMS]
|
|
|
|
# 3) 交给模型逐件分析。
|
|
# 实测坑:mimo 推理模型输出长 JSON 会撞网关 ~150s 504,且思考长度方差大(36s~150s+)。
|
|
# 对策:①提示词收紧输出(12件/2条/40字)②首选 enable_thinking=false 关思考
|
|
# ③单次超时 130s(低于网关线)④失败重试一次(第二次退回不带关思考参数,
|
|
# 兼容不认该参数的上游)。三种配置实测 28~55s 内 finish=stop 且 JSON 合法。
|
|
model_name = (settings.get("model_name") or "").strip() or "qwen-plus"
|
|
messages = [
|
|
{"role": "system", "content": SYSTEM_PROMPT},
|
|
{
|
|
"role": "user",
|
|
"content": USER_TEMPLATE.format(
|
|
payload=json.dumps(payload_items, ensure_ascii=False)
|
|
),
|
|
},
|
|
]
|
|
# 第一发关思考(快),第二发退回默认参数(兼容不认 enable_thinking 的上游)
|
|
attempt_extras = [{"enable_thinking": False}, {}]
|
|
|
|
content = ""
|
|
parsed: Optional[Dict[str, Any]] = None
|
|
last_err: Optional[Exception] = None
|
|
for attempt, extra in enumerate(attempt_extras):
|
|
try:
|
|
client = OpenAI(
|
|
api_key=api_key,
|
|
base_url=(settings.get("base_url") or "").strip() or None,
|
|
timeout=130.0,
|
|
max_retries=0,
|
|
default_headers={"User-Agent": settings.get("user_agent") or DEFAULT_UA},
|
|
)
|
|
response = client.chat.completions.create(
|
|
model=model_name,
|
|
messages=messages,
|
|
temperature=0.4,
|
|
max_tokens=6000,
|
|
extra_body=extra or None,
|
|
)
|
|
content = (
|
|
(response.choices[0].message.content or "")
|
|
if response.choices else ""
|
|
)
|
|
parsed = _extract_json(content)
|
|
break
|
|
except (ValueError, json.JSONDecodeError) as exc:
|
|
# JSON 被截断/格式坏 → 带上原输出重试一次
|
|
last_err = exc
|
|
logger.warning(f"AI优化建议 JSON 解析失败(第 {attempt + 1} 次):{exc}")
|
|
messages = [
|
|
messages[0],
|
|
{
|
|
"role": "user",
|
|
"content": messages[1]["content"]
|
|
+ f"\n\n你上次输出的 JSON 解析失败({exc}),请重新输出一次完整合法 JSON。",
|
|
},
|
|
]
|
|
except Exception as exc:
|
|
last_err = exc
|
|
logger.warning(f"AI优化建议模型调用失败(第 {attempt + 1} 次):{exc}")
|
|
if parsed is None:
|
|
raise HTTPException(
|
|
status_code=502,
|
|
detail=f"模型调用失败:{last_err}(已重试一次,请稍后再试)",
|
|
) from last_err
|
|
|
|
# 用本地数据补齐/校正模型回填的标题,排序按 score 升序
|
|
local_titles = {b["item_id"]: b["title"] for b in briefs}
|
|
items: List[Dict[str, Any]] = []
|
|
for raw in parsed.get("items") or []:
|
|
if not isinstance(raw, dict):
|
|
continue
|
|
item_id = str(raw.get("item_id") or "")
|
|
try:
|
|
score = int(raw.get("score"))
|
|
except (TypeError, ValueError):
|
|
score = 60
|
|
score = max(0, min(100, score))
|
|
priority = raw.get("priority")
|
|
if priority not in ("high", "medium", "low"):
|
|
priority = "high" if score < 60 else ("medium" if score < 80 else "low")
|
|
issues = [str(x) for x in (raw.get("issues") or []) if str(x).strip()]
|
|
suggestions = [str(x) for x in (raw.get("suggestions") or []) if str(x).strip()]
|
|
if not issues and not suggestions:
|
|
continue
|
|
items.append({
|
|
"item_id": item_id,
|
|
"title": local_titles.get(item_id) or str(raw.get("title") or "")[:120],
|
|
"score": score,
|
|
"priority": priority,
|
|
"issues": issues,
|
|
"suggestions": suggestions,
|
|
})
|
|
items.sort(key=lambda x: x["score"])
|
|
|
|
return {
|
|
"status": "ok",
|
|
"summary": str(parsed.get("summary") or "").strip(),
|
|
"items": items,
|
|
"stats": stats,
|
|
"analyzed_count": len(payload_items),
|
|
"truncated": truncated,
|
|
"model": model_name,
|
|
}
|
|
|
|
return router
|