feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持
This commit is contained in:
1 parent
ac4262cd75
commit
c8ce77199e
183 files changed
+11690
-2300
No files matched your search
+74
-166
@@ -39,13 +39,9 @@ from app.core.errors import (
|
||||
)
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
agent_name = str(getattr(agent_proxy, 'name', None) or '').strip()
|
||||
return agent_name in LEAVE_FEATURE_AGENT_NAMES
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
@@ -88,18 +84,18 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, agent_name: str | None = None) -> str:
|
||||
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_name: 当前 Agent 名称,仅对发货通知 Agent 做工具名净化。
|
||||
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_name or '').strip() != SHIPPING_NOTICE_AGENT_NAME:
|
||||
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
|
||||
return value
|
||||
import re
|
||||
|
||||
@@ -977,10 +973,10 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_name = str(getattr(g.current_agent, 'name', '') or '').strip()
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_name)})
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
@@ -1283,6 +1279,11 @@ def chat_completions():
|
||||
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
|
||||
if resolve_runtime_provider(agent) == 'iframe':
|
||||
raise ValidationError('Embedded iframe agents do not support chat completions')
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
|
||||
@@ -1290,9 +1291,17 @@ def chat_completions():
|
||||
agent_proxy = SimpleNamespace(
|
||||
id=agent_id,
|
||||
name=getattr(agent, 'name', None),
|
||||
type=getattr(agent, 'type', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
agent_code=getattr(agent, 'agent_code', None),
|
||||
runtime_provider=getattr(agent, 'runtime_provider', None),
|
||||
conversation_mode=getattr(agent, 'conversation_mode', None),
|
||||
dify_app_type=getattr(agent, 'dify_app_type', None),
|
||||
capabilities=getattr(agent, 'capabilities', None),
|
||||
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
|
||||
handler_config=getattr(agent, 'handler_config', None),
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
@@ -1302,7 +1311,6 @@ def chat_completions():
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
@@ -1369,39 +1377,44 @@ def chat_completions():
|
||||
if not normalized_files:
|
||||
normalized_files = None
|
||||
|
||||
if normalized_files and PLMOracleService.supports(query, agent_proxy):
|
||||
raise ValidationError('This route does not support attachments')
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
|
||||
relay_stream_ctx = ChatStreamContext(
|
||||
query=query,
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
request_id=request_id,
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.chat.router import try_fast_route
|
||||
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
from app.services.maintenance_chat_service import MaintenanceChatService
|
||||
faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None
|
||||
|
||||
if faq_hit:
|
||||
generator = FaqCacheService.stream_chat(
|
||||
faq_hit,
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif not normalized_files and MaintenanceChatService.supports(query, agent_proxy):
|
||||
generator = MaintenanceChatService.stream_chat(
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported and leave_feature_enabled:
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
fast_route = try_fast_route(
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
)
|
||||
if fast_route is not None:
|
||||
generator = fast_route.generator
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
@@ -1422,61 +1435,10 @@ def chat_completions():
|
||||
),
|
||||
),
|
||||
)
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.text2sql import Text2SQLService
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
declares_file_check = agent_declares_file_check_progress(agent_proxy)
|
||||
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
|
||||
dify_inputs = build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
session_id=session.session_id,
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
)
|
||||
if declares_file_check or is_file_check_agent:
|
||||
# [STEP 1] file_check 的 task_id 校验已在统一 dify_inputs 分发入口完成;这里只保留 turn 注册
|
||||
if is_file_check_agent:
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_file_check_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
display_query=display_query,
|
||||
)
|
||||
generator = stream_chat_via_executor(relay_stream_ctx)
|
||||
|
||||
def relay_stream():
|
||||
from app.services.chat_perf import chat_perf_enabled
|
||||
@@ -1493,77 +1455,15 @@ def chat_completions():
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
is_shipping_stream = str(getattr(agent_proxy, 'name', '') or '').strip() == SHIPPING_NOTICE_AGENT_NAME
|
||||
emitted_shipping_state_keys: set[str] = set()
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
def build_shipping_ui_state_event() -> dict | None:
|
||||
"""
|
||||
构造发货通知专属 UI State SSE 事件。
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
)
|
||||
|
||||
核心逻辑:优先使用前端显式 task_id,其次按 batch 焦点任务补齐;事件只携带状态机读模型,
|
||||
不依赖 Dify 文本,供前端即时渲染按钮和步骤。
|
||||
"""
|
||||
if not is_shipping_stream:
|
||||
return None
|
||||
try:
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
task = get_task_by_ref(shipping_task_id)
|
||||
batch = get_batch_by_no(shipping_batch_no)
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
candidate = get_task_by_ref(focus_task_no)
|
||||
if candidate is not None and candidate.batch_id == batch.id:
|
||||
task = candidate
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session.session_id,
|
||||
'task_no': task.task_no,
|
||||
'batch_no': task.batch.batch_no if task.batch is not None else None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
}
|
||||
if batch is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session.session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'batch_ui_state': build_batch_ui_state(batch),
|
||||
}
|
||||
except Exception:
|
||||
current_app.logger.exception(
|
||||
'[chat-api] build shipping_ui_state failed request_id=%s session_id=%s task_id=%s batch_no=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
shipping_task_id,
|
||||
shipping_batch_no,
|
||||
)
|
||||
return None
|
||||
|
||||
def maybe_emit_shipping_ui_state() -> str | None:
|
||||
event = build_shipping_ui_state_event()
|
||||
if not event:
|
||||
return None
|
||||
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
|
||||
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
|
||||
focus_state = batch_ui_state.get('focus_task_ui_state') if isinstance(batch_ui_state.get('focus_task_ui_state'), dict) else {}
|
||||
checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint')
|
||||
key = json.dumps({
|
||||
'task_no': event.get('task_no'),
|
||||
'batch_no': event.get('batch_no'),
|
||||
'checkpoint': checkpoint,
|
||||
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
|
||||
}, ensure_ascii=False, sort_keys=True)
|
||||
if key in emitted_shipping_state_keys:
|
||||
return None
|
||||
emitted_shipping_state_keys.add(key)
|
||||
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
|
||||
initial_shipping_state = maybe_emit_shipping_ui_state()
|
||||
if initial_shipping_state:
|
||||
yield initial_shipping_state
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
yield preface_line
|
||||
|
||||
try:
|
||||
for chunk in generator:
|
||||
@@ -1625,9 +1525,12 @@ def chat_completions():
|
||||
}
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
shipping_state = maybe_emit_shipping_ui_state()
|
||||
if shipping_state:
|
||||
yield shipping_state
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
event_data,
|
||||
emitted_keys=emitted_handler_state_keys,
|
||||
):
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
@@ -2219,3 +2122,8 @@ def preview_file_raw():
|
||||
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
||||
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
||||
return resp
|
||||
|
||||
|
||||
from app.api.chat_turns import register_chat_turn_routes
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
Reference in new issue
Block a user