Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-05-14 18:21:04 +08:00
commit ab60a7da52
5 files changed
+156 -47

No files matched your search

-2
View File
@@ -29,8 +29,6 @@ AUTH_LOCAL_JWT_ISSUER=hxops-backend
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
DATABASE_URL=postgresql://postgres:@localhost:5432/hxops_db
# SiliconFlow API Configuration
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
GJL_API_BASE=https://api.siliconflow.cn/v1
+1 -1
View File
@@ -446,7 +446,7 @@ def test_agent(id):
'tested_at': tested_at
}), 400
request_url = DifyService.build_chat_messages_url(base_url)
request_url = DifyService._build_chat_messages_url(base_url)
payload = {
'inputs': {},
'query': '系统连通性测试,请简短回复OK。',
+27 -5
View File
@@ -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),
+82 -22
View File
@@ -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
+46 -17
View File
@@ -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<HTMLElement | null>(null);
const kbOptions = ['企业知识库', 'ERP知识库'];
const chatScrollContainer = ref<HTMLElement | null>(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);
<div class="flex min-h-0 flex-1">
<div class="flex min-h-0 flex-1 flex-col">
<main
ref="chatScrollContainer"
class="flex-1 p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'space-y-2 overflow-y-auto scrollbar-thin md:space-y-6'"
>
@@ -1233,14 +1275,9 @@ const showChatRating = ref(false);
<template v-for="(msg, index) in messages" :key="index">
<div
v-if="shouldRenderMessage(msg)"
class="group mx-auto flex max-w-4xl gap-4 animate-slide-up mb-6"
class="group mx-auto flex max-w-4xl animate-slide-up mb-6"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
>
<!-- AI Avatar -->
<div v-if="msg.role === 'assistant'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-white shadow-sm shadow-brand-500/20">
<Sparkles class="h-4 w-4" />
</div>
<div
class="flex flex-col"
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
@@ -1530,18 +1567,10 @@ const showChatRating = ref(false);
</div>
</div>
<!-- User Avatar -->
<div v-if="msg.role === 'user'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand-600 text-white shadow-sm shadow-brand-500/20">
<User class="h-4 w-4" />
</div>
</div>
</template>
<div v-if="shouldShowThinkingBubble" class="mx-auto flex max-w-5xl gap-4">
<div class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 shadow-md shadow-brand-500/25">
<Bot class="h-5 w-5 text-white" />
</div>
<div v-if="shouldShowThinkingBubble" class="mx-auto flex max-w-5xl">
<div class="flex items-center gap-3 rounded-2xl rounded-tl-md border border-slate-200 bg-white/95 px-5 py-3 shadow-md dark:border-slate-700 dark:bg-slate-900/85">
<div class="flex gap-1">
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400"></span>