335 lines
14 KiB
Python
335 lines
14 KiB
Python
"""
|
|
api/chat/completions.py
|
|
|
|
用途:处理聊天 SSE completions 请求与上游事件转发。
|
|
依赖:chat.shared、chat.core、services.chat.router、DifyService。
|
|
逻辑:解析 HTTP 请求并建立本地会话,按 Chat Router 分流后保持原 SSE 契约输出。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from .shared import * # noqa: F403
|
|
from . import chat_bp
|
|
from .core import (
|
|
_build_chat_adapter_hints,
|
|
_ensure_chat_session,
|
|
_get_chat_session,
|
|
_should_reset_provider_conversation_for_asset_query,
|
|
_update_chat_session,
|
|
)
|
|
|
|
|
|
@chat_bp.route('/completions', methods=['POST'])
|
|
@require_agent_permission
|
|
def chat_completions():
|
|
"""
|
|
SSE 流式聊天接口
|
|
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
|
|
核心逻辑:
|
|
1. 从请求体中读取 query / agent_id / conversation_id
|
|
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
|
|
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
|
|
传入参数:
|
|
无(从 request.json 读取)
|
|
返回值:
|
|
Flask Response 对象,mimetype=text/event-stream
|
|
"""
|
|
data = request.get_json() or {}
|
|
query = data.get('query')
|
|
display_query = str(data.get('display_query') or query or '').strip()
|
|
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
|
conversation_id = data.get('conversation_id')
|
|
shipping_task_id = str(data.get('task_id') or '').strip()
|
|
kb_type = data.get('kb_type', '企业知识库')
|
|
files = data.get('files')
|
|
request_id = uuid.uuid4().hex[:12]
|
|
user = getattr(g, 'current_user', None)
|
|
agent = getattr(g, 'current_agent', None)
|
|
current_app.logger.info('[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s', request_id, getattr(user, 'id', None), getattr(agent, 'id', None), len(query or ''), conversation_id, kb_type)
|
|
if user is None or agent is None:
|
|
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)
|
|
|
|
from types import SimpleNamespace
|
|
from app.services.agent_directory import serialize_directory_members
|
|
|
|
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
|
|
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
|
|
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),
|
|
is_aggregate=is_aggregate,
|
|
directory_members=directory_members,
|
|
)
|
|
user_proxy = SimpleNamespace(
|
|
id=user_id,
|
|
username=getattr(user, 'username', None),
|
|
employee_id=getattr(user, 'employee_id', None),
|
|
real_name=getattr(user, 'real_name', None),
|
|
role=getattr(user, 'role', None),
|
|
)
|
|
|
|
from app.services.integrations.dify import DifyService
|
|
|
|
external_conversation_id = None
|
|
if conversation_id:
|
|
existing_session = _get_chat_session(user_id, agent_id, conversation_id)
|
|
if existing_session:
|
|
session = _ensure_chat_session(
|
|
user_id,
|
|
agent_id,
|
|
existing_session.session_id,
|
|
title=display_query,
|
|
status='running',
|
|
)
|
|
external_conversation_id = session.external_conversation_id
|
|
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
|
|
current_app.logger.info(
|
|
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
|
|
request_id,
|
|
session.session_id,
|
|
external_conversation_id,
|
|
query,
|
|
)
|
|
session.external_conversation_id = None
|
|
session.updated_at = datetime.utcnow()
|
|
session.last_active_at = datetime.utcnow()
|
|
db.session.commit()
|
|
external_conversation_id = None
|
|
else:
|
|
session = _ensure_chat_session(
|
|
user_id,
|
|
agent_id,
|
|
conversation_id,
|
|
title=display_query,
|
|
status='running',
|
|
external_conversation_id=conversation_id,
|
|
)
|
|
external_conversation_id = session.external_conversation_id
|
|
else:
|
|
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
|
|
|
# [STEP 1] SSE 生成器可能在请求 scoped Session 清理后才开始迭代;提前快照会话标量,
|
|
# 避免流内事务提交使 ORM 实例过期后触发 DetachedInstanceError。
|
|
local_session_id = str(session.session_id)
|
|
initial_session_status = str(session.status or 'running')
|
|
initial_external_conversation_id = str(external_conversation_id or '').strip() or None
|
|
stream_session = SimpleNamespace(session_id=local_session_id)
|
|
|
|
normalized_files: list[dict] | None = None
|
|
if files is not None:
|
|
if not isinstance(files, list):
|
|
raise ValidationError('files must be a list')
|
|
normalized_files = []
|
|
for item in files:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
transfer_method = str(item.get('transfer_method') or '').strip()
|
|
ftype = str(item.get('type') or '').strip()
|
|
if transfer_method not in ('local_file', 'remote_url'):
|
|
continue
|
|
if ftype not in ('image', 'document', 'audio', 'video', 'custom'):
|
|
continue
|
|
if transfer_method == 'local_file':
|
|
upload_file_id = str(item.get('upload_file_id') or '').strip()
|
|
if not upload_file_id:
|
|
continue
|
|
normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id})
|
|
else:
|
|
url = str(item.get('url') or '').strip()
|
|
if not url:
|
|
continue
|
|
normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url})
|
|
if not normalized_files:
|
|
normalized_files = None
|
|
|
|
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=stream_session,
|
|
external_conversation_id=initial_external_conversation_id,
|
|
request_id=request_id,
|
|
normalized_files=normalized_files,
|
|
adapter_hints=_build_chat_adapter_hints(
|
|
shipping_task_id=shipping_task_id,
|
|
),
|
|
shipping_task_id=shipping_task_id,
|
|
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)
|
|
|
|
fast_route = try_fast_route(
|
|
user=user_proxy,
|
|
agent=agent_proxy,
|
|
query=query,
|
|
agent_id=agent_id,
|
|
session_id=local_session_id,
|
|
external_conversation_id=initial_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,
|
|
user_proxy.id,
|
|
agent_proxy,
|
|
initial_external_conversation_id,
|
|
request_id=request_id,
|
|
session_id=local_session_id,
|
|
files=normalized_files,
|
|
inputs=build_chat_dify_inputs(
|
|
agent_proxy,
|
|
session_id=local_session_id,
|
|
request_id=request_id,
|
|
trigger_source="frontend_chat",
|
|
user_role=user_proxy.role,
|
|
adapter_hints=_build_chat_adapter_hints(
|
|
shipping_task_id=shipping_task_id,
|
|
),
|
|
),
|
|
)
|
|
else:
|
|
from app.services.chat.executors import stream_chat_via_executor
|
|
|
|
generator = stream_chat_via_executor(relay_stream_ctx)
|
|
|
|
def relay_stream():
|
|
from app.services.chat_perf import chat_perf_enabled
|
|
|
|
relay_started = time.perf_counter()
|
|
relay_first_chunk_at: float | None = None
|
|
created_event = {
|
|
'event': 'session_created',
|
|
'conversation_id': local_session_id,
|
|
'provider_conversation_id': initial_external_conversation_id,
|
|
'session_status': initial_session_status,
|
|
}
|
|
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
|
|
|
|
known_provider_conversation_id = initial_external_conversation_id
|
|
known_status = initial_session_status
|
|
emitted_handler_state_keys: set[str] = set()
|
|
|
|
from app.services.chat.stream_relay import (
|
|
iter_handler_preface_sse,
|
|
iter_handler_terminal_sse,
|
|
)
|
|
|
|
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:
|
|
if relay_first_chunk_at is None:
|
|
relay_first_chunk_at = time.perf_counter()
|
|
if not isinstance(chunk, str) or not chunk.startswith('data: '):
|
|
yield chunk
|
|
continue
|
|
|
|
raw_payload = chunk[6:].strip()
|
|
try:
|
|
event_data = json.loads(raw_payload)
|
|
except Exception:
|
|
yield chunk
|
|
continue
|
|
|
|
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
|
|
event_name = event_data.get('event')
|
|
should_touch = False
|
|
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
|
|
known_provider_conversation_id = provider_conversation_id
|
|
should_touch = True
|
|
if event_name in ('message_end', 'workflow_finished'):
|
|
known_status = 'done'
|
|
should_touch = True
|
|
elif event_name == 'error':
|
|
known_status = 'error'
|
|
should_touch = True
|
|
|
|
if should_touch:
|
|
updated_session = _update_chat_session(
|
|
user_id,
|
|
agent_id,
|
|
local_session_id,
|
|
status=known_status,
|
|
external_conversation_id=known_provider_conversation_id,
|
|
touch=True,
|
|
)
|
|
if updated_session:
|
|
known_status = updated_session.status
|
|
|
|
event_data['provider_conversation_id'] = provider_conversation_id
|
|
event_data['conversation_id'] = local_session_id
|
|
event_data['session_status'] = known_status
|
|
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
|
|
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
|
|
relay_total_ms = int((time.perf_counter() - relay_started) * 1000)
|
|
current_app.logger.info(
|
|
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
|
|
request_id,
|
|
local_session_id,
|
|
relay_first_ms,
|
|
relay_total_ms,
|
|
event_name,
|
|
)
|
|
event_data['hxops_relay'] = {
|
|
'first_chunk_ms': relay_first_ms,
|
|
'total_relay_ms': relay_total_ms,
|
|
}
|
|
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
|
if event_name in ('message_end', 'workflow_finished'):
|
|
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, local_session_id)
|
|
payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'}
|
|
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
|
|
|
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
|
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',
|
|
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
|
|
'X-Accel-Buffering': 'no'
|
|
}
|
|
)
|