162 lines
6.2 KiB
Python
162 lines
6.2 KiB
Python
"""
|
||
backend/app/api/chat_turns.py
|
||
|
||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
|
||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import uuid
|
||
|
||
from flask import Response, g, request, stream_with_context
|
||
|
||
from app.core.decorators import require_agent_permission
|
||
from app.core.errors import AppError, ValidationError
|
||
from app.services.chat.turn_runtime import ChatTurnRuntime
|
||
|
||
|
||
def _parse_turn_body_and_files() -> tuple[dict, list]:
|
||
"""
|
||
解析 Chat Turn 请求体;multipart 时从 form 字段读取 JSON 与 files。
|
||
|
||
Returns:
|
||
(body, uploads) — uploads 为 Werkzeug FileStorage 列表,JSON 请求时为空。
|
||
"""
|
||
content_type = str(request.content_type or "")
|
||
if "multipart/form-data" in content_type:
|
||
input_raw = request.form.get("input") or "{}"
|
||
try:
|
||
input_data = json.loads(input_raw)
|
||
except json.JSONDecodeError as exc:
|
||
raise ValidationError("input must be valid JSON") from exc
|
||
context_raw = request.form.get("context") or "{}"
|
||
try:
|
||
context_data = json.loads(context_raw) if context_raw else {}
|
||
except json.JSONDecodeError as exc:
|
||
raise ValidationError("context must be valid JSON") from exc
|
||
agent_id = request.form.get("agent_id") or request.form.get("agentId")
|
||
conversation_id = request.form.get("conversation_id") or request.form.get("conversationId")
|
||
body: dict = {
|
||
"agent_id": agent_id,
|
||
"conversation_id": conversation_id,
|
||
"input": input_data if isinstance(input_data, dict) else {},
|
||
"context": context_data if isinstance(context_data, dict) else {},
|
||
}
|
||
uploads = request.files.getlist("files")
|
||
if not uploads:
|
||
single = request.files.get("file")
|
||
if single:
|
||
uploads = [single]
|
||
return body, uploads
|
||
|
||
body = request.get_json(silent=True) or {}
|
||
return body if isinstance(body, dict) else {}, []
|
||
|
||
|
||
def _stage_upload_files(uploads: list) -> list[dict]:
|
||
"""将 multipart 文件读入内存 staged 结构,供 handler 构造 FileStorage。"""
|
||
staged: list[dict] = []
|
||
for upload in uploads:
|
||
if upload is None:
|
||
continue
|
||
data = upload.read() or b""
|
||
if not data:
|
||
continue
|
||
staged.append({
|
||
"filename": str(getattr(upload, "filename", None) or "upload"),
|
||
"content_type": str(getattr(upload, "content_type", None) or ""),
|
||
"data": data,
|
||
})
|
||
return staged
|
||
|
||
|
||
def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||
"""
|
||
将 multipart 附件写入 Turn input.payload。
|
||
|
||
- shipping.create_batch_from_notices:预检 notice_items
|
||
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
|
||
"""
|
||
if not uploads:
|
||
return
|
||
input_block = body.get("input") if isinstance(body.get("input"), dict) else {}
|
||
action_type = str(input_block.get("action_type") or input_block.get("actionType") or "").strip()
|
||
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
|
||
payload = dict(payload)
|
||
|
||
if action_type == "shipping.create_batch_from_notices":
|
||
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
|
||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||
|
||
temp_request_id = uuid.uuid4().hex
|
||
try:
|
||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||
finally:
|
||
cleanup_temp_notice_uploads(temp_request_id)
|
||
if not notice_items:
|
||
raise ValidationError(
|
||
"all uploaded files failed extraction or contained no parseable text",
|
||
details={"file_summary": file_summary},
|
||
)
|
||
payload["notice_items"] = notice_items
|
||
payload["file_summary"] = file_summary
|
||
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
|
||
if conversation_id:
|
||
payload["conversation_id"] = conversation_id
|
||
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||
staged = _stage_upload_files(uploads)
|
||
if not staged:
|
||
raise ValidationError("file is required")
|
||
payload["_staged_files"] = staged
|
||
else:
|
||
return
|
||
|
||
input_block["payload"] = payload
|
||
input_block["type"] = input_block.get("type") or "upload_followup"
|
||
body["input"] = input_block
|
||
|
||
|
||
def register_chat_turn_routes(chat_bp) -> None:
|
||
"""将 Chat Turn 路由注册到 chat Blueprint。"""
|
||
|
||
@chat_bp.route('/turns/stream', methods=['POST'])
|
||
@require_agent_permission
|
||
def chat_turns_stream():
|
||
"""
|
||
统一 Chat Turn SSE 接口。
|
||
|
||
核心逻辑:解析 action/form_submit/upload_followup;multipart 时预检附件并注入 payload,
|
||
经 ChatTurnRuntime 路由至 action handler,返回 run.started / step.* / message.* / run.completed。
|
||
"""
|
||
user = getattr(g, 'current_user', None)
|
||
agent = getattr(g, 'current_agent', None)
|
||
if user is None or agent is None:
|
||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||
|
||
body, uploads = _parse_turn_body_and_files()
|
||
request_id = uuid.uuid4().hex[:12]
|
||
|
||
def relay_stream():
|
||
if uploads:
|
||
_inject_multipart_upload_payload(body, uploads)
|
||
yield from ChatTurnRuntime.stream(
|
||
user=user,
|
||
agent=agent,
|
||
body=body,
|
||
request_id=request_id,
|
||
)
|
||
|
||
return Response(
|
||
stream_with_context(relay_stream()),
|
||
mimetype='text/event-stream',
|
||
headers={
|
||
'Cache-Control': 'no-cache',
|
||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||
'Connection': 'keep-alive',
|
||
'X-Accel-Buffering': 'no',
|
||
},
|
||
)
|