Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-05-20 09:36:20 +08:00
commit 4d05b5674e
3 files changed
+187 -115

No files matched your search

+100 -95
View File
@@ -342,113 +342,118 @@ class DifyService:
retriever_resources: List[Any] = [] retriever_resources: List[Any] = []
attribution_parts: List[str] = [] attribution_parts: List[str] = []
try: max_retries = 3
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response: for attempt in range(1, max_retries + 1):
if current_app: try:
current_app.logger.info( with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
"[chat-stream] dify response status=%s reason=%s",
response.status_code,
response.reason,
)
if not response.ok and current_app:
try:
error_body = response.text[:2000]
except Exception:
error_body = "<failed to read response body>"
current_app.logger.error(
"[chat-stream] dify bad response status=%s url=%s payload=%s body=%s",
response.status_code,
url,
json.dumps(payload, ensure_ascii=False),
error_body,
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
decoded_line = line.decode('utf-8')
if not decoded_line.startswith('data: '):
continue
raw_json = decoded_line[6:]
try:
data = json.loads(raw_json)
except json.JSONDecodeError:
continue
event = data.get('event')
if current_app: if current_app:
current_app.logger.info( current_app.logger.info(
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s", "[chat-stream] dify response status=%s reason=%s attempt=%s",
event, response.status_code,
len(data.get('answer', '') or ''), response.reason,
bool(data.get('metadata')), attempt,
data.get('conversation_id') or normalized_conversation_id,
) )
if not response.ok and current_app:
retryable = response.status_code in (404, 502, 503, 504)
try:
error_body = response.text[:2000]
except Exception:
error_body = "<failed to read response body>"
current_app.logger.error(
"[chat-stream] dify bad response status=%s url=%s attempt=%s body=%s",
response.status_code,
url,
attempt,
error_body,
)
if retryable and attempt < max_retries:
time.sleep(attempt * 2)
continue
response.raise_for_status()
if event == 'message': for line in response.iter_lines():
full_answer.append(data.get('answer', '')) if not line:
DifyService._collect_metadata(retriever_resources, attribution_parts, data) continue
elif event in ('message_end', 'agent_message', 'workflow_finished'): decoded_line = line.decode('utf-8')
# Keep metadata from non-message events, but avoid appending if not decoded_line.startswith('data: '):
# intermediate workflow/agent outputs into final user answer. continue
if event == 'message_end' and data.get('answer'):
raw_json = decoded_line[6:]
try:
data = json.loads(raw_json)
except json.JSONDecodeError:
continue
event = data.get('event')
if current_app:
current_app.logger.info(
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s",
event,
len(data.get('answer', '') or ''),
bool(data.get('metadata')),
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'message':
full_answer.append(data.get('answer', '')) full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data) DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end': elif event in ('message_end', 'agent_message', 'workflow_finished'):
if current_app: if event == 'message_end' and data.get('answer'):
current_app.logger.info( full_answer.append(data.get('answer', ''))
"[source-link] message_end: collected retriever resources=%s", DifyService._collect_metadata(retriever_resources, attribution_parts, data)
len(retriever_resources),
)
# Resolve original source file URLs from external integration API.
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') or {} if event == 'message_end':
metadata['retriever_resources'] = retriever_resources if current_app:
data['metadata'] = metadata current_app.logger.info(
data['retriever_resources'] = retriever_resources "[source-link] message_end: collected retriever resources=%s",
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
latency = int((time.time() - start_time) * 1000) metadata = data.get('metadata') or {}
usage = metadata.get('usage', {}) or {} metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
with current_app.app_context(): latency = int((time.time() - start_time) * 1000)
chat_log_id = DifyService._log_chat( usage = metadata.get('usage', {}) or {}
user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=''.join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id:
data['chat_log_id'] = chat_log_id
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 normalized_conversation_id,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
latency,
)
# Pass-through SSE event (after optional enrichment). with current_app.app_context():
# SSE frame delimiter must be real newlines, not literal "\n". chat_log_id = DifyService._log_chat(
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n" user_id=user_id,
agent_id=agent.id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=''.join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id:
data['chat_log_id'] = chat_log_id
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 normalized_conversation_id,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
latency,
)
except requests.exceptions.RequestException as e: yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
if current_app: break
current_app.logger.exception("[chat-stream] request exception: %s", e) except requests.exceptions.RequestException as e:
error_msg = json.dumps({'event': 'error', 'message': str(e)}) if current_app:
yield f"data: {error_msg}\n\n" current_app.logger.exception("[chat-stream] request exception attempt=%s: %s", attempt, e)
if attempt < max_retries:
time.sleep(attempt * 2)
continue
error_msg = json.dumps({'event': 'error', 'message': str(e)})
yield f"data: {error_msg}\n\n"
@staticmethod @staticmethod
def _log_chat( def _log_chat(
+86 -19
View File
@@ -13,7 +13,7 @@
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue'; import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat'; import { useChat } from '../composables/useChat';
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search } 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, Search, LayoutGrid } from 'lucide-vue-next';
import { marked } from 'marked'; import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { config } from '../config'; import { config } from '../config';
@@ -34,6 +34,7 @@ const kbMenuRef = ref<HTMLElement | null>(null);
const kbOptions = ['企业知识库', 'ERP知识库']; const kbOptions = ['企业知识库', 'ERP知识库'];
const chatScrollContainer = ref<HTMLElement | null>(null); const chatScrollContainer = ref<HTMLElement | null>(null);
let scrollToBottomFrame: number | null = null; let scrollToBottomFrame: number | null = null;
let wasThinking = false;
marked.setOptions({ marked.setOptions({
gfm: true, gfm: true,
@@ -571,7 +572,9 @@ const copiedIndex = ref<number | null>(null);
const { messages, isThinking, conversationId, sendMessage } = useChat(); const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref(''); const input = ref('');
const currentAgent = ref<any>(null); const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string }>>([]);
const showGeneralFeedbackDialog = ref(false); const showGeneralFeedbackDialog = ref(false);
const showAgentPanel = ref(true);
const OA_BASE_URL = 'http://oa.well-trust.com:8888'; const OA_BASE_URL = 'http://oa.well-trust.com:8888';
const OA_LOGIN_URL = `${OA_BASE_URL}/login/Login.jsp?logintype=1`; const OA_LOGIN_URL = `${OA_BASE_URL}/login/Login.jsp?logintype=1`;
@@ -1125,6 +1128,39 @@ const scrollChatToBottom = async () => {
}); });
}; };
const scrollToMessage = async (index: number) => {
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
const el = container.querySelector(`[data-msg-index="${index}"]`) as HTMLElement | null;
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const scrollToUserQuestion = async () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
await nextTick();
await nextTick();
const container = chatScrollContainer.value;
if (!container) return;
let lastUserIndex = -1;
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return;
const el = container.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const scheduleScrollChatToBottom = () => { const scheduleScrollChatToBottom = () => {
if (scrollToBottomFrame !== null) { if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame); window.cancelAnimationFrame(scrollToBottomFrame);
@@ -1265,7 +1301,6 @@ const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value; const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value) return; if (!content.trim() || isThinking.value) return;
// Clear input if sending from input box (not resending/regenerating)
if (typeof textOrEvent !== 'string') input.value = ''; if (typeof textOrEvent !== 'string') input.value = '';
if (isStrongLeaveIntent(content)) { if (isStrongLeaveIntent(content)) {
@@ -1273,13 +1308,12 @@ const handleSend = async (textOrEvent?: string | Event) => {
return; return;
} }
const userMsgIndex = messages.value.length;
await sendMessage(content, agentId, selectedKb.value); await sendMessage(content, agentId, selectedKb.value);
// 发送完成后刷新历史记录,确保新会话出现
if (!conversationId.value && history.value.length === 0) { if (!conversationId.value && history.value.length === 0) {
await loadHistory(); await loadHistory();
} else if (conversationId.value) { } else if (conversationId.value) {
// Check if current conversation is in history, if not, reload
const exists = history.value.some(h => h.conversation_id === conversationId.value); const exists = history.value.some(h => h.conversation_id === conversationId.value);
if (!exists) await loadHistory(); if (!exists) await loadHistory();
} }
@@ -1535,6 +1569,28 @@ const loadAgent = async () => {
} }
}; };
const loadUserAgents = async () => {
try {
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
if (res.ok) {
const agents = await res.json();
userAgents.value = Array.isArray(agents) ? agents.filter((a: any) => a.id !== agentId) : [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
}
} catch (e) {
userAgents.value = [];
showAgentPanel.value = false;
}
};
const switchToAgent = (agent: { id: number; name: string }) => {
if (agent.id === agentId) return;
const url = router.resolve(`/chat/${agent.id}`).href;
window.open(url, '_blank');
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送 // 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => { onMounted(async () => {
document.addEventListener('mousedown', handleDocumentPointerDown); document.addEventListener('mousedown', handleDocumentPointerDown);
@@ -1542,6 +1598,7 @@ onMounted(async () => {
window.addEventListener('resize', syncViewportWidth); window.addEventListener('resize', syncViewportWidth);
await syncCurrentUserProfile(); await syncCurrentUserProfile();
await loadAgent(); await loadAgent();
await loadUserAgents();
await loadHistory(); await loadHistory();
@@ -1574,7 +1631,13 @@ watch(
conversationId: conversationId.value || '', conversationId: conversationId.value || '',
}), }),
() => { () => {
scheduleScrollChatToBottom(); if (wasThinking && !isThinking.value) {
wasThinking = false;
scrollToUserQuestion();
} else {
if (isThinking.value) wasThinking = true;
scheduleScrollChatToBottom();
}
}, },
{ deep: false }, { deep: false },
); );
@@ -1630,7 +1693,7 @@ const showChatRating = ref(false);
<div class="flex items-center justify-between p-4"> <div class="flex items-center justify-between p-4">
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">AI</div> <div class="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">AI</div>
<span class="font-bold text-slate-800 dark:text-slate-100">Hxops Alagent</span> <span class="font-bold text-slate-800 dark:text-slate-100">{{ currentAgent?.name || 'AI' }}</span>
</div> </div>
<button @click="isSidebarCollapsed = true" class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200"> <button @click="isSidebarCollapsed = true" class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
<PanelLeftClose class="h-5 w-5" /> <PanelLeftClose class="h-5 w-5" />
@@ -1680,21 +1743,23 @@ const showChatRating = ref(false);
</div> </div>
<div class="mt-auto flex flex-col p-4"> <div class="mt-auto flex flex-col p-4">
<!-- Upgrade card disabled for now. Keep code for future rollout. <div v-if="userAgents.length > 0 && showAgentPanel" class="mb-4 rounded-2xl border border-slate-200 bg-slate-50/70 p-3 dark:border-slate-700 dark:bg-slate-800/60">
<div class="mb-4 rounded-2xl border border-brand-100 bg-brand-50/70 p-4 dark:border-brand-500/20 dark:bg-brand-900/10"> <div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-slate-500 dark:text-slate-400">
<div class="mb-2 flex items-center gap-1 font-bold text-brand-700 dark:text-brand-300"> <LayoutGrid class="h-3.5 w-3.5" /> 智能体
<Crown class="h-4 w-4" /> 专业版 </div>
<div class="grid grid-cols-2 gap-1.5">
<button
v-for="agent in userAgents"
:key="agent.id"
@click="switchToAgent(agent)"
class="flex items-center justify-center gap-1.5 rounded-xl px-2 py-2 text-xs font-medium text-slate-600 transition-colors hover:bg-white hover:shadow-sm dark:text-slate-200 dark:hover:bg-slate-700/50 truncate"
>
<div v-if="agent.icon_url" class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat" :style="{ backgroundImage: `url(${agent.icon_url})` }"></div>
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600 dark:bg-brand-900/30 dark:text-brand-400">{{ agent.name.charAt(0) }}</div>
<span class="truncate">{{ agent.name }}</span>
</button>
</div> </div>
<ul class="mb-3 space-y-1 text-[11px] text-slate-600 dark:text-slate-300">
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 统一Agent知识库入口</li>
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 优化Chat界面及交互</li>
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-brand-400"></div> 修改文档预览bug等</li>
</ul>
<button class="w-full rounded-xl bg-brand-600 py-2 text-xs font-medium text-white shadow-md shadow-brand-500/20 transition-colors hover:bg-brand-700 dark:bg-brand-500 dark:hover:bg-brand-400">
🚀 升级说明
</button>
</div> </div>
-->
<!-- Bottom Icons --> <!-- Bottom Icons -->
<div class="flex items-center justify-between text-slate-400 relative" ref="userMenuRef"> <div class="flex items-center justify-between text-slate-400 relative" ref="userMenuRef">
@@ -1722,6 +1787,7 @@ const showChatRating = ref(false);
</div> </div>
<div class="flex gap-3"> <div class="flex gap-3">
<button @click="userAgents.length === 0 ? undefined : (showAgentPanel = !showAgentPanel)" :class="showAgentPanel && userAgents.length > 0 ? 'text-brand-600 dark:text-brand-400' : ''" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" :title="userAgents.length === 0 ? '暂无可用智能体' : (showAgentPanel ? '收起智能体' : '展开智能体')"><LayoutGrid class="h-4 w-4" /></button>
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Heart class="h-4 w-4" /></button> <button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Heart class="h-4 w-4" /></button>
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Bell class="h-4 w-4" /></button> <button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Bell class="h-4 w-4" /></button>
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-4 w-4" /></button> <button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-4 w-4" /></button>
@@ -1768,6 +1834,7 @@ const showChatRating = ref(false);
<template v-for="(msg, index) in messages" :key="index"> <template v-for="(msg, index) in messages" :key="index">
<div <div
v-if="shouldRenderMessage(msg)" v-if="shouldRenderMessage(msg)"
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up" class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'" :class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
> >
+1 -1
View File
@@ -1470,7 +1470,7 @@ onMounted(async () => {
<Bot class="h-6 w-6" /> <Bot class="h-6 w-6" />
</div> </div>
<div class="min-w-0"> <div class="min-w-0">
<div class="text-2xl font-extrabold tracking-tight text-[#14213d]">Hxops</div> <div class="text-2xl font-extrabold tracking-tight text-[#14213d]">和信AI</div>
<div class="truncate text-xs font-medium text-slate-400"> <div class="truncate text-xs font-medium text-slate-400">
{{ currentUser?.username }} / {{ currentUser?.role }} {{ currentUser?.username }} / {{ currentUser?.role }}
</div> </div>