209 lines
8.4 KiB
Python
209 lines
8.4 KiB
Python
"""
|
|
backend/app/services/chat/turn_runtime.py
|
|
|
|
用途:平台统一 Chat Turn 执行器,编排 SSE 生命周期、session、ChatLog 与 action 路由。
|
|
依赖:action_registry、turn_events、session_service、log_service、turn_context、action_schema、db。
|
|
逻辑:api/chat/turns/stream 调用 ChatTurnRuntime.stream();业务 handler 只 yield TurnEvent。
|
|
失败路径先 db.session.rollback(),再 touch_chat_session,避免 handler 脏写被一并提交。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
import uuid
|
|
from typing import Any, Iterator
|
|
|
|
from flask import current_app
|
|
|
|
from app import db
|
|
from app.core.errors import AppError, ValidationError
|
|
from app.services.chat.action_registry import ensure_handlers_loaded, resolve_action_handler
|
|
from app.services.chat.action_schema import TurnEvent, TurnInput, parse_turn_refs_from_context
|
|
from app.services.chat.log_service import save_turn_chat_log
|
|
from app.services.chat.session_service import ensure_chat_session, touch_chat_session
|
|
from app.services.chat.turn_context import TurnContext
|
|
from app.services.chat.turn_events import (
|
|
emit_message_completed,
|
|
emit_run_completed,
|
|
emit_run_failed,
|
|
emit_run_started,
|
|
emit_session_created,
|
|
emit_turn_event,
|
|
)
|
|
|
|
|
|
def _parse_turn_input(raw: dict[str, Any] | None) -> TurnInput:
|
|
data = raw if isinstance(raw, dict) else {}
|
|
input_type = str(data.get("type") or data.get("input_type") or "").strip().lower()
|
|
if input_type not in ("text", "action", "form_submit", "upload_followup"):
|
|
raise ValidationError("input.type must be one of: text, action, form_submit, upload_followup")
|
|
display_text = str(data.get("display_text") or data.get("displayText") or "").strip()
|
|
action_type = str(data.get("action_type") or data.get("actionType") or "").strip() or None
|
|
text = str(data.get("text") or "").strip() or None
|
|
payload = data.get("payload") if isinstance(data.get("payload"), dict) else {}
|
|
if input_type in ("action", "form_submit", "upload_followup") and not display_text:
|
|
display_text = action_type or text or "操作"
|
|
if input_type == "text" and not display_text:
|
|
display_text = text or ""
|
|
return TurnInput(
|
|
type=input_type, # type: ignore[arg-type]
|
|
display_text=display_text,
|
|
action_type=action_type,
|
|
text=text,
|
|
payload=payload,
|
|
)
|
|
|
|
|
|
class ChatTurnRuntime:
|
|
"""平台 Chat Turn 执行器门面。"""
|
|
|
|
@staticmethod
|
|
def stream(
|
|
*,
|
|
user: Any,
|
|
agent: Any,
|
|
body: dict[str, Any],
|
|
request_id: str | None = None,
|
|
) -> Iterator[str]:
|
|
"""
|
|
执行单轮 Chat Turn 并以 SSE 事件流返回。
|
|
|
|
Args:
|
|
user: 当前用户代理(须含 id)。
|
|
agent: 当前 Agent 代理(须含 id、name)。
|
|
body: POST JSON 请求体。
|
|
request_id: 可选请求追踪 ID。
|
|
|
|
Yields:
|
|
SSE data 帧字符串。
|
|
"""
|
|
ensure_handlers_loaded()
|
|
started = time.perf_counter()
|
|
req_id = str(request_id or uuid.uuid4().hex[:12])
|
|
turn_input = _parse_turn_input(body.get("input") if isinstance(body.get("input"), dict) else body)
|
|
refs = parse_turn_refs_from_context(body.get("context") if isinstance(body.get("context"), dict) else None)
|
|
|
|
if turn_input.type == "text":
|
|
raise ValidationError("text turns are not migrated yet; use /api/chat/completions")
|
|
if turn_input.type not in ("action", "form_submit", "upload_followup"):
|
|
raise ValidationError(f"input type '{turn_input.type}' is not supported yet")
|
|
|
|
user_id = getattr(user, "id", None)
|
|
agent_id = getattr(agent, "id", None)
|
|
if user_id is None or agent_id is None:
|
|
raise ValidationError("Missing user or agent context")
|
|
|
|
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip() or None
|
|
session = ensure_chat_session(
|
|
user_id,
|
|
agent_id,
|
|
conversation_id,
|
|
title=turn_input.display_text,
|
|
status="running",
|
|
)
|
|
turn_id = uuid.uuid4().hex
|
|
run_id = turn_id
|
|
ctx = TurnContext(
|
|
turn_id=turn_id,
|
|
run_id=run_id,
|
|
session_id=session.session_id,
|
|
request_id=req_id,
|
|
user=user,
|
|
agent=agent,
|
|
input=turn_input,
|
|
refs=refs,
|
|
external_conversation_id=session.external_conversation_id,
|
|
)
|
|
|
|
yield emit_session_created(
|
|
conversation_id=session.session_id,
|
|
session_status=session.status,
|
|
provider_conversation_id=session.external_conversation_id,
|
|
)
|
|
yield emit_run_started(
|
|
run_id=run_id,
|
|
turn_id=turn_id,
|
|
conversation_id=session.session_id,
|
|
session_status=session.status,
|
|
)
|
|
|
|
assistant_content = ""
|
|
message_type: str | None = None
|
|
message_payload: dict[str, Any] | None = None
|
|
|
|
try:
|
|
handler = resolve_action_handler(ctx)
|
|
for event in handler.stream(ctx):
|
|
if not isinstance(event, TurnEvent):
|
|
continue
|
|
event_name = event.event
|
|
if event_name in ("step.started", "step.completed", "ui_state.updated"):
|
|
yield emit_turn_event(event, conversation_id=session.session_id)
|
|
elif event_name == "message.delta":
|
|
assistant_content += str(event.data.get("content") or "")
|
|
yield emit_turn_event(event, conversation_id=session.session_id)
|
|
elif event_name == "message.completed":
|
|
assistant_content = str(event.data.get("content") or assistant_content)
|
|
message_type = str(event.data.get("message_type") or "") or None
|
|
payload = event.data.get("payload")
|
|
message_payload = payload if isinstance(payload, dict) else None
|
|
|
|
latency_ms = int((time.perf_counter() - started) * 1000)
|
|
chat_log_id = save_turn_chat_log(
|
|
user_id=user_id,
|
|
agent_id=agent_id,
|
|
session_id=session.session_id,
|
|
external_conversation_id=session.external_conversation_id,
|
|
query=turn_input.display_text,
|
|
answer=assistant_content,
|
|
message_type=message_type,
|
|
payload=message_payload,
|
|
turn_id=turn_id,
|
|
latency_ms=latency_ms,
|
|
)
|
|
if assistant_content:
|
|
yield emit_message_completed(
|
|
content=assistant_content,
|
|
conversation_id=session.session_id,
|
|
message_type=message_type,
|
|
payload=message_payload,
|
|
chat_log_id=chat_log_id,
|
|
)
|
|
touch_chat_session(user_id, agent_id, session.session_id, status="done")
|
|
yield emit_run_completed(
|
|
run_id=run_id,
|
|
turn_id=turn_id,
|
|
conversation_id=session.session_id,
|
|
session_status="done",
|
|
chat_log_id=chat_log_id,
|
|
)
|
|
except AppError as exc:
|
|
current_app.logger.warning(
|
|
"[chat-turn] failed request_id=%s turn_id=%s code=%s message=%s",
|
|
req_id,
|
|
turn_id,
|
|
getattr(exc, "code", None),
|
|
exc.message,
|
|
)
|
|
# 业务失败后先 rollback,避免 handler 预占/脏写被 touch_chat_session 一并提交
|
|
db.session.rollback()
|
|
touch_chat_session(user_id, agent_id, session.session_id, status="error")
|
|
yield emit_run_failed(
|
|
run_id=run_id,
|
|
turn_id=turn_id,
|
|
conversation_id=session.session_id,
|
|
message=exc.message,
|
|
code=str(getattr(exc, "code", "") or "") or None,
|
|
user_facing=True,
|
|
)
|
|
except Exception as exc:
|
|
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
|
|
db.session.rollback()
|
|
touch_chat_session(user_id, agent_id, session.session_id, status="error")
|
|
yield emit_run_failed(
|
|
run_id=run_id,
|
|
turn_id=turn_id,
|
|
conversation_id=session.session_id,
|
|
message=str(exc),
|
|
)
|