feat(rohs-check): 新增 RoHS 检核执行进度中增加 Excel 下载功能及相关配置

This commit is contained in:
hugo committed 2026-06-11 17:35:16 +08:00
1 parent ee39270069
commit 599d492895
14 files changed
+845 -272

No files matched your search

+161 -56
View File
@@ -27,7 +27,7 @@ import os
import time
import uuid
from datetime import datetime, timedelta
from threading import Lock
from threading import Lock, Thread
from typing import Any, List, Optional
import requests
@@ -567,78 +567,76 @@ class DifyService:
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
chat_logged = False
chat_persist_started = False
has_sent_answer = False
def persist_stream_chat(data: dict, event_name: str) -> None:
nonlocal chat_logged
if chat_logged:
persist_stream_chat_async(data, event_name)
def persist_stream_chat_async(data: dict, event_name: str) -> None:
nonlocal chat_persist_started
if chat_persist_started:
return
chat_persist_started = True
if data.get('answer'):
full_answer.append(data.get('answer', ''))
app_obj = current_app._get_current_object() if current_app else None
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
resources_snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
attribution_snapshot = list(attribution_parts)
answer_snapshot = build_final_answer_text(persist_data, event_name)
latency_snapshot = int((time.time() - start_time) * 1000)
def _persist() -> None:
if not app_obj:
return
with app_obj.app_context():
DifyService._persist_stream_chat_record(
data=persist_data,
event_name=event_name,
request_id=request_id,
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
normalized_conversation_id=normalized_conversation_id,
query=query,
answer_text=answer_snapshot,
latency=latency_snapshot,
retriever_resources=resources_snapshot,
attribution_parts=attribution_snapshot,
)
Thread(target=_persist, daemon=True, name=f"dify-chat-persist-{request_id or 'unknown'}").start()
def build_final_answer_text(data: dict, event_name: str) -> str:
answer_text = ''.join(full_answer).strip()
if data.get('answer'):
answer_text = (answer_text + str(data.get('answer') or '')).strip()
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'text', 'result'):
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text:
for value in outputs.values():
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
return answer_text
if not answer_text and not str(query or '').strip():
return
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
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
chat_logged = True
if current_app:
current_app.logger.info(
"[chat-perf] persisted request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
data.get('conversation_id') or normalized_conversation_id,
)
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 300)) as response:
connect_timeout = max(1, int(getattr(Config, "DIFY_CHAT_CONNECT_TIMEOUT_SECONDS", 5) or 5))
read_timeout = max(5, int(getattr(Config, "DIFY_CHAT_READ_TIMEOUT_SECONDS", 30) or 30))
if attempt == 1:
yield f"data: {json.dumps({'event': 'upstream_start', 'message': '正在连接 Dify'}, ensure_ascii=False)}\n\n"
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(connect_timeout, read_timeout)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
@@ -665,6 +663,7 @@ class DifyService:
time.sleep(attempt * 2)
continue
response.raise_for_status()
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
for line in response.iter_lines():
if not line:
@@ -696,6 +695,8 @@ class DifyService:
if event == 'message':
message_count += 1
if data.get('answer'):
has_sent_answer = True
if first_token_at is None:
first_token_at = time.time()
if current_app:
@@ -709,20 +710,66 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event in ('message_end', 'workflow_finished') or data.get('answer'):
has_sent_answer = True
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'workflow_finished' and not data.get('answer'):
final_answer = build_final_answer_text(data, event)
if final_answer:
data['answer'] = final_answer
data['replace_answer'] = True
if event in ('message_end', 'workflow_finished'):
persist_stream_chat(data, event)
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
if event in ('message_end', 'workflow_finished'):
break
break
except requests.exceptions.RequestException as e:
if current_app:
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
if attempt < max_retries:
is_timeout = isinstance(e, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout))
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
if current_app:
current_app.logger.warning(
"[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently",
request_id,
attempt,
)
persist_stream_chat(
{
'event': 'message_end',
'conversation_id': normalized_conversation_id,
'answer': ''.join(full_answer).strip(),
'metadata': {},
},
'message_end',
)
break
if not is_timeout and attempt < max_retries:
time.sleep(attempt * 2)
continue
error_msg = json.dumps({'event': 'error', 'message': str(e)})
if isinstance(e, requests.exceptions.ReadTimeout):
message = (
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
)
elif isinstance(e, requests.exceptions.ConnectTimeout):
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
else:
message = str(e)
persist_stream_chat(
{
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'metadata': {},
},
'error',
)
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\n\n"
@staticmethod
@@ -775,6 +822,64 @@ class DifyService:
return None
@staticmethod
def _persist_stream_chat_record(
*,
data: dict,
event_name: str,
request_id: str | None,
user_id: int,
agent_id: int,
session_id: str | None,
normalized_conversation_id: str | None,
query: str,
answer_text: str,
latency: int,
retriever_resources: List[Any],
attribution_parts: List[str],
) -> None:
if not answer_text and not str(query or '').strip():
return
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent_id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id and current_app:
current_app.logger.info(
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
data.get('conversation_id') or normalized_conversation_id,
)
@staticmethod
def _normalize_resources(resources):
"""