feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持

This commit is contained in:
hugo committed 2026-07-07 11:10:32 +08:00
1 parent ac4262cd75
commit c8ce77199e
183 files changed
+11690 -2300

No files matched your search

@@ -0,0 +1,85 @@
"""
backend/app/services/chat/action_registry.py
用途:Chat Turn Action Handler 注册与解析。
依赖:turn_context.TurnContext、action_schema.TurnEvent、agent_registry.resolver。
逻辑:各领域在 chat_action_handlers / maintenance_chat_actions 等模块注册 handler;turn_runtime 调用 resolve。
"""
from __future__ import annotations
from typing import Any, Iterator, Protocol
from app.core.errors import ForbiddenError, NotFoundError, ValidationError
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
# action_type 前缀 → 允许的 agent_code 集合;空集合表示不限制。
ACTION_AGENT_CODES: dict[str, tuple[str, ...]] = {
"shipping.": ("shipping_notice",),
}
class ChatActionHandler(Protocol):
"""业务 Action Handler 统一接口。"""
action_type: str
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
...
_REGISTRY: dict[str, ChatActionHandler] = {}
def register_action_handler(handler: ChatActionHandler) -> ChatActionHandler:
"""注册 action handler 并返回原实例,便于模块级装饰式写法。"""
key = str(getattr(handler, "action_type", "") or "").strip()
if not key:
raise ValidationError("action handler missing action_type")
_REGISTRY[key] = handler
return handler
def list_action_types() -> list[str]:
return sorted(_REGISTRY.keys())
def _assert_agent_may_run(action_type: str, agent: Any) -> None:
from app.services.agent_registry.resolver import resolve_agent_code
agent_code = resolve_agent_code(agent)
for prefix, allowed_codes in ACTION_AGENT_CODES.items():
if not action_type.startswith(prefix):
continue
if allowed_codes and agent_code not in allowed_codes:
agent_name = str(getattr(agent, "name", "") or "").strip() or agent_code
raise ForbiddenError(f"Agent '{agent_name}' cannot run action '{action_type}'")
return
def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler:
"""
根据 input.action_type 解析 handler,并校验 Agent 权限。
Raises:
ValidationError: action_type 缺失或未注册。
ForbiddenError: 当前 Agent 不允许执行该 action。
"""
action_type = str(ctx.input.action_type or "").strip()
if not action_type:
raise ValidationError("action_type is required for action/form_submit turns")
handler = _REGISTRY.get(action_type)
if handler is None:
raise NotFoundError(f"Unknown action_type: {action_type}")
_assert_agent_may_run(action_type, ctx.agent)
return handler
def ensure_handlers_loaded() -> None:
"""延迟导入各领域 handler 模块以完成注册。"""
from app.services.shipping_notice import chat_action_handlers as _shipping_handlers # noqa: F401
from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401
_ = _shipping_handlers
_ = _shipping_extended
@@ -0,0 +1,90 @@
"""
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
Whitespace-only changes.
@@ -0,0 +1,75 @@
"""
backend/app/services/chat/executors/__init__.py
用途:RUNTIME_PROVIDER_REGISTRY 与聊天 Executor 解析入口。
依赖:dify_chat、hybrid、builtin executors;agent_registry.resolver。
逻辑:chat.py completions 默认 Dify 路径调用 stream_chat_via_executor。
"""
from __future__ import annotations
from typing import Iterator
from app.core.errors import ValidationError
from app.services.agent_registry.handlers.base import ChatStreamContext
from app.services.agent_registry.resolver import resolve_runtime_provider
from app.services.chat.executors.base import ChatExecutor
from app.services.chat.executors.builtin import BuiltinChatExecutor
from app.services.chat.executors.dify_chat import DifyChatExecutor
from app.services.chat.executors.dify_workflow import DifyWorkflowExecutor
from app.services.chat.executors.hybrid import HybridChatExecutor
_dify_chat = DifyChatExecutor()
_dify_workflow = DifyWorkflowExecutor()
_builtin = BuiltinChatExecutor()
_hybrid = HybridChatExecutor()
RUNTIME_PROVIDER_REGISTRY: dict[str, ChatExecutor] = {
'dify': _dify_chat,
'builtin': _builtin,
'hybrid': _hybrid,
}
def resolve_chat_executor(agent) -> ChatExecutor:
"""
按 agents.runtime_provider 解析 Executor。
核心逻辑:dify 时按 dify_app_type 区分 workflow/chatflow;iframe 禁止走 completions。
Raises:
ValidationError: runtime_provider=iframe。
"""
provider = resolve_runtime_provider(agent)
if provider == 'iframe':
raise ValidationError('Embedded iframe agents do not support chat completions')
if provider == 'dify':
app_type = str(getattr(agent, 'dify_app_type', None) or 'chatflow').strip().lower()
return _dify_workflow if app_type == 'workflow' else _dify_chat
executor = RUNTIME_PROVIDER_REGISTRY.get(provider)
if executor is None:
raise ValidationError(f'Unsupported runtime_provider: {provider}')
return executor
def stream_chat_via_executor(ctx: ChatStreamContext) -> Iterator[str]:
"""
经 RUNTIME_PROVIDER_REGISTRY 执行聊天上游 SSE 流。
Args:
ctx: ChatStreamContext。
Returns:
上游 SSE 行迭代器。
"""
executor = resolve_chat_executor(ctx.agent)
return executor.stream(ctx)
__all__ = [
'RUNTIME_PROVIDER_REGISTRY',
'resolve_chat_executor',
'stream_chat_via_executor',
]
@@ -0,0 +1,49 @@
"""
backend/app/services/chat/executors/base.py
用途:聊天 Executor 基类与 Dify 流构建辅助。
依赖:agent_runtime_context.dify_inputs、agent_registry.handlers。
逻辑:各 runtime_provider Executor 实现 stream() 返回上游 SSE 行迭代器。
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Iterator
from app.services.agent_registry.handlers.base import ChatStreamContext
class ChatExecutor(ABC):
"""聊天运行时 Executor 基类。"""
provider_key: str = ''
@abstractmethod
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
"""
产出上游 SSE 行(`data: {...}\\n\\n`)。
Args:
ctx: 聊天流上下文。
"""
def build_dify_inputs_for_context(ctx: ChatStreamContext) -> dict[str, Any]:
"""调用 Context Adapter Registry 构建 Dify inputs。"""
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
return build_chat_dify_inputs(
ctx.agent,
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
request_id=ctx.request_id,
trigger_source='frontend_chat',
adapter_hints=ctx.adapter_hints,
)
__all__ = [
'ChatExecutor',
'ChatStreamContext',
'build_dify_inputs_for_context',
]
@@ -0,0 +1,31 @@
"""
backend/app/services/chat/executors/builtin.py
用途:runtime_provider=builtin 的聊天 Executor。
依赖:agent_registry.resolver.resolve_handler。
逻辑:必须存在 Handler;由 Handler 驱动内置流(v1 未实现完整 builtin 流时显式报错)。
"""
from __future__ import annotations
from typing import Iterator
from app.core.errors import AppError
from app.services.agent_registry.resolver import resolve_handler
from app.services.chat.executors.base import ChatExecutor, ChatStreamContext
class BuiltinChatExecutor(ChatExecutor):
"""纯内置运行时 Executor。"""
provider_key = 'builtin'
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
handler = resolve_handler(ctx.agent)
ctx = handler.prepare_stream(ctx)
raise AppError(
code='AGENT.BUILTIN_NOT_IMPLEMENTED',
message='runtime_provider=builtin 的聊天流尚未实现,请使用 hybrid 或 dify',
http_status=501,
details={'handler_key': handler.handler_key},
)
@@ -0,0 +1,43 @@
"""
backend/app/services/chat/executors/dify_chat.py
用途:runtime_provider=dify 的 Chatflow 聊天 Executor。
依赖:DifyService.stream_chat、executors.base、agent_registry.resolver。
逻辑:Handler.prepare_stream → build_chat_dify_inputs → DifyService.stream_chat。
"""
from __future__ import annotations
from typing import Iterator
from app.services.agent_registry.resolver import resolve_handler_for_agent_code
from app.services.chat.executors.base import (
ChatExecutor,
ChatStreamContext,
build_dify_inputs_for_context,
)
from app.services.dify import DifyService
class DifyChatExecutor(ChatExecutor):
"""Dify Chatflow 流式对话 Executor。"""
provider_key = 'dify'
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
handler = resolve_handler_for_agent_code(ctx.agent)
if handler is not None:
ctx = handler.prepare_stream(ctx)
dify_inputs = build_dify_inputs_for_context(ctx)
yield from DifyService.stream_chat(
ctx.query,
int(getattr(ctx.user, 'id', 0) or 0),
ctx.agent,
ctx.external_conversation_id,
request_id=ctx.request_id,
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
hxops_turn_id=ctx.hxops_turn_id,
files=ctx.normalized_files,
inputs=dify_inputs,
display_query=ctx.display_query,
)
@@ -0,0 +1,17 @@
"""
backend/app/services/chat/executors/dify_workflow.py
用途:runtime_provider=dify 且 dify_app_type=workflow 的 Executor。
依赖:DifyChatExecutor(当前聊天 completions 仍走 chat-messages SSE)。
逻辑:v1 与 Chatflow 共用 stream_chat;后续可切换 run_workflow_streaming 适配器。
"""
from __future__ import annotations
from app.services.chat.executors.dify_chat import DifyChatExecutor
class DifyWorkflowExecutor(DifyChatExecutor):
"""Dify Workflow 类型 Agent 的聊天 Executor(暂与 Chatflow 同路径)。"""
provider_key = 'dify_workflow'
@@ -0,0 +1,29 @@
"""
backend/app/services/chat/executors/hybrid.py
用途:runtime_provider=hybrid 的聊天 Executor(Handler 前置 + Dify 流)。
依赖:resolve_handler、DifyChatExecutor。
逻辑:resolve_handler 校验 → handler.prepare_stream → DifyChatExecutor.stream。
"""
from __future__ import annotations
from typing import Iterator
from app.services.agent_registry.resolver import resolve_handler
from app.services.chat.executors.base import ChatExecutor, ChatStreamContext
from app.services.chat.executors.dify_chat import DifyChatExecutor
class HybridChatExecutor(ChatExecutor):
"""Hybrid:业务 Handler 前置 + Dify Chatflow 流。"""
provider_key = 'hybrid'
def __init__(self) -> None:
self._dify = DifyChatExecutor()
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
handler = resolve_handler(ctx.agent)
ctx = handler.prepare_stream(ctx)
yield from self._dify.stream(ctx)
@@ -0,0 +1,193 @@
"""
backend/app/services/chat/intent_route_registry.py
用途:Chat Intent 快路径 handler 注册表(展示配置 + match/stream 执行器)。
依赖:agent_registry.intent_routes。
逻辑:各 intent_routes/*.py 由 load_builtin_intent_routes 调用 register;router 遍历本表;Admin 选项与 handler 同源。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, Iterator
from app.core.errors import ValidationError
from app.services.agent_registry.intent_routes import (
IntentRouteDefinition,
get_intent_route_definition,
list_intent_routes,
parse_intent_routes,
register_intent_route,
)
@dataclass(frozen=True)
class ChatIntentRouteContext:
"""Intent Router 单次 dispatch 上下文。"""
user: Any
agent: Any
query: str
agent_id: int | None
session_id: str
external_conversation_id: str | None
normalized_files: list[dict] | None
kb_type: str | None
leave_supported: bool | None
@property
def has_files(self) -> bool:
return bool(self.normalized_files)
@dataclass(frozen=True)
class ChatIntentRouteHandler:
"""可执行 Chat Intent 快路径定义。"""
key: str
label: str
description: str
priority: int
match: Callable[[ChatIntentRouteContext], bool]
stream: Callable[[ChatIntentRouteContext], Iterator[str]]
category: str = 'business'
enabled: bool = True
supports_files: bool = False
ui_profile: str | None = None
leave_feature: bool = False
_CHAT_INTENT_ROUTE_REGISTRY: dict[str, ChatIntentRouteHandler] = {}
_ROUTES_LOADED = False
def register_chat_intent_route(handler: ChatIntentRouteHandler) -> ChatIntentRouteHandler:
"""
注册 Chat Intent handler,并同步写入 agent_registry.intent_routes。
Raises:
ValidationError: key 为空或重复注册。
"""
key = str(handler.key or '').strip()
if not key:
raise ValidationError('chat intent route key 不能为空')
if key in _CHAT_INTENT_ROUTE_REGISTRY:
raise ValidationError(f'重复的 chat intent route: {key}')
register_intent_route(IntentRouteDefinition(
key=handler.key,
label=handler.label,
description=handler.description,
category=handler.category,
enabled=handler.enabled,
sort_order=handler.priority,
ui_profile=handler.ui_profile,
))
_CHAT_INTENT_ROUTE_REGISTRY[key] = handler
return handler
def list_chat_intent_route_definitions(*, include_disabled: bool = False) -> list[dict[str, Any]]:
"""返回 Admin 可选 route 列表(与 agent_registry.intent_routes 同源)。"""
ensure_intent_routes_loaded()
return list_intent_routes(include_disabled=include_disabled)
def iter_enabled_chat_intent_routes() -> list[ChatIntentRouteHandler]:
"""按 priority 升序返回已启用的 handler 列表。"""
ensure_intent_routes_loaded()
return sorted(
[item for item in _CHAT_INTENT_ROUTE_REGISTRY.values() if item.enabled],
key=lambda item: item.priority,
)
def get_chat_intent_route_handler(key: str) -> ChatIntentRouteHandler | None:
"""按 key 读取 handler;未知 key 返回 None。"""
ensure_intent_routes_loaded()
normalized = str(key or '').strip()
return _CHAT_INTENT_ROUTE_REGISTRY.get(normalized)
def _resolve_content_profile_key(agent) -> str | None:
"""只读 handler_config.content_profile;运行时不再从 intent route 组合推断。"""
handler_config = getattr(agent, 'handler_config', None)
if not isinstance(handler_config, dict):
return None
from app.services.agent_registry.content_profiles import VALID_CONTENT_PROFILES
profile = str(handler_config.get('content_profile') or '').strip()
return profile if profile in VALID_CONTENT_PROFILES else None
def resolve_agent_intent_metadata(agent) -> dict[str, Any]:
"""
根据 Agent 已声明 intent_routes 聚合 UI/功能元数据,供序列化与前端消费。
Returns:
intent_ui_profiles、leave_feature_enabled、hr_focused_avatar、content_profile_key。
"""
ensure_intent_routes_loaded()
content_profile_key = _resolve_content_profile_key(agent)
declared = parse_intent_routes(
getattr(agent, 'handler_config', None).get('intent_routes')
if isinstance(getattr(agent, 'handler_config', None), dict)
else None,
)
if not declared:
return {
'intent_ui_profiles': [],
'leave_feature_enabled': False,
'hr_focused_avatar': False,
'content_profile_key': content_profile_key,
}
ui_profiles: set[str] = set()
leave_feature = False
for route_key in declared:
handler = get_chat_intent_route_handler(route_key)
if handler:
if handler.ui_profile:
ui_profiles.add(handler.ui_profile)
if handler.leave_feature:
leave_feature = True
continue
definition = get_intent_route_definition(route_key)
if definition and definition.ui_profile:
ui_profiles.add(definition.ui_profile)
leave_route_keys = {
key for key in declared
if (handler := get_chat_intent_route_handler(key)) and handler.leave_feature
}
hr_focused_avatar = declared == leave_route_keys and len(leave_route_keys) == 1
return {
'intent_ui_profiles': sorted(ui_profiles),
'leave_feature_enabled': leave_feature,
'hr_focused_avatar': hr_focused_avatar,
'content_profile_key': content_profile_key,
}
def ensure_intent_routes_loaded() -> None:
"""懒加载内置 Chat Intent route 模块(幂等)。"""
global _ROUTES_LOADED
if _ROUTES_LOADED:
return
from app.services.chat.intent_routes import load_builtin_intent_routes
load_builtin_intent_routes()
_ROUTES_LOADED = True
__all__ = [
'ChatIntentRouteContext',
'ChatIntentRouteHandler',
'ensure_intent_routes_loaded',
'get_chat_intent_route_handler',
'iter_enabled_chat_intent_routes',
'list_chat_intent_route_definitions',
'register_chat_intent_route',
'resolve_agent_intent_metadata',
]
@@ -0,0 +1,33 @@
"""
backend/app/services/chat/intent_routes/__init__.py
用途:集中加载内置 Chat Intent route 注册模块。
依赖:chat/intent_routes/* 各业务 route 文件。
逻辑:ensure_intent_routes_loaded / router 首次 dispatch 前调用 load_builtin_intent_routes。
"""
from __future__ import annotations
_LOADED = False
def load_builtin_intent_routes() -> None:
"""幂等加载全部内置 Intent route handler。"""
global _LOADED
if _LOADED:
return
from app.services.chat.intent_routes import (
hr_leave,
maintenance_chat,
plm_oracle,
text2sql,
)
maintenance_chat.register()
plm_oracle.register()
hr_leave.register()
text2sql.register()
_LOADED = True
__all__ = ['load_builtin_intent_routes']
@@ -0,0 +1,48 @@
"""
backend/app/services/chat/intent_routes/hr_leave.py
用途:请假 / HR SQL Intent 快路径注册。
依赖:hr_leave_sqlserver、chat.intent_route_registry。
逻辑:由 load_builtin_intent_routes 调用 register() 完成注册;router 通过注册表 dispatch。
"""
from __future__ import annotations
from app.services.chat.intent_route_registry import (
ChatIntentRouteContext,
ChatIntentRouteHandler,
register_chat_intent_route,
)
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
if ctx.leave_supported is not None:
return bool(ctx.leave_supported)
return HRLeaveSQLServerService.supports(ctx.query)
def _stream(ctx: ChatIntentRouteContext):
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
return HRLeaveSQLServerService.stream_chat(
ctx.query,
ctx.user,
ctx.agent,
ctx.external_conversation_id,
session_id=ctx.session_id,
)
def register() -> ChatIntentRouteHandler:
"""注册 hr_leave_sql 快路径 handler。"""
return register_chat_intent_route(ChatIntentRouteHandler(
key='hr_leave_sql',
label='请假 / HR SQL',
description='命中请假、HR 查询意图时走 HR SQL 快路径',
priority=40,
leave_feature=True,
match=_match,
stream=_stream,
))
@@ -0,0 +1,46 @@
"""
backend/app/services/chat/intent_routes/maintenance_chat.py
用途:设备维保对话 Intent 快路径注册。
依赖:maintenance_chat_service、chat.intent_route_registry。
逻辑:由 load_builtin_intent_routes 调用 register() 完成注册;router 通过注册表 dispatch。
"""
from __future__ import annotations
from app.services.chat.intent_route_registry import (
ChatIntentRouteContext,
ChatIntentRouteHandler,
register_chat_intent_route,
)
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.maintenance_chat_service import MaintenanceChatService
return MaintenanceChatService.supports(ctx.query, ctx.agent)
def _stream(ctx: ChatIntentRouteContext):
from app.services.maintenance_chat_service import MaintenanceChatService
return MaintenanceChatService.stream_chat(
ctx.query,
ctx.user,
ctx.agent,
ctx.external_conversation_id,
session_id=ctx.session_id,
)
def register() -> ChatIntentRouteHandler:
"""注册 maintenance_chat 快路径 handler。"""
return register_chat_intent_route(ChatIntentRouteHandler(
key='maintenance_chat',
label='设备维保对话',
description='命中设备维保助手意图时走内置维保对话快路径',
priority=20,
ui_profile='maintenance',
match=_match,
stream=_stream,
))
@@ -0,0 +1,45 @@
"""
backend/app/services/chat/intent_routes/plm_oracle.py
用途:PLM 物料提取 Intent 快路径注册。
依赖:plm_oracle、chat.intent_route_registry。
逻辑:由 load_builtin_intent_routes 调用 register() 完成注册;router 通过注册表 dispatch。
"""
from __future__ import annotations
from app.services.chat.intent_route_registry import (
ChatIntentRouteContext,
ChatIntentRouteHandler,
register_chat_intent_route,
)
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.plm_oracle import PLMOracleService
return PLMOracleService.supports(ctx.query, ctx.agent)
def _stream(ctx: ChatIntentRouteContext):
from app.services.plm_oracle import PLMOracleService
return PLMOracleService.stream_chat(
ctx.query,
ctx.user,
ctx.agent,
ctx.external_conversation_id,
session_id=ctx.session_id,
)
def register() -> ChatIntentRouteHandler:
"""注册 plm_oracle 快路径 handler。"""
return register_chat_intent_route(ChatIntentRouteHandler(
key='plm_oracle',
label='PLM 物料提取',
description='命中 PLM 物料/生产 SOP 意图时走 Oracle 快路径',
priority=30,
match=_match,
stream=_stream,
))
@@ -0,0 +1,50 @@
"""
backend/app/services/chat/intent_routes/text2sql.py
用途:固资 Text2SQL Intent 快路径注册。
依赖:text2sql、chat.intent_route_registry、agent_registry.resolver。
逻辑:由 load_builtin_intent_routes 调用 register();match 读 capabilities.erp_kb + kb_type 标签。
"""
from __future__ import annotations
from app.services.chat.intent_route_registry import (
ChatIntentRouteContext,
ChatIntentRouteHandler,
register_chat_intent_route,
)
# 与前端 chat kb 选项 label 一致;仅在本 route 注册文件定义。
ERP_KB_TYPE_LABEL = 'ERP知识库'
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.agent_registry.resolver import agent_has_erp_kb
if not agent_has_erp_kb(ctx.agent):
return False
return str(ctx.kb_type or '').strip() == ERP_KB_TYPE_LABEL
def _stream(ctx: ChatIntentRouteContext):
from app.services.text2sql import Text2SQLService
return Text2SQLService.stream_chat(
ctx.query,
ctx.user,
ctx.agent,
ctx.external_conversation_id,
session_id=ctx.session_id,
)
def register() -> ChatIntentRouteHandler:
"""注册 text2sql 快路径 handler。"""
return register_chat_intent_route(ChatIntentRouteHandler(
key='text2sql',
label='Text2SQL / 固资',
description='命中固资 Text2SQL 或 ERP 知识库特化意图时走 SQL 快路径',
priority=50,
match=_match,
stream=_stream,
))
+70 -1
View File
@@ -1,5 +1,74 @@
"""
backend/app/services/chat/log_service.py
用途:聊天历史、反馈业务逻辑。
用途:Chat Turn 与对话历史的 ChatLog 统一写入。
依赖:models.ChatLog、SQLAlchemy。
逻辑:turn_runtime 在 run.completed 时调用 save_turn_chat_log;api/chat 历史路由可逐步迁入。
"""
from __future__ import annotations
import time
from typing import Any
from flask import current_app
from app import db
from app.models import ChatLog
def save_turn_chat_log(
*,
user_id: int | None,
agent_id: int | None,
session_id: str,
external_conversation_id: str | None,
query: str,
answer: str,
message_type: str | None = None,
payload: dict[str, Any] | None = None,
turn_id: str | None = None,
latency_ms: int | None = None,
) -> int | None:
"""
将单轮 Chat Turn 的用户问题与助手摘要写入 ChatLog。
Args:
user_id: 用户 ID。
agent_id: Agent ID。
session_id: 本地会话 ID。
external_conversation_id: 外部 provider 会话 ID。
query: 用户可见问题(display_text)。
answer: 助手最终摘要。
message_type: 结构化消息类型,如 shipping-match-result。
payload: 结构化 payload,供前端回放卡片。
turn_id: 本轮 turn 标识,写入 payload 便于追踪。
latency_ms: 耗时毫秒。
Returns:
新建 ChatLog.id;失败时返回 None。
"""
merged_payload = dict(payload or {})
if turn_id:
merged_payload.setdefault("turn_id", turn_id)
try:
chat_log = ChatLog(
user_id=user_id,
agent_id=agent_id,
conversation_id=external_conversation_id or session_id,
session_id=session_id,
query=query,
answer=answer,
latency=int(latency_ms or 0),
message_type=message_type,
payload=merged_payload or None,
tokens_used=0,
)
db.session.add(chat_log)
db.session.commit()
return chat_log.id
except Exception as exc:
if current_app:
current_app.logger.exception("[chat-turn] failed to save chat log: %s", exc)
db.session.rollback()
return None
+119 -14
View File
@@ -1,27 +1,132 @@
"""
backend/app/services/chat/router.py
用途:Chat Intent Router,按意图分流至 PLM/HR/Text2SQL/Dify。
依赖:integrations/* stream_chat 实现。
逻辑:api/chat/completions 调用本模块 select_stream_generator。
设计参考:docs/tec.md §4.1 Chat Intent Router。
用途:Chat Intent Router — completions 内先于 Executor 的 FAQ 与注册式快路径 dispatch。
依赖:faq_cache、chat.intent_route_registry、agent_registry.resolver。
逻辑:api/chat.completions 调用 try_fast_route;未命中时由 chat.py 走 Executor/Dify。
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any, Iterator
from app.services.agent_registry.resolver import agent_has_intent_route
def select_stream_generator(*, user: Any, agent: Any, query: str, **kwargs: Any) -> Iterator[str]:
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class FastRouteResult:
"""Intent Router 命中结果。"""
generator: Iterator[str]
route_name: str
def try_fast_route(
*,
user: Any,
agent: Any,
query: str,
agent_id: int | None,
session_id: str,
external_conversation_id: str | None = None,
normalized_files: list[dict] | None = None,
kb_type: str | None = None,
leave_supported: bool | None = None,
) -> FastRouteResult | None:
"""
根据 agent 配置与用户问题选择流式 generator。
核心逻辑:Wave 3 从 api/chat.py /completions 分支迁入。
尝试 Intent 快路径;命中则返回 SSE 迭代器,未命中返回 None。
核心逻辑:FAQ 仍优先;其余快路径按 intent_route_registry 的 priority 遍历,
仅当 Agent 声明对应 route 且 match() 命中时 dispatch。
Args:
user: 当前 User 模型实例。
agent: 当前 Agent 模型实例。
query: 用户问题文本。
user: 当前用户代理对象。
agent: 当前 Agent 代理对象。
query: 用户问题。
agent_id: Agent 主键,FAQ 匹配使用。
session_id: HXOPS ChatSession.session_id。
external_conversation_id: Dify 侧会话 ID。
normalized_files: 规范化附件列表。
kb_type: 知识库类型(如 ERP知识库)。
leave_supported: 预计算的 HRLeaveSQLServerService.supports;为 None 时由 route match 计算。
Returns:
SSE 事件字符串迭代器。
Raises:
NotImplementedError: Wave 0 占位。
FastRouteResult 或 None。
"""
raise NotImplementedError('ChatIntentRouter pending Wave 3 migration from api/chat.py')
from app.services.agent_registry.resolver import resolve_agent_code
from app.services.chat.intent_route_registry import (
ChatIntentRouteContext,
ensure_intent_routes_loaded,
iter_enabled_chat_intent_routes,
)
from app.services.faq_cache import FaqCacheService
ensure_intent_routes_loaded()
agent_code = resolve_agent_code(agent)
has_files = bool(normalized_files)
if not has_files:
faq_hit = FaqCacheService.try_match(query, agent_id) if agent_id else None
if faq_hit:
_log_fast_route('faq_cache', agent_code=agent_code, agent_id=agent_id, session_id=session_id)
return FastRouteResult(
generator=FaqCacheService.stream_chat(
faq_hit,
query,
user,
agent,
external_conversation_id,
session_id=session_id,
),
route_name='faq_cache',
)
ctx = ChatIntentRouteContext(
user=user,
agent=agent,
query=query,
agent_id=agent_id,
session_id=session_id,
external_conversation_id=external_conversation_id,
normalized_files=normalized_files,
kb_type=kb_type,
leave_supported=leave_supported,
)
for route in iter_enabled_chat_intent_routes():
if not agent_has_intent_route(agent, route.key):
continue
if has_files and not route.supports_files:
continue
if not route.match(ctx):
continue
_log_fast_route(route.key, agent_code=agent_code, agent_id=agent_id, session_id=session_id)
return FastRouteResult(
generator=route.stream(ctx),
route_name=route.key,
)
return None
def _log_fast_route(route_name: str, *, agent_code: str, agent_id: int | None, session_id: str) -> None:
"""记录 Intent Router 命中日志,便于联调与排错。"""
logger.info(
'[chat-router] route=%s agent_code=%s agent_id=%s session_id=%s',
route_name,
agent_code,
agent_id,
session_id,
)
__all__ = [
'FastRouteResult',
'try_fast_route',
]
+110 -2
View File
@@ -1,6 +1,114 @@
"""
backend/app/services/chat/session_service.py
用途:聊天会话 CRUD 业务逻辑。
逻辑:Wave 3 从 api/chat/_legacy 抽取 sessions 相关路由逻辑。
用途:聊天会话 CRUD,供 turn_runtime 与 api/chat 共用。
依赖:models.ChatSession、SQLAlchemy。
逻辑:从 api/chat.py 抽取 ensure/update session 逻辑,避免 turn 与 completions 各写一套。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from app import db
from app.models import ChatSession
def _session_title_from_text(text: str) -> str:
value = str(text or "").strip()
if not value:
return ""
return value[:30] + ("..." if len(value) > 30 else "")
def get_chat_session(user_id: int, agent_id: int, session_id: str | None) -> ChatSession | None:
"""按 user/agent/session_id 查询已有会话。"""
session_key = str(session_id or "").strip()
if not session_key:
return None
return db.session.query(ChatSession).filter_by(
user_id=user_id,
agent_id=agent_id,
session_id=session_key,
).first()
def ensure_chat_session(
user_id: int,
agent_id: int,
session_id: str | None,
*,
title: str = "",
status: str = "running",
external_conversation_id: str | None = None,
) -> ChatSession:
"""
获取或创建聊天会话,并更新 last_active_at。
Args:
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
session_id: 已有 session_id;为空则新建。
title: 会话标题候选。
status: 会话状态 running/done/error。
external_conversation_id: 外部 provider 会话 ID。
Returns:
ChatSession ORM 实例。
"""
session_key = str(session_id or "").strip()
external_id = str(external_conversation_id or "").strip() or None
session = get_chat_session(user_id, agent_id, session_key)
changed = False
if not session:
session = ChatSession(
session_id=session_key or uuid.uuid4().hex,
user_id=user_id,
agent_id=agent_id,
title=_session_title_from_text(title),
status=status,
external_conversation_id=external_id,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
last_active_at=datetime.utcnow(),
)
db.session.add(session)
db.session.commit()
return session
if not session.title and title:
session.title = _session_title_from_text(title)
changed = True
if status and session.status != status:
session.status = status
changed = True
if external_id and session.external_conversation_id != external_id:
session.external_conversation_id = external_id
changed = True
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
changed = True
if changed:
db.session.commit()
return session
def touch_chat_session(
user_id: int,
agent_id: int,
session_id: str,
*,
status: str | None = None,
) -> ChatSession | None:
"""更新会话活跃时间与可选状态。"""
session = get_chat_session(user_id, agent_id, session_id)
if not session:
return None
if status and session.status != status:
session.status = status
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
db.session.commit()
return session
+79
View File
@@ -0,0 +1,79 @@
"""
backend/app/services/chat/stream_relay.py
用途:聊天 SSE relay 领域增强(Handler UI State 等)。
依赖:agent_registry.resolver、handlers.base。
逻辑:chat.py relay_stream 调用本模块,避免按 Agent 名称硬编码分支。
"""
from __future__ import annotations
import json
from typing import Iterator
from app.services.agent_registry.handlers.base import ChatStreamContext
from app.services.agent_registry.resolver import resolve_handler_for_agent_code
def iter_handler_preface_sse(ctx: ChatStreamContext, *, emitted_keys: set[str]) -> Iterator[str]:
"""
上游流开始前下发 Handler preface SSE(如 shipping_ui_state)。
核心逻辑:按 agent_code 查找 Handler;dedupe 键由 handler.iter_ui_state_dedupe_key 提供。
"""
handler = resolve_handler_for_agent_code(ctx.agent)
if handler is None:
return
for line in handler.iter_preface_sse_lines(ctx):
yield line
try:
payload = line[6:].strip() if line.startswith('data: ') else ''
event = json.loads(payload) if payload else {}
except json.JSONDecodeError:
continue
dedupe_key = handler.iter_ui_state_dedupe_key(event) if isinstance(event, dict) else None
if dedupe_key:
emitted_keys.add(dedupe_key)
def iter_handler_terminal_sse(
ctx: ChatStreamContext,
event_data: dict,
*,
emitted_keys: set[str],
) -> Iterator[str]:
"""上游终态事件后追加 Handler SSE(如 shipping_ui_state 刷新)。"""
handler = resolve_handler_for_agent_code(ctx.agent)
if handler is None:
return
for line in handler.on_upstream_terminal_event(ctx, event_data):
yield line
try:
payload = line[6:].strip() if line.startswith('data: ') else ''
event = json.loads(payload) if payload else {}
except json.JSONDecodeError:
continue
dedupe_key = handler.iter_ui_state_dedupe_key(event) if isinstance(event, dict) else None
if dedupe_key:
emitted_keys.add(dedupe_key)
def maybe_emit_handler_ui_state(ctx: ChatStreamContext, *, emitted_keys: set[str]) -> str | None:
"""
构造并格式化单次 UI State SSE;已 emit 的 dedupe 键则跳过。
Returns:
`data: ...\\n\\n` 字符串或 None。
"""
handler = resolve_handler_for_agent_code(ctx.agent)
if handler is None:
return None
event = handler.build_ui_state_event(ctx)
if not event:
return None
dedupe_key = handler.iter_ui_state_dedupe_key(event)
if dedupe_key and dedupe_key in emitted_keys:
return None
if dedupe_key:
emitted_keys.add(dedupe_key)
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
+56
View File
@@ -0,0 +1,56 @@
"""
backend/app/services/chat/turn_context.py
用途:Chat Turn 执行上下文,供 turn_runtime 与 action handler 共享。
依赖:action_schema.TurnInput。
逻辑:turn_runtime 构造 TurnContext 后传入 handler.stream(ctx);refs 为不透明 dict,领域键名由各 handler 解析。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from app.services.chat.action_schema import TurnInput
@dataclass
class TurnContext:
"""
单轮 Chat Turn 的运行时上下文。
Args:
turn_id: 本轮唯一标识,写入 SSE 与 ChatLog 关联字段。
run_id: 与 turn_id 相同或独立 run 标识,供前端 runs 列表使用。
session_id: 本地 ChatSession.session_id。
request_id: HTTP 请求追踪 ID。
user: 当前用户代理对象(须含 id)。
agent: 当前 Agent 代理对象(须含 id、name)。
input: 归一化后的 TurnInput。
refs: 会话级业务锚点(不透明 dict);键名由各 domain 自行约定。
external_conversation_id: Dify 等外部会话 ID,可为空。
"""
turn_id: str
run_id: str
session_id: str
request_id: str
user: Any
agent: Any
input: TurnInput
refs: dict[str, str] = field(default_factory=dict)
external_conversation_id: str | None = None
@property
def user_id(self) -> int | None:
value = getattr(self.user, "id", None)
return int(value) if value is not None else None
@property
def agent_id(self) -> int | None:
value = getattr(self.agent, "id", None)
return int(value) if value is not None else None
@property
def agent_name(self) -> str:
return str(getattr(self.agent, "name", "") or "").strip()
+179
View File
@@ -0,0 +1,179 @@
"""
backend/app/services/chat/turn_events.py
用途:Chat Turn SSE 事件构造与序列化。
依赖:action_schema.TurnEvent、json。
逻辑:turn_runtime 与 action handler 通过本模块 emit 统一 envelope;兼容层可双发 Dify 风格 message 事件。
"""
from __future__ import annotations
import json
from typing import Any
from app.services.chat.action_schema import TurnEvent
def sse_frame(payload: dict[str, Any]) -> str:
"""将 JSON 对象序列化为 SSE data 帧。"""
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
def emit_run_started(*, run_id: str, turn_id: str, conversation_id: str, session_status: str) -> str:
return sse_frame({
"event": "run.started",
"run_id": run_id,
"turn_id": turn_id,
"conversation_id": conversation_id,
"session_status": session_status,
})
def emit_session_created(*, conversation_id: str, session_status: str, provider_conversation_id: str | None = None) -> str:
"""兼容旧前端 session_created 事件。"""
return sse_frame({
"event": "session_created",
"conversation_id": conversation_id,
"provider_conversation_id": provider_conversation_id,
"session_status": session_status,
})
def emit_step_started(*, step_id: str, label: str, conversation_id: str) -> str:
return sse_frame({
"event": "step.started",
"step_id": step_id,
"label": label,
"conversation_id": conversation_id,
})
def emit_step_completed(*, step_id: str, conversation_id: str) -> str:
return sse_frame({
"event": "step.completed",
"step_id": step_id,
"conversation_id": conversation_id,
})
def emit_ui_state_updated(*, domain: str, conversation_id: str, payload: dict[str, Any]) -> str:
modern = sse_frame({
"event": "ui_state.updated",
"domain": domain,
"conversation_id": conversation_id,
"payload": payload,
})
if domain != "shipping":
return modern
shipping_payload: dict[str, Any] = {
"event": "shipping_ui_state",
"conversation_id": conversation_id,
}
if isinstance(payload.get("ui_state"), dict):
shipping_payload["ui_state"] = payload["ui_state"]
if payload.get("task_no"):
shipping_payload["task_no"] = payload["task_no"]
if payload.get("batch_no"):
shipping_payload["batch_no"] = payload["batch_no"]
return modern + sse_frame(shipping_payload)
def emit_message_delta(*, content: str, conversation_id: str) -> str:
legacy = sse_frame({"event": "message", "answer": content, "conversation_id": conversation_id})
modern = sse_frame({"event": "message.delta", "content": content, "conversation_id": conversation_id})
return legacy + modern
def emit_message_completed(
*,
content: str,
conversation_id: str,
message_type: str | None = None,
payload: dict[str, Any] | None = None,
chat_log_id: int | None = None,
) -> str:
end_payload: dict[str, Any] = {
"event": "message.completed",
"content": content,
"conversation_id": conversation_id,
"replace_answer": True,
}
if message_type:
end_payload["message_type"] = message_type
end_payload["type"] = message_type
if payload is not None:
end_payload["payload"] = payload
end_payload["message_payload"] = payload
if chat_log_id is not None:
end_payload["chat_log_id"] = chat_log_id
legacy = sse_frame({
"event": "message_end",
"answer": content,
"conversation_id": conversation_id,
"replace_answer": True,
**({"type": message_type} if message_type else {}),
**({"payload": payload, "message_payload": payload} if payload is not None else {}),
**({"chat_log_id": chat_log_id} if chat_log_id is not None else {}),
})
return sse_frame(end_payload) + legacy
def emit_run_completed(
*,
run_id: str,
turn_id: str,
conversation_id: str,
session_status: str,
chat_log_id: int | None = None,
) -> str:
return sse_frame({
"event": "run.completed",
"run_id": run_id,
"turn_id": turn_id,
"conversation_id": conversation_id,
"session_status": session_status,
**({"chat_log_id": chat_log_id} if chat_log_id is not None else {}),
})
def emit_run_failed(
*,
run_id: str,
turn_id: str,
conversation_id: str,
message: str,
code: str | None = None,
) -> str:
error_payload: dict[str, Any] = {
"event": "run.failed",
"run_id": run_id,
"turn_id": turn_id,
"conversation_id": conversation_id,
"message": message,
"session_status": "error",
}
if code:
error_payload["code"] = code
legacy = sse_frame({"event": "error", "message": message, "conversation_id": conversation_id, "session_status": "error"})
return sse_frame(error_payload) + legacy
def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str:
"""将 handler 产出的 TurnEvent 转为 SSE;自动补 conversation_id。"""
payload = event.to_dict()
payload.setdefault("conversation_id", conversation_id)
event_name = str(payload.get("event") or "")
if event_name == "ui_state.updated":
domain = str(payload.get("domain") or "")
ui_payload = payload.get("payload") if isinstance(payload.get("payload"), dict) else payload
return emit_ui_state_updated(domain=domain, conversation_id=conversation_id, payload=ui_payload)
if event_name == "message.delta":
return emit_message_delta(content=str(payload.get("content") or ""), conversation_id=conversation_id)
if event_name == "message.completed":
return emit_message_completed(
content=str(payload.get("content") or ""),
conversation_id=conversation_id,
message_type=str(payload.get("message_type") or "") or None,
payload=payload.get("payload") if isinstance(payload.get("payload"), dict) else None,
)
return sse_frame(payload)
+202
View File
@@ -0,0 +1,202 @@
"""
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。
逻辑:api/chat/turns/stream 调用 ChatTurnRuntime.stream();业务 handler 只 yield TurnEvent。
"""
from __future__ import annotations
import time
import uuid
from typing import Any, Iterator
from flask import current_app
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,
)
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,
)
except Exception as exc:
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
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),
)