From bf5f735404d782cddfd63d65026127edf33f369f Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Thu, 14 May 2026 17:52:21 +0800 Subject: [PATCH] =?UTF-8?q?chatview=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/services/dify.py | 32 ++++++++-- backend/app/services/text2sql.py | 104 ++++++++++++++++++++++++------- frontend/src/views/ChatView.vue | 63 ++++++++++++++----- 3 files changed, 155 insertions(+), 44 deletions(-) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 3552a15a..ac4fa4d4 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -24,6 +24,7 @@ chat.py (/api/chat/completions) """ import json import time +import uuid from typing import Any, List, Optional import requests @@ -37,6 +38,26 @@ from app.services.integration_api import IntegrationApiService class DifyService: """Dify service wrapper.""" + @staticmethod + def _normalize_dify_conversation_id(conversation_id: str | None) -> str: + """ + Dify 只接受标准 UUID 会话 ID。 + 本项目里 ERP Text2SQL 会生成 `erp_xxx` 形式的本地会话号, + 这类值不能继续透传给 Dify,否则会触发 400 invalid_param。 + """ + value = str(conversation_id or "").strip() + if not value: + return "" + try: + return str(uuid.UUID(value)) + except (ValueError, TypeError, AttributeError): + if current_app: + current_app.logger.warning( + "[chat-stream] ignore non-uuid conversation_id for dify: %s", + value, + ) + return "" + @staticmethod def _build_chat_messages_url(base_url: str) -> str: """ @@ -90,6 +111,7 @@ class DifyService: # Prefer agent-specific base URL; fallback to global config. base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE url = DifyService._build_chat_messages_url(base_url) + normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id) headers = { 'Authorization': f'Bearer {agent.dify_api_key}', @@ -99,7 +121,7 @@ class DifyService: 'inputs': {}, 'query': query, 'response_mode': 'streaming', - 'conversation_id': conversation_id or '', + 'conversation_id': normalized_conversation_id, 'user': str(user_id), } @@ -110,7 +132,7 @@ class DifyService: getattr(agent, 'id', None), base_url, len(query or ''), - conversation_id, + normalized_conversation_id or conversation_id, ) start_time = time.time() @@ -161,7 +183,7 @@ class DifyService: event, len(data.get('answer', '') or ''), bool(data.get('metadata')), - data.get('conversation_id') or conversation_id, + data.get('conversation_id') or normalized_conversation_id, ) if event == 'message': @@ -196,7 +218,7 @@ class DifyService: chat_log_id = DifyService._log_chat( user_id=user_id, agent_id=agent.id, - conversation_id=data.get('conversation_id') or conversation_id, + conversation_id=data.get('conversation_id') or normalized_conversation_id, query=query, answer=''.join(full_answer), tokens=usage.get('total_tokens', 0), @@ -209,7 +231,7 @@ class DifyService: if current_app: current_app.logger.info( "[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s", - data.get('conversation_id') or conversation_id, + data.get('conversation_id') or normalized_conversation_id, len(''.join(full_answer)), len(retriever_resources), len(attribution_parts), diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index ff86e263..d4347835 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -3,7 +3,7 @@ import os import re import time from pathlib import Path -from flask import current_app +from flask import current_app, has_app_context class Text2SQLService: _schema_text = None @@ -568,28 +568,88 @@ class Text2SQLService: """Yields SSE events to frontend just like DifyService""" start_time = time.time() final_conversation_id = conversation_id or f"erp_{int(time.time())}" - - # 1. Generate SQL - yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n" - sql = Text2SQLService.generate_sql(query) - yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n" - - # 2. Execute SQL - columns, rows = Text2SQLService.execute_sql(sql) - if columns == ["Error"] and rows and rows[0]: - error_message = str(rows[0][0] or "") - if Text2SQLService._is_repairable_sql_error(error_message): - yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n" - repaired_sql = Text2SQLService.repair_sql(query, sql, error_message) - if repaired_sql and repaired_sql != sql: - sql = repaired_sql - columns, rows = Text2SQLService.execute_sql(sql) - - # 3. Format result - yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n" - result_text = Text2SQLService.format_result(columns, rows, sql, query) + try: + # 1. Generate SQL + yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n" + stage_start = time.time() + sql = Text2SQLService.generate_sql(query) + generate_sql_ms = int((time.time() - stage_start) * 1000) + if current_app: + current_app.logger.info( + "[text2sql] generate_sql done conversation_id=%s elapsed_ms=%s sql_preview=%s", + final_conversation_id, + generate_sql_ms, + (sql or "")[:300], + ) + yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n" - latency = int((time.time() - start_time) * 1000) + # 2. Execute SQL + stage_start = time.time() + columns, rows = Text2SQLService.execute_sql(sql) + execute_sql_ms = int((time.time() - stage_start) * 1000) + if current_app: + current_app.logger.info( + "[text2sql] execute_sql done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s", + final_conversation_id, + execute_sql_ms, + len(columns or []), + len(rows or []), + ) + if columns == ["Error"] and rows and rows[0]: + error_message = str(rows[0][0] or "") + if Text2SQLService._is_repairable_sql_error(error_message): + yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n" + repair_stage_start = time.time() + repaired_sql = Text2SQLService.repair_sql(query, sql, error_message) + repair_sql_ms = int((time.time() - repair_stage_start) * 1000) + if current_app: + current_app.logger.info( + "[text2sql] repair_sql done conversation_id=%s elapsed_ms=%s sql_changed=%s", + final_conversation_id, + repair_sql_ms, + bool(repaired_sql and repaired_sql != sql), + ) + if repaired_sql and repaired_sql != sql: + sql = repaired_sql + stage_start = time.time() + columns, rows = Text2SQLService.execute_sql(sql) + execute_sql_ms = int((time.time() - stage_start) * 1000) + if current_app: + current_app.logger.info( + "[text2sql] execute_sql retry done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s", + final_conversation_id, + execute_sql_ms, + len(columns or []), + len(rows or []), + ) + + # 3. Format result + yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n" + stage_start = time.time() + result_text = Text2SQLService.format_result(columns, rows, sql, query) + format_result_ms = int((time.time() - stage_start) * 1000) + latency = int((time.time() - start_time) * 1000) + if current_app: + current_app.logger.info( + "[text2sql] format_result done conversation_id=%s elapsed_ms=%s total_ms=%s", + final_conversation_id, + format_result_ms, + latency, + ) + except Exception as exc: + if current_app: + current_app.logger.exception( + "[text2sql] stream_chat failed conversation_id=%s query=%s", + final_conversation_id, + query, + ) + error_data = { + 'event': 'error', + 'message': str(exc) or 'ERP 问数执行失败', + 'conversation_id': final_conversation_id, + } + yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n" + return # Create ChatLog from app.models import ChatLog, db diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index ce73a026..9901df09 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -10,10 +10,10 @@ * - 支持从首页携带预设问题快速发起对话 * - 在回答结束后允许用户对本次回答进行评分与意见反馈 */ -import { ref, onMounted, onBeforeUnmount, computed } from 'vue'; +import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue'; import { useI18n } from 'vue-i18n'; import { useChat } from '../composables/useChat'; -import { Send, Bot, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, User, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink } from 'lucide-vue-next'; +import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink } from 'lucide-vue-next'; import { marked } from 'marked'; import { useRoute, useRouter } from 'vue-router'; import { config } from '../config'; @@ -32,6 +32,8 @@ const selectedKb = ref('企业知识库'); const showKbDropdown = ref(false); const kbMenuRef = ref(null); const kbOptions = ['企业知识库', 'ERP知识库']; +const chatScrollContainer = ref(null); +let scrollToBottomFrame: number | null = null; marked.setOptions({ gfm: true, @@ -672,6 +674,26 @@ const browserPanelStyle = computed(() => { return { width: `${browserPanelWidth.value}px` }; }); +const scrollChatToBottom = async () => { + await nextTick(); + const container = chatScrollContainer.value; + if (!container) return; + container.scrollTo({ + top: container.scrollHeight, + behavior: 'auto', + }); +}; + +const scheduleScrollChatToBottom = () => { + if (scrollToBottomFrame !== null) { + window.cancelAnimationFrame(scrollToBottomFrame); + } + scrollToBottomFrame = window.requestAnimationFrame(() => { + scrollToBottomFrame = null; + void scrollChatToBottom(); + }); +}; + const normalizeBrowserInput = (value: string) => { const raw = (value || '').trim(); if (!raw) return ''; @@ -1039,6 +1061,7 @@ onMounted(async () => { } // Use config from config.ts instead of API showChatRating.value = config.workspace?.showChatRating ?? true; + scheduleScrollChatToBottom(); }); onBeforeUnmount(() => { @@ -1046,8 +1069,26 @@ onBeforeUnmount(() => { document.removeEventListener('touchstart', handleDocumentPointerDown); window.removeEventListener('resize', syncViewportWidth); stopBrowserResize(); + if (scrollToBottomFrame !== null) { + window.cancelAnimationFrame(scrollToBottomFrame); + scrollToBottomFrame = null; + } }); +watch( + () => ({ + messageCount: messages.value.length, + lastMessageContent: messages.value[messages.value.length - 1]?.content || '', + lastMessageRole: messages.value[messages.value.length - 1]?.role || '', + isThinking: isThinking.value, + conversationId: conversationId.value || '', + }), + () => { + scheduleScrollChatToBottom(); + }, + { deep: false }, +); + /** * 反馈相关状态 * showChatRating:是否启用评分功能(后续可接入配置) @@ -1220,6 +1261,7 @@ const showChatRating = ref(false);
@@ -1233,14 +1275,9 @@ const showChatRating = ref(false); -
-
- -
+