chat回复滑动的起始位置
This commit is contained in:
1 parent
316b8f326e
commit
d473ca9a22
2 files changed
+143
-99
No files matched your search
+100
-95
@@ -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(
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -1127,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);
|
||||||
@@ -1267,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)) {
|
||||||
@@ -1275,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();
|
||||||
}
|
}
|
||||||
@@ -1599,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 },
|
||||||
);
|
);
|
||||||
@@ -1796,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'"
|
||||||
>
|
>
|
||||||
|
|||||||
Reference in new issue
Block a user