chatview优化
This commit is contained in:
1 parent
e2510c0565
commit
bf5f735404
3 files changed
+155
-44
No files matched your search
@@ -24,6 +24,7 @@ chat.py (/api/chat/completions)
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import requests
|
||||
@@ -37,6 +38,26 @@ from app.services.integration_api import IntegrationApiService
|
||||
class DifyService:
|
||||
"""Dify service wrapper."""
|
||||
|
||||
@staticmethod
|
||||
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
|
||||
"""
|
||||
Dify 只接受标准 UUID 会话 ID。
|
||||
本项目里 ERP Text2SQL 会生成 `erp_xxx` 形式的本地会话号,
|
||||
这类值不能继续透传给 Dify,否则会触发 400 invalid_param。
|
||||
"""
|
||||
value = str(conversation_id or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] ignore non-uuid conversation_id for dify: %s",
|
||||
value,
|
||||
)
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _build_chat_messages_url(base_url: str) -> str:
|
||||
"""
|
||||
@@ -90,6 +111,7 @@ class DifyService:
|
||||
# Prefer agent-specific base URL; fallback to global config.
|
||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||
url = DifyService._build_chat_messages_url(base_url)
|
||||
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
@@ -99,7 +121,7 @@ class DifyService:
|
||||
'inputs': {},
|
||||
'query': query,
|
||||
'response_mode': 'streaming',
|
||||
'conversation_id': conversation_id or '',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'user': str(user_id),
|
||||
}
|
||||
|
||||
@@ -110,7 +132,7 @@ class DifyService:
|
||||
getattr(agent, 'id', None),
|
||||
base_url,
|
||||
len(query or ''),
|
||||
conversation_id,
|
||||
normalized_conversation_id or conversation_id,
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
@@ -161,7 +183,7 @@ class DifyService:
|
||||
event,
|
||||
len(data.get('answer', '') or ''),
|
||||
bool(data.get('metadata')),
|
||||
data.get('conversation_id') or conversation_id,
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
if event == 'message':
|
||||
@@ -196,7 +218,7 @@ class DifyService:
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or conversation_id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=''.join(full_answer),
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
@@ -209,7 +231,7 @@ class DifyService:
|
||||
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 conversation_id,
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
len(''.join(full_answer)),
|
||||
len(retriever_resources),
|
||||
len(attribution_parts),
|
||||
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
from flask import current_app
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
class Text2SQLService:
|
||||
_schema_text = None
|
||||
@@ -568,28 +568,88 @@ class Text2SQLService:
|
||||
"""Yields SSE events to frontend just like DifyService"""
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"erp_{int(time.time())}"
|
||||
|
||||
# 1. Generate SQL
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n"
|
||||
sql = Text2SQLService.generate_sql(query)
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n"
|
||||
|
||||
# 2. Execute SQL
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
if columns == ["Error"] and rows and rows[0]:
|
||||
error_message = str(rows[0][0] or "")
|
||||
if Text2SQLService._is_repairable_sql_error(error_message):
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n"
|
||||
repaired_sql = Text2SQLService.repair_sql(query, sql, error_message)
|
||||
if repaired_sql and repaired_sql != sql:
|
||||
sql = repaired_sql
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
|
||||
# 3. Format result
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n"
|
||||
result_text = Text2SQLService.format_result(columns, rows, sql, query)
|
||||
try:
|
||||
# 1. Generate SQL
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n"
|
||||
stage_start = time.time()
|
||||
sql = Text2SQLService.generate_sql(query)
|
||||
generate_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] generate_sql done conversation_id=%s elapsed_ms=%s sql_preview=%s",
|
||||
final_conversation_id,
|
||||
generate_sql_ms,
|
||||
(sql or "")[:300],
|
||||
)
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n"
|
||||
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
# 2. Execute SQL
|
||||
stage_start = time.time()
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
execute_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] execute_sql done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s",
|
||||
final_conversation_id,
|
||||
execute_sql_ms,
|
||||
len(columns or []),
|
||||
len(rows or []),
|
||||
)
|
||||
if columns == ["Error"] and rows and rows[0]:
|
||||
error_message = str(rows[0][0] or "")
|
||||
if Text2SQLService._is_repairable_sql_error(error_message):
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n"
|
||||
repair_stage_start = time.time()
|
||||
repaired_sql = Text2SQLService.repair_sql(query, sql, error_message)
|
||||
repair_sql_ms = int((time.time() - repair_stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] repair_sql done conversation_id=%s elapsed_ms=%s sql_changed=%s",
|
||||
final_conversation_id,
|
||||
repair_sql_ms,
|
||||
bool(repaired_sql and repaired_sql != sql),
|
||||
)
|
||||
if repaired_sql and repaired_sql != sql:
|
||||
sql = repaired_sql
|
||||
stage_start = time.time()
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
execute_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] execute_sql retry done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s",
|
||||
final_conversation_id,
|
||||
execute_sql_ms,
|
||||
len(columns or []),
|
||||
len(rows or []),
|
||||
)
|
||||
|
||||
# 3. Format result
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n"
|
||||
stage_start = time.time()
|
||||
result_text = Text2SQLService.format_result(columns, rows, sql, query)
|
||||
format_result_ms = int((time.time() - stage_start) * 1000)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] format_result done conversation_id=%s elapsed_ms=%s total_ms=%s",
|
||||
final_conversation_id,
|
||||
format_result_ms,
|
||||
latency,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[text2sql] stream_chat failed conversation_id=%s query=%s",
|
||||
final_conversation_id,
|
||||
query,
|
||||
)
|
||||
error_data = {
|
||||
'event': 'error',
|
||||
'message': str(exc) or 'ERP 问数执行失败',
|
||||
'conversation_id': final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
|
||||
# Create ChatLog
|
||||
from app.models import ChatLog, db
|
||||
|
||||
Reference in new issue
Block a user