From e0d91e53e7c0dda5fea808ba19e6328fb23e3a21 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Wed, 20 May 2026 15:39:07 +0800 Subject: [PATCH] =?UTF-8?q?=E9=83=A8=E7=BD=B2=E6=88=90=E5=8A=9F=E6=88=96?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E5=8F=91=E9=80=81=E4=BC=81=E4=B8=9A=E5=BE=AE?= =?UTF-8?q?=E4=BF=A1=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Jenkinsfile | 141 +++++++++++++++++++++++++++++++++++ backend/app/api/chat.py | 7 +- backend/app/services/dify.py | 59 ++++++++++++--- 3 files changed, 193 insertions(+), 14 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index d3351a7e..8acec369 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,3 +1,84 @@ +import groovy.json.JsonOutput + +// 企业微信群机器人部署通知(成功/失败/中止)。Webhook 完整 URL 存 Jenkins 凭据 WECOM_WEBHOOK_DEPLOY,勿写入 Git。 +// WeCom group-bot deploy notifications. Store webhook URL in Jenkins Secret text credential only. +def notifyWecomDeploy(Map opts) { + if ((env.DISABLE_DEPLOY_WECOM_NOTIFY ?: '').equalsIgnoreCase('true')) { + echo '[WeCom] DISABLE_DEPLOY_WECOM_NOTIFY=true,跳过通知' + return + } + + def credId = (opts.webhookCredId ?: env.WECOM_WEBHOOK_CRED ?: 'WECOM_WEBHOOK_DEPLOY').trim() + def envLabel = opts.envLabel ?: '部署环境' + def host = opts.host ?: '-' + def status = (opts.status ?: 'success').toString().toLowerCase() + def isSuccess = status == 'success' + def extraNote = (opts.extraNote ?: '').trim() + + try { + withCredentials([string(credentialsId: credId, variable: 'WECOM_WEBHOOK_URL')]) { + def webhookUrl = WECOM_WEBHOOK_URL?.trim() + if (!webhookUrl) { + echo "[WeCom] 凭据 ${credId} 为空,跳过通知" + return + } + + def shortCommit = env.GIT_COMMIT ? env.GIT_COMMIT.take(8) : '-' + def buildLink = env.BUILD_URL ?: '-' + def title = isSuccess ? "✅ ${envLabel} 部署成功" : "❌ ${envLabel} 部署失败" + def lines = [ + "## ${title}", + "> **分支**: ${env.BRANCH_NAME ?: '-'}", + "> **提交**: `${shortCommit}`", + "> **目标主机**: ${host}", + "> **构建**: [#${env.BUILD_NUMBER}](${buildLink})", + "> **变更**: 前端=${env.FRONTEND_CHANGED ?: '-'} 后端=${env.BACKEND_CHANGED ?: '-'} 配置=${env.DEPLOY_CONFIG_CHANGED ?: '-'}", + ] + if (env.FORCE_FULL_DEPLOY_USED == 'true') { + lines << '> **备注**: 强制全量部署' + } + if (env.REMOTE_DRIFT_DETECTED == 'true') { + lines << '> **备注**: 远端版本漂移触发部署' + } + if (extraNote) { + lines << "> **说明**: ${extraNote}" + } + if (!isSuccess) { + lines << '> **处理**: 请打开 Jenkins 构建日志排查失败步骤' + } + + def payload = [ + msgtype: 'markdown', + markdown: [content: lines.join('\n')], + ] + writeFile(file: 'wecom-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload)) + + def httpCode = sh( + returnStdout: true, + script: ''' + set +e + code=$(curl -sS -o wecom-notify-response.txt -w "%{http_code}" \ + -X POST "$WECOM_WEBHOOK_URL" \ + -H "Content-Type: application/json" \ + -d @wecom-notify-payload.json) + echo "[WeCom] HTTP ${code}" >&2 + cat wecom-notify-response.txt >&2 || true + echo "${code}" + ''' + ).trim() + + def resp = readFile('wecom-notify-response.txt').trim() + if (httpCode == '200' && resp.contains('"errcode":0')) { + echo '[WeCom] 通知已发送' + } else { + echo "[WeCom] 发送可能失败,HTTP=${httpCode},响应=${resp}" + } + } + } catch (Exception e) { + echo "[WeCom] 通知发送异常(不影响构建结果): ${e.message}" + } +} + pipeline { agent any @@ -242,6 +323,36 @@ pipeline { } echo "[Deploy Test] done" } + post { + success { + script { + notifyWecomDeploy( + envLabel: '测试环境', + host: env.TEST_DEPLOY_HOST, + status: 'success', + ) + } + } + failure { + script { + notifyWecomDeploy( + envLabel: '测试环境', + host: env.TEST_DEPLOY_HOST, + status: 'failure', + ) + } + } + aborted { + script { + notifyWecomDeploy( + envLabel: '测试环境', + host: env.TEST_DEPLOY_HOST, + status: 'failure', + extraNote: '阶段已中止(可能为人工取消)', + ) + } + } + } } stage('Deploy Prod') { @@ -301,6 +412,36 @@ pipeline { } echo "[Deploy Prod] done" } + post { + success { + script { + notifyWecomDeploy( + envLabel: '生产环境', + host: env.PROD_DEPLOY_HOST, + status: 'success', + ) + } + } + failure { + script { + notifyWecomDeploy( + envLabel: '生产环境', + host: env.PROD_DEPLOY_HOST, + status: 'failure', + ) + } + } + aborted { + script { + notifyWecomDeploy( + envLabel: '生产环境', + host: env.PROD_DEPLOY_HOST, + status: 'failure', + extraNote: '阶段已中止(可能为未确认生产部署或人工取消)', + ) + } + } + } } } diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index c61350c1..37231092 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -11,6 +11,7 @@ import mimetypes import tempfile import os import subprocess +import uuid from urllib.parse import urlparse import requests @@ -738,13 +739,15 @@ def chat_completions(): conversation_id = data.get('conversation_id') # 知识库类型 kb_type = data.get('kb_type', '企业知识库') + request_id = uuid.uuid4().hex[:12] # 从全局 g 中获取装饰器注入的用户和 Agent 对象 user = getattr(g, 'current_user', None) agent = getattr(g, 'current_agent', None) current_app.logger.info( - "[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s", + "[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s", + request_id, getattr(user, 'id', None), getattr(agent, 'id', None), len(query or ''), @@ -776,7 +779,7 @@ def chat_completions(): if HRLeaveSQLServerService.supports(query): generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id) else: - generator = DifyService.stream_chat(query, user.id, agent, conversation_id) + generator = DifyService.stream_chat(query, user.id, agent, conversation_id, request_id=request_id) # 返回 SSE 响应,mimetype 设为 text/event-stream return Response( diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index ca549d66..c9390516 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -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 = "" 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