chat回复滑动的起始位置

This commit is contained in:
runny committed 2026-05-20 09:15:10 +08:00
1 parent 316b8f326e
commit d473ca9a22
2 files changed
+143 -99

No files matched your search

+100 -95
View File
@@ -342,113 +342,118 @@ class DifyService:
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
if current_app:
current_app.logger.info(
"[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')
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
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,
"[chat-stream] dify response status=%s reason=%s attempt=%s",
response.status_code,
response.reason,
attempt,
)
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':
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
for line in response.iter_lines():
if not line:
continue
elif event in ('message_end', 'agent_message', 'workflow_finished'):
# Keep metadata from non-message events, but avoid appending
# intermediate workflow/agent outputs into final user answer.
if event == 'message_end' and data.get('answer'):
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:
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', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end':
if current_app:
current_app.logger.info(
"[source-link] message_end: collected retriever resources=%s",
len(retriever_resources),
)
# Resolve original source file URLs from external integration API.
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event == 'message_end' and data.get('answer'):
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
if event == 'message_end':
if current_app:
current_app.logger.info(
"[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)
usage = metadata.get('usage', {}) or {}
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
with current_app.app_context():
chat_log_id = DifyService._log_chat(
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,
)
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
# Pass-through SSE event (after optional enrichment).
# SSE frame delimiter must be real newlines, not literal "\n".
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
with current_app.app_context():
chat_log_id = DifyService._log_chat(
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:
if current_app:
current_app.logger.exception("[chat-stream] request exception: %s", e)
error_msg = json.dumps({'event': 'error', 'message': str(e)})
yield f"data: {error_msg}\n\n"
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
break
except requests.exceptions.RequestException as e:
if current_app:
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
def _log_chat(
+43 -4
View File
@@ -34,6 +34,7 @@ const kbMenuRef = ref<HTMLElement | null>(null);
const kbOptions = ['企业知识库', 'ERP知识库'];
const chatScrollContainer = ref<HTMLElement | null>(null);
let scrollToBottomFrame: number | null = null;
let wasThinking = false;
marked.setOptions({
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 = () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
@@ -1267,7 +1301,6 @@ const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value) return;
// Clear input if sending from input box (not resending/regenerating)
if (typeof textOrEvent !== 'string') input.value = '';
if (isStrongLeaveIntent(content)) {
@@ -1275,13 +1308,12 @@ const handleSend = async (textOrEvent?: string | Event) => {
return;
}
const userMsgIndex = messages.value.length;
await sendMessage(content, agentId, selectedKb.value);
// 发送完成后刷新历史记录,确保新会话出现
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
} 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);
if (!exists) await loadHistory();
}
@@ -1599,7 +1631,13 @@ watch(
conversationId: conversationId.value || '',
}),
() => {
scheduleScrollChatToBottom();
if (wasThinking && !isThinking.value) {
wasThinking = false;
scrollToUserQuestion();
} else {
if (isThinking.value) wasThinking = true;
scheduleScrollChatToBottom();
}
},
{ deep: false },
);
@@ -1796,6 +1834,7 @@ const showChatRating = ref(false);
<template v-for="(msg, index) in messages" :key="index">
<div
v-if="shouldRenderMessage(msg)"
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
>