部署成功或失败发送企业微信通知

This commit is contained in:
sophie committed 2026-05-20 15:39:07 +08:00
1 parent 72642b981e
commit e0d91e53e7
3 files changed
+193 -14

No files matched your search

+47 -12
View File
@@ -23,6 +23,7 @@ chat.py (/api/chat/completions)
-> yield SSE events to frontend
"""
import json
import os
import time
import uuid
from typing import Any, List, Optional
@@ -37,6 +38,7 @@ from app.services.integration_api import IntegrationApiService
class DifyService:
"""Dify service wrapper."""
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
@staticmethod
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
@@ -290,7 +292,7 @@ class DifyService:
return {}
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
Stream chat completion from Dify and relay SSE events to caller.
@@ -329,7 +331,8 @@ class DifyService:
if current_app:
current_app.logger.info(
"[chat-stream] start user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
"[chat-stream] start request_id=%s user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
request_id,
user_id,
getattr(agent, 'id', None),
base_url,
@@ -338,6 +341,9 @@ class DifyService:
)
start_time = time.time()
first_token_at: float | None = None
message_count = 0
event_count = 0
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
@@ -348,7 +354,8 @@ class DifyService:
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 attempt=%s",
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
request_id,
response.status_code,
response.reason,
attempt,
@@ -360,7 +367,8 @@ class DifyService:
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",
"[chat-stream] dify bad response request_id=%s status=%s url=%s attempt=%s body=%s",
request_id,
response.status_code,
url,
attempt,
@@ -386,9 +394,13 @@ class DifyService:
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_count += 1
# Keep stream event logs behind an explicit switch to prevent
# flooding when global logger level is DEBUG.
if DifyService.VERBOSE_STREAM_LOG and current_app:
current_app.logger.debug(
"[chat-stream] event request_id=%s event=%s answer_len=%s has_metadata=%s conversation_id=%s",
request_id,
event,
len(data.get('answer', '') or ''),
bool(data.get('metadata')),
@@ -396,6 +408,16 @@ class DifyService:
)
if event == 'message':
message_count += 1
if first_token_at is None:
first_token_at = time.time()
if current_app:
current_app.logger.info(
"[chat-perf] first-token request_id=%s ttft_ms=%s attempt=%s",
request_id,
int((first_token_at - start_time) * 1000),
attempt,
)
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
@@ -405,12 +427,15 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end':
message_end_started = time.time()
if current_app:
current_app.logger.info(
"[source-link] message_end: collected retriever resources=%s",
"[source-link] message_end request_id=%s collected retriever_resources=%s",
request_id,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
enrich_done_at = time.time()
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
@@ -420,6 +445,7 @@ class DifyService:
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,
@@ -432,23 +458,32 @@ class DifyService:
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
db_write_done_at = time.time()
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,
"[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s",
request_id,
latency,
int((first_token_at - start_time) * 1000) if first_token_at else None,
int((message_end_started - first_token_at) * 1000) if first_token_at else None,
int((time.time() - message_end_started) * 1000),
int((enrich_done_at - message_end_started) * 1000),
int((db_write_done_at - db_write_started) * 1000),
event_count,
message_count,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
latency,
data.get('conversation_id') or normalized_conversation_id,
)
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)
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
if attempt < max_retries:
time.sleep(attempt * 2)
continue