91 lines
2.8 KiB
Python
91 lines
2.8 KiB
Python
"""
|
||
backend/app/services/chat/action_schema.py
|
||
|
||
用途:Chat Turn 平台层统一输入/事件结构定义。
|
||
依赖:typing、dataclasses。
|
||
逻辑:turn_runtime 解析请求体并构造 TurnInput;action handler yield TurnEvent 供 SSE 序列化。
|
||
平台层不定义任何领域 refs 键名(如 task_no),refs 为不透明 dict,由各领域 handler 自行解析。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Literal
|
||
|
||
TurnInputType = Literal["text", "action", "form_submit", "upload_followup"]
|
||
|
||
|
||
@dataclass
|
||
class TurnInput:
|
||
"""
|
||
单轮 Chat Turn 的用户侧输入。
|
||
|
||
Args:
|
||
type: 输入类型;第一阶段仅开放 action / form_submit。
|
||
display_text: 写入 ChatLog.query 与前端 user 气泡的可见文案。
|
||
action_type: action / form_submit 时的全局唯一动作标识,如 shipping.submit_decision。
|
||
text: type=text 时的原始问题。
|
||
payload: 业务动作参数,由各领域 handler 自行解析。
|
||
"""
|
||
|
||
type: TurnInputType
|
||
display_text: str
|
||
action_type: str | None = None
|
||
text: str | None = None
|
||
payload: dict[str, Any] = field(default_factory=dict)
|
||
|
||
|
||
def parse_turn_refs(raw: dict[str, Any] | None) -> dict[str, str]:
|
||
"""
|
||
将请求 context.refs 归一化为 string→string 字典。
|
||
|
||
平台层只做类型清洗,不识别具体键名;货代 task_no、请假 leave_id 等由各 domain handler 读取。
|
||
|
||
Args:
|
||
raw: 前端或 adapter 传入的 refs 对象。
|
||
|
||
Returns:
|
||
非空 string 键值对。
|
||
"""
|
||
data = raw if isinstance(raw, dict) else {}
|
||
refs: dict[str, str] = {}
|
||
for key, value in data.items():
|
||
key_text = str(key or "").strip()
|
||
value_text = str(value or "").strip()
|
||
if key_text and value_text:
|
||
refs[key_text] = value_text
|
||
return refs
|
||
|
||
|
||
def parse_turn_refs_from_context(context: dict[str, Any] | None) -> dict[str, str]:
|
||
"""
|
||
从 Chat Turn 请求 context 块提取 refs。
|
||
|
||
Args:
|
||
context: POST body 中的 context 字段。
|
||
|
||
Returns:
|
||
归一化后的 refs 字典。
|
||
"""
|
||
ctx = context if isinstance(context, dict) else {}
|
||
refs_raw = ctx.get("refs") if isinstance(ctx.get("refs"), dict) else {}
|
||
return parse_turn_refs(refs_raw)
|
||
|
||
|
||
@dataclass
|
||
class TurnEvent:
|
||
"""
|
||
Handler 产出的平台语义事件;turn_runtime 负责序列化为 SSE 并写 ChatLog。
|
||
|
||
event 取值:step.started / step.completed / ui_state.updated /
|
||
message.delta / message.completed / run.failed(run.* 由 runtime 统一 emit)。
|
||
"""
|
||
|
||
event: str
|
||
data: dict[str, Any] = field(default_factory=dict)
|
||
|
||
def to_dict(self) -> dict[str, Any]:
|
||
payload = {"event": self.event}
|
||
payload.update(self.data)
|
||
return payload
|