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] = []
|
||||
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(
|
||||
|
||||
Reference in new issue
Block a user