feat: 增加会员服务与估价模版智能体
会员服务改为固定栏目,首页在线服务不再进入报告审核。估价模版智能体可多会话制作模版并下载,下载过程显示加载状态。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
55b5a87482
commit
2074a45681
63 files changed
+6428
-461
No files matched your search
@@ -0,0 +1,500 @@
|
||||
"""估价模版智能体。只为智能体管理员准备可下载的模版,不写入模版列表。"""
|
||||
|
||||
import json
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.deps import require_agent
|
||||
from app.db import get_db
|
||||
from app.models.agent_user import AgentActor, load_agent_actor, presented_credential_version
|
||||
from app.models.content import read_upload_limit
|
||||
from app.models.valuation import COACH_WELCOME, ValuationCoachMessage, ValuationCoachSession, ValuationFile, _now
|
||||
from app.services.dify_chat import DifyChatError, DifyNotConfigured, iter_dify_chat, upload_dify_file
|
||||
from app.services.storage import make_object_key, read_object, safe_filename, upload_object
|
||||
from app.services.template_coach import (
|
||||
Outline,
|
||||
build_template_file,
|
||||
finish_model_answer,
|
||||
parse_outline_block,
|
||||
plan_turn,
|
||||
summary,
|
||||
)
|
||||
from app.services.valuation import owned_files
|
||||
from app.services.valuation_context import ALLOWED_EXTENSIONS, IMAGE_EXTENSIONS, MAX_FILES, extract_excerpt, file_kind
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_agent)])
|
||||
|
||||
COACH_EXTENSIONS = ALLOWED_EXTENSIONS | {"pptx"}
|
||||
_CONTENT_TYPES = {
|
||||
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
"pdf": "application/pdf",
|
||||
"txt": "text/plain",
|
||||
"md": "text/markdown",
|
||||
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"xls": "application/vnd.ms-excel",
|
||||
"csv": "text/csv",
|
||||
"jpg": "image/jpeg",
|
||||
"jpeg": "image/jpeg",
|
||||
"png": "image/png",
|
||||
"webp": "image/webp",
|
||||
}
|
||||
|
||||
|
||||
class CoachMessageIn(BaseModel):
|
||||
query: str = Field(default="", max_length=2000)
|
||||
fileIds: list[int] = Field(default_factory=list, max_length=MAX_FILES)
|
||||
sessionId: int | None = None
|
||||
|
||||
|
||||
class SessionRename(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=40)
|
||||
|
||||
|
||||
def _actor(db: Session, principal: dict) -> AgentActor:
|
||||
try:
|
||||
return load_agent_actor(
|
||||
db,
|
||||
str(principal.get("sub") or ""),
|
||||
credential_version=presented_credential_version(principal),
|
||||
)
|
||||
except LookupError as exc:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
|
||||
|
||||
|
||||
def _require_manager(db: Session, principal: dict) -> AgentActor:
|
||||
actor = _actor(db, principal)
|
||||
if not actor.can_manage:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="仅管理员可制作模版")
|
||||
return actor
|
||||
|
||||
|
||||
def _sse(payload: dict) -> str:
|
||||
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def _read_limited(upload: UploadFile, limit: int) -> bytes:
|
||||
chunks = bytearray()
|
||||
while True:
|
||||
piece = upload.file.read(65536)
|
||||
if not piece:
|
||||
break
|
||||
if len(chunks) + len(piece) > limit:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件超过大小上限")
|
||||
chunks.extend(piece)
|
||||
return bytes(chunks)
|
||||
|
||||
|
||||
def _session_rows(db: Session, owner: str) -> list[ValuationCoachSession]:
|
||||
return list(
|
||||
db.scalars(
|
||||
select(ValuationCoachSession)
|
||||
.where(ValuationCoachSession.owner_key == owner)
|
||||
.order_by(ValuationCoachSession.updated_at.desc(), ValuationCoachSession.id.desc())
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _remember_title(db: Session, row: ValuationCoachSession) -> str:
|
||||
title = (row.title or "").strip() or "新会话"
|
||||
if title != "新会话":
|
||||
return title
|
||||
first = db.scalar(
|
||||
select(ValuationCoachMessage.content)
|
||||
.where(ValuationCoachMessage.session_id == row.id, ValuationCoachMessage.role == "user")
|
||||
.order_by(ValuationCoachMessage.created_at, ValuationCoachMessage.id)
|
||||
.limit(1)
|
||||
)
|
||||
text = (first or "").strip()
|
||||
if not text:
|
||||
row.title = "新会话"
|
||||
return row.title
|
||||
row.title = text[:22]
|
||||
return row.title
|
||||
|
||||
|
||||
def _session_payload(db: Session, row: ValuationCoachSession) -> dict:
|
||||
return {
|
||||
"id": row.id,
|
||||
"title": _remember_title(db, row),
|
||||
"updatedAt": row.updated_at.isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
|
||||
def _create_session(db: Session, owner: str) -> ValuationCoachSession:
|
||||
now = _now()
|
||||
row = ValuationCoachSession(owner_key=owner, title="新会话", created_at=now, updated_at=now)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
db.add(
|
||||
ValuationCoachMessage(
|
||||
session_id=row.id,
|
||||
role="assistant",
|
||||
content=COACH_WELCOME,
|
||||
thought="",
|
||||
attachments="[]",
|
||||
kind="chat",
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
def _session(db: Session, owner: str) -> ValuationCoachSession:
|
||||
rows = _session_rows(db, owner)
|
||||
if rows:
|
||||
return rows[0]
|
||||
return _create_session(db, owner)
|
||||
|
||||
|
||||
def _owned_session(db: Session, owner: str, session_id: int) -> ValuationCoachSession | None:
|
||||
row = db.get(ValuationCoachSession, session_id)
|
||||
if row is None or row.owner_key != owner:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def _messages(db: Session, session_id: int) -> list[dict]:
|
||||
rows = db.scalars(
|
||||
select(ValuationCoachMessage)
|
||||
.where(ValuationCoachMessage.session_id == session_id)
|
||||
.order_by(ValuationCoachMessage.created_at, ValuationCoachMessage.id)
|
||||
)
|
||||
return [_message_payload(row) for row in rows]
|
||||
|
||||
|
||||
def _message_payload(row: ValuationCoachMessage) -> dict:
|
||||
try:
|
||||
attachments = json.loads(row.attachments or "[]")
|
||||
except json.JSONDecodeError:
|
||||
attachments = []
|
||||
if not isinstance(attachments, list):
|
||||
attachments = []
|
||||
return {
|
||||
"id": row.id,
|
||||
"role": row.role,
|
||||
"content": row.content or "",
|
||||
"thought": row.thought or "",
|
||||
"attachments": [str(item) for item in attachments if str(item).strip()],
|
||||
"kind": row.kind or "chat",
|
||||
"draftFormat": row.draft_format if row.kind == "template" else "",
|
||||
"draftName": (row.draft_name or "").strip() if row.kind == "template" else "",
|
||||
"createdAt": row.created_at.isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
|
||||
def _stored_outline(session: ValuationCoachSession) -> Outline | None:
|
||||
if not (session.outline_text or "").strip():
|
||||
return None
|
||||
parsed = parse_outline_block(session.outline_text)
|
||||
if parsed is None or not parsed.sections:
|
||||
return None
|
||||
return parsed
|
||||
|
||||
|
||||
def _remember(session: ValuationCoachSession, outline: Outline | None, source_text: str) -> None:
|
||||
session.source_text = source_text or ""
|
||||
if outline is not None and not outline.sections:
|
||||
session.outline_name = ""
|
||||
session.outline_format = ""
|
||||
session.outline_text = ""
|
||||
elif outline and outline.sections:
|
||||
session.outline_name = outline.name[:80]
|
||||
session.outline_format = outline.format
|
||||
session.outline_text = outline.render()
|
||||
session.updated_at = _now()
|
||||
|
||||
|
||||
def _coach_state(db: Session, owner: str, session: ValuationCoachSession) -> dict:
|
||||
rows = _session_rows(db, owner)
|
||||
payloads = [_session_payload(db, row) for row in rows]
|
||||
db.commit()
|
||||
return {"sessionId": session.id, "sessions": payloads, "items": _messages(db, session.id)}
|
||||
|
||||
|
||||
@router.get("/template-coach")
|
||||
def open_coach(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _session(db, actor.key)
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.post("/template-coach/sessions", status_code=status.HTTP_201_CREATED)
|
||||
def new_coach_session(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _create_session(db, actor.key)
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.get("/template-coach/sessions/{session_id}")
|
||||
def open_coach_session(
|
||||
session_id: int,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _owned_session(db, actor.key, session_id)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.patch("/template-coach/sessions/{session_id}")
|
||||
def rename_coach_session(
|
||||
session_id: int,
|
||||
body: SessionRename,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _owned_session(db, actor.key, session_id)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
title = body.title.strip()[:40]
|
||||
if not title:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请填写会话名称")
|
||||
session.title = title
|
||||
session.updated_at = _now()
|
||||
db.commit()
|
||||
db.refresh(session)
|
||||
return _session_payload(db, session)
|
||||
|
||||
|
||||
@router.delete("/template-coach/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def remove_coach_session(
|
||||
session_id: int,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> None:
|
||||
actor = _require_manager(db, principal)
|
||||
session = _owned_session(db, actor.key, session_id)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
db.execute(delete(ValuationCoachMessage).where(ValuationCoachMessage.session_id == session.id))
|
||||
db.delete(session)
|
||||
db.commit()
|
||||
|
||||
|
||||
@router.post("/template-coach/reset")
|
||||
def reset_coach(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
|
||||
"""保留旧会话,另开一段新的。"""
|
||||
actor = _require_manager(db, principal)
|
||||
session = _create_session(db, actor.key)
|
||||
return _coach_state(db, actor.key, session)
|
||||
|
||||
|
||||
@router.post("/template-coach/files", status_code=status.HTTP_201_CREATED)
|
||||
def upload_coach_file(
|
||||
file: UploadFile = File(...),
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
actor = _require_manager(db, principal)
|
||||
filename = safe_filename(file.filename or "")
|
||||
extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
||||
if extension in {"doc", "ppt"}:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请另存为 docx 或 pptx 后再上传")
|
||||
if extension not in COACH_EXTENSIONS:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="不支持该文件类型")
|
||||
limit = read_upload_limit(db) or 10 * 1024 * 1024
|
||||
data = _read_limited(file, limit)
|
||||
if not data:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件是空的")
|
||||
content_type = _CONTENT_TYPES.get(extension, "application/octet-stream")
|
||||
object_key = make_object_key(filename)
|
||||
upload_object("private", object_key, data, content_type)
|
||||
row = ValuationFile(
|
||||
member_id=0,
|
||||
owner_key=actor.key,
|
||||
filename=filename,
|
||||
extension=extension,
|
||||
content_type=content_type,
|
||||
size=len(data),
|
||||
object_key=object_key,
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return {"id": row.id, "name": row.filename, "size": row.size}
|
||||
|
||||
|
||||
@router.post("/template-coach/messages")
|
||||
def coach_message(
|
||||
body: CoachMessageIn,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
actor = _require_manager(db, principal)
|
||||
if body.sessionId:
|
||||
session = _owned_session(db, actor.key, body.sessionId)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="会话不存在")
|
||||
else:
|
||||
session = _session(db, actor.key)
|
||||
query = body.query.strip()
|
||||
files = owned_files(db, actor.key, body.fileIds)
|
||||
if files is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
|
||||
if not query and not files:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请输入要求或上传附件")
|
||||
excerpts: list[tuple[str, str, str]] = []
|
||||
for item in files:
|
||||
try:
|
||||
content = read_object("private", item.object_key)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="附件读取失败") from exc
|
||||
excerpts.append((item.filename, item.extension, extract_excerpt(item.extension, content, limit=8000)))
|
||||
plan = plan_turn(
|
||||
message=query,
|
||||
outline=_stored_outline(session),
|
||||
source_text=session.source_text or "",
|
||||
excerpts=excerpts,
|
||||
)
|
||||
file_names = [item.filename for item in files]
|
||||
now = _now()
|
||||
title_source = query or (file_names[0] if file_names else "")
|
||||
if (session.title or "新会话") == "新会话" and title_source:
|
||||
session.title = title_source[:22]
|
||||
session.updated_at = now
|
||||
db.add(
|
||||
ValuationCoachMessage(
|
||||
session_id=session.id,
|
||||
role="user",
|
||||
content=query or "请结合附件整理模版。",
|
||||
thought="",
|
||||
attachments=json.dumps(file_names, ensure_ascii=False),
|
||||
kind="chat",
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
owner = actor.key
|
||||
session_id = session.id
|
||||
user_key = owner
|
||||
|
||||
def generate():
|
||||
reply = plan.reply
|
||||
outline = plan.outline
|
||||
thought = ""
|
||||
if plan.mode == "local":
|
||||
if reply:
|
||||
yield _sse({"type": "delta", "text": reply})
|
||||
else:
|
||||
reply, outline, thought = yield from _stream_model(plan, files, user_key)
|
||||
saved = _save_assistant(db, owner, session_id, plan.source_text, reply, outline, thought)
|
||||
if saved is None:
|
||||
yield _sse({"type": "error", "message": "提纲已整理,但没能保存,请稍后重试"})
|
||||
return
|
||||
yield _sse(
|
||||
{
|
||||
"type": "saved",
|
||||
"messageId": saved.id,
|
||||
"kind": saved.kind,
|
||||
"draftFormat": saved.draft_format if saved.kind == "template" else "",
|
||||
"draftName": saved.draft_name if saved.kind == "template" else "",
|
||||
}
|
||||
)
|
||||
|
||||
return StreamingResponse(generate(), media_type="text/event-stream")
|
||||
|
||||
|
||||
def _stream_model(plan, files: list[ValuationFile], user_key: str):
|
||||
dify_files = []
|
||||
raw: list[str] = []
|
||||
thought = ""
|
||||
try:
|
||||
for item in files:
|
||||
if item.extension not in IMAGE_EXTENSIONS and item.extension not in {"pdf", "docx", "pptx", "txt", "md"}:
|
||||
continue
|
||||
content = read_object("private", item.object_key)
|
||||
uploaded_id = upload_dify_file(
|
||||
filename=item.filename,
|
||||
content=content,
|
||||
content_type=item.content_type,
|
||||
user=user_key,
|
||||
)
|
||||
dify_files.append(
|
||||
{
|
||||
"type": file_kind(item.extension),
|
||||
"transfer_method": "local_file",
|
||||
"upload_file_id": uploaded_id,
|
||||
}
|
||||
)
|
||||
for event in iter_dify_chat(query=plan.prompt, conversation_id="", user=user_key, files=dify_files or None):
|
||||
if event["type"] == "delta":
|
||||
raw.append(event["text"])
|
||||
elif event["type"] == "replace":
|
||||
raw = [event["text"]]
|
||||
elif event["type"] == "thought" and event.get("text"):
|
||||
thought = event["text"]
|
||||
yield _sse({"type": "thought", "text": thought})
|
||||
except (DifyNotConfigured, DifyChatError):
|
||||
if plan.fallback and plan.fallback.sections:
|
||||
reply = summary(plan.fallback, lead="暂时连不上估价智能体,我按已有材料")
|
||||
yield _sse({"type": "replace", "text": reply})
|
||||
return reply, plan.fallback, thought
|
||||
reply = "暂时连不上估价智能体,没能整理出新提纲。可以换个说法,或上传 docx、pptx 后重试。"
|
||||
yield _sse({"type": "replace", "text": reply})
|
||||
return reply, None, thought
|
||||
reply, outline = finish_model_answer("".join(raw), fallback=plan.fallback)
|
||||
if reply:
|
||||
yield _sse({"type": "delta", "text": reply})
|
||||
return reply, outline if outline and outline.sections else None, thought
|
||||
|
||||
|
||||
def _save_assistant(db, owner: str, session_id: int, source_text: str, reply: str, outline: Outline | None, thought: str):
|
||||
session = _owned_session(db, owner, session_id)
|
||||
if session is None:
|
||||
return None
|
||||
try:
|
||||
_remember(session, outline, source_text)
|
||||
ready = outline is not None and bool(outline.sections)
|
||||
row = ValuationCoachMessage(
|
||||
session_id=session.id,
|
||||
role="assistant",
|
||||
content=reply or "没能整理出模版提纲。",
|
||||
thought=thought or "",
|
||||
attachments="[]",
|
||||
kind="template" if ready else "chat",
|
||||
draft_format=outline.format if ready else "",
|
||||
draft_name=outline.name[:80] if ready else "",
|
||||
outline=outline.render() if ready else "",
|
||||
created_at=_now(),
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
except Exception:
|
||||
db.rollback()
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/template-coach/messages/{message_id}/file")
|
||||
def download_coach_template(
|
||||
message_id: int,
|
||||
principal: dict = Depends(require_agent),
|
||||
db: Session = Depends(get_db),
|
||||
) -> Response:
|
||||
actor = _require_manager(db, principal)
|
||||
row = db.get(ValuationCoachMessage, message_id)
|
||||
session = _owned_session(db, actor.key, row.session_id) if row is not None else None
|
||||
if row is None or session is None or row.role != "assistant" or row.kind != "template":
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模版文件不存在")
|
||||
outline = parse_outline_block(row.outline or "")
|
||||
if outline is None or not outline.sections:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="模版文件不存在")
|
||||
content, media_type, filename = build_template_file(outline)
|
||||
return Response(
|
||||
content=content,
|
||||
media_type=media_type,
|
||||
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename)}"},
|
||||
)
|
||||
Reference in new issue
Block a user