perf(固资): 优化固资查询结果过多分页加载;优化一些查询状态中文显示问题;
This commit is contained in:
1 parent
0a647a0b79
commit
96cc3913fc
5 files changed
+483
-45
No files matched your search
@@ -983,6 +983,60 @@ def save_local_message():
|
|||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||||
|
|
||||||
|
@chat_bp.route('/query-preview/<int:chat_log_id>', methods=['GET'])
|
||||||
|
@require_agent_permission
|
||||||
|
def get_chat_query_preview(chat_log_id: int):
|
||||||
|
page = request.args.get('page', type=int) or 1
|
||||||
|
page_size = request.args.get('page_size', type=int) or 100
|
||||||
|
page = max(1, page)
|
||||||
|
page_size = max(1, min(200, page_size))
|
||||||
|
|
||||||
|
log = db.session.query(ChatLog).filter(
|
||||||
|
ChatLog.id == chat_log_id,
|
||||||
|
ChatLog.user_id == getattr(g.current_user, 'id', 0),
|
||||||
|
ChatLog.agent_id == getattr(g.current_agent, 'id', 0),
|
||||||
|
).first()
|
||||||
|
if not log:
|
||||||
|
raise NotFoundError('query preview not found')
|
||||||
|
|
||||||
|
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||||
|
if payload.get('kind') != 'text2sql_result_preview':
|
||||||
|
raise ValidationError('current message does not support query preview')
|
||||||
|
|
||||||
|
sql = str(payload.get('sql') or '').strip()
|
||||||
|
query = str(payload.get('query') or log.query or '').strip()
|
||||||
|
if not sql:
|
||||||
|
raise ValidationError('query preview sql is missing')
|
||||||
|
|
||||||
|
from app.services.text2sql import Text2SQLService
|
||||||
|
total_count = payload.get('total_count')
|
||||||
|
try:
|
||||||
|
total_count = int(total_count) if total_count is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
total_count = None
|
||||||
|
|
||||||
|
columns, rows, resolved_total = Text2SQLService.get_preview_page(
|
||||||
|
sql=sql,
|
||||||
|
query=query,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
agent=g.current_agent,
|
||||||
|
total_count=total_count,
|
||||||
|
)
|
||||||
|
if columns == ["Error"]:
|
||||||
|
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
|
||||||
|
|
||||||
|
total = resolved_total if resolved_total is not None else len(rows)
|
||||||
|
return jsonify({
|
||||||
|
'columns': columns,
|
||||||
|
'rows': [list(row) for row in rows],
|
||||||
|
'page': page,
|
||||||
|
'page_size': page_size,
|
||||||
|
'total': total,
|
||||||
|
'has_more': page * page_size < total,
|
||||||
|
'query': query,
|
||||||
|
})
|
||||||
|
|
||||||
@chat_bp.route('/completions', methods=['POST'])
|
@chat_bp.route('/completions', methods=['POST'])
|
||||||
@require_agent_permission
|
@require_agent_permission
|
||||||
def chat_completions():
|
def chat_completions():
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ class Text2SQLService:
|
|||||||
"FAJ22": "存放营运中心",
|
"FAJ22": "存放营运中心",
|
||||||
"FAJ25": "取得日期",
|
"FAJ25": "取得日期",
|
||||||
"FAJ26": "入账日期",
|
"FAJ26": "入账日期",
|
||||||
|
"FAJ43": "资产状态",
|
||||||
"FAB02": "类型名称",
|
"FAB02": "类型名称",
|
||||||
"FAF02": "存放位置名称",
|
"FAF02": "存放位置名称",
|
||||||
"GEN01": "员工编号",
|
"GEN01": "员工编号",
|
||||||
@@ -70,6 +71,36 @@ class Text2SQLService:
|
|||||||
"GEM01": "部门编号",
|
"GEM01": "部门编号",
|
||||||
"GEM02": "部门名称",
|
"GEM02": "部门名称",
|
||||||
}
|
}
|
||||||
|
_ASSET_VALUE_MAPPINGS = {
|
||||||
|
"资产性质": {
|
||||||
|
"1": "有形资产",
|
||||||
|
"2": "无形资产",
|
||||||
|
"3": "土地",
|
||||||
|
"4": "递耗资产",
|
||||||
|
"5": "费用",
|
||||||
|
},
|
||||||
|
"资产状态": {
|
||||||
|
"0": "取得",
|
||||||
|
"1": "资本化",
|
||||||
|
"2": "折旧中",
|
||||||
|
"3": "外送",
|
||||||
|
"4": "折毕",
|
||||||
|
"5": "出售",
|
||||||
|
"6": "销账",
|
||||||
|
"7": "折旧再提",
|
||||||
|
"8": "改良",
|
||||||
|
"9": "重估",
|
||||||
|
"X": "被资本",
|
||||||
|
"Z": "停用",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ASSET_FALLBACK_NAME_COLUMNS = {
|
||||||
|
"保管人": ("保管人姓名", "员工姓名"),
|
||||||
|
"保管人工号": ("保管人姓名", "员工姓名"),
|
||||||
|
"保管部门": ("保管部门名称", "部门名称"),
|
||||||
|
"存放位置": ("存放位置名称",),
|
||||||
|
"资产类型": ("资产类型名称", "类型名称"),
|
||||||
|
}
|
||||||
_ASSET_PERSON_PATTERN = re.compile(
|
_ASSET_PERSON_PATTERN = re.compile(
|
||||||
r"(?:保管人|员工|人员|姓名|用户|使用人|归属人)\s*(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20})"
|
r"(?:保管人|员工|人员|姓名|用户|使用人|归属人)\s*(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_-]{2,20})"
|
||||||
)
|
)
|
||||||
@@ -689,6 +720,43 @@ ORDER BY faj.faj02
|
|||||||
localized.append(cls._ASSET_COLUMN_LABELS.get(raw_name.upper(), raw_name))
|
localized.append(cls._ASSET_COLUMN_LABELS.get(raw_name.upper(), raw_name))
|
||||||
return localized
|
return localized
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _translate_asset_display_value(cls, display_name: str, value) -> str:
|
||||||
|
text = cls._stringify_value(value)
|
||||||
|
mapping = cls._ASSET_VALUE_MAPPINGS.get(str(display_name or "").strip())
|
||||||
|
if not mapping:
|
||||||
|
return text
|
||||||
|
return mapping.get(text.strip().upper(), mapping.get(text.strip(), text))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _localize_asset_rows(cls, columns, rows, query: str, sql: str, agent=None):
|
||||||
|
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
|
||||||
|
return rows
|
||||||
|
display_columns = cls._localize_asset_columns(columns, query, sql, agent=agent)
|
||||||
|
index_map = {str(name or "").strip(): idx for idx, name in enumerate(display_columns)}
|
||||||
|
localized_rows = []
|
||||||
|
for row in rows or []:
|
||||||
|
row_values = list(row)
|
||||||
|
display_values = []
|
||||||
|
for idx, display_name in enumerate(display_columns):
|
||||||
|
raw_value = row_values[idx] if idx < len(row_values) else None
|
||||||
|
fallback_columns = cls._ASSET_FALLBACK_NAME_COLUMNS.get(display_name, ())
|
||||||
|
fallback_value = None
|
||||||
|
for fallback_column in fallback_columns:
|
||||||
|
fallback_idx = index_map.get(fallback_column)
|
||||||
|
if fallback_idx is None or fallback_idx >= len(row_values):
|
||||||
|
continue
|
||||||
|
candidate = cls._stringify_value(row_values[fallback_idx]).strip()
|
||||||
|
if candidate and candidate != "NULL":
|
||||||
|
fallback_value = candidate
|
||||||
|
break
|
||||||
|
if fallback_value:
|
||||||
|
display_values.append(fallback_value)
|
||||||
|
continue
|
||||||
|
display_values.append(cls._translate_asset_display_value(display_name, raw_value))
|
||||||
|
localized_rows.append(display_values)
|
||||||
|
return localized_rows
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _is_aggregate_sql(sql: str) -> bool:
|
def _is_aggregate_sql(sql: str) -> bool:
|
||||||
return bool(re.search(r"(?is)\b(count|sum|avg|min|max)\s*\(", sql or ""))
|
return bool(re.search(r"(?is)\b(count|sum|avg|min|max)\s*\(", sql or ""))
|
||||||
@@ -753,6 +821,69 @@ ORDER BY faj.faj02
|
|||||||
"- 异常提醒:当前结果未体现明显异常。"
|
"- 异常提醒:当前结果未体现明显异常。"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _sanitize_sql_text(cls, sql: str) -> str:
|
||||||
|
return str(sql or "").strip().rstrip(";")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_paged_query_sql(cls, sql: str, limit: int, offset: int = 0) -> str:
|
||||||
|
safe_sql = cls._sanitize_sql_text(sql)
|
||||||
|
upper_bound = max(0, int(offset)) + max(1, int(limit))
|
||||||
|
lower_bound = max(0, int(offset))
|
||||||
|
return (
|
||||||
|
"SELECT * FROM ("
|
||||||
|
"SELECT preview_data__.*, ROWNUM AS preview_rownum__ "
|
||||||
|
f"FROM ({safe_sql}) preview_data__ "
|
||||||
|
f"WHERE ROWNUM <= {upper_bound}"
|
||||||
|
f") WHERE preview_rownum__ > {lower_bound}"
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _build_generic_total_count_sql(cls, sql: str) -> str:
|
||||||
|
safe_sql = cls._sanitize_sql_text(sql)
|
||||||
|
return f"SELECT COUNT(*) AS total_count FROM ({safe_sql}) preview_total__"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _execute_sql_internal(cls, sql: str):
|
||||||
|
try:
|
||||||
|
import oracledb
|
||||||
|
except ImportError:
|
||||||
|
return None, None, ["Error"], [["oracledb is not installed"]]
|
||||||
|
|
||||||
|
user = "EXT_VIEW_USER"
|
||||||
|
password = "extviewuser"
|
||||||
|
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||||
|
|
||||||
|
try:
|
||||||
|
cls._init_oracle_client(oracledb)
|
||||||
|
except Exception as e:
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(f"Failed to init thick mode: {e}")
|
||||||
|
|
||||||
|
connection = None
|
||||||
|
cursor = None
|
||||||
|
try:
|
||||||
|
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
||||||
|
cursor = connection.cursor()
|
||||||
|
cursor.execute(sql)
|
||||||
|
columns = [col[0] for col in cursor.description]
|
||||||
|
return connection, cursor, columns, None
|
||||||
|
except Exception as e:
|
||||||
|
if cursor:
|
||||||
|
try:
|
||||||
|
cursor.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if connection:
|
||||||
|
try:
|
||||||
|
connection.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
error_text = str(e)
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(f"Oracle direct query failed: {error_text}")
|
||||||
|
return None, None, ["Error"], [[error_text]]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _ensure_asset_join_site(cls, sql: str, base_alias: str, table_name: str) -> str:
|
def _ensure_asset_join_site(cls, sql: str, base_alias: str, table_name: str) -> str:
|
||||||
join_pattern = re.compile(
|
join_pattern = re.compile(
|
||||||
@@ -964,40 +1095,49 @@ ORDER BY faj.faj02
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def execute_sql(cls, sql: str):
|
def execute_sql(cls, sql: str):
|
||||||
|
connection, cursor, columns, error_rows = cls._execute_sql_internal(sql)
|
||||||
|
if columns == ["Error"]:
|
||||||
|
return columns, error_rows
|
||||||
try:
|
try:
|
||||||
import oracledb
|
|
||||||
except ImportError:
|
|
||||||
return ["Error"], [["oracledb is not installed"]]
|
|
||||||
|
|
||||||
user = "EXT_VIEW_USER"
|
|
||||||
password = "extviewuser"
|
|
||||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Old ERP Oracle versions require python-oracledb thick mode.
|
|
||||||
cls._init_oracle_client(oracledb)
|
|
||||||
except Exception as e:
|
|
||||||
if current_app:
|
|
||||||
current_app.logger.warning(f"Failed to init thick mode: {e}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
|
||||||
cursor = connection.cursor()
|
|
||||||
cursor.execute(sql)
|
|
||||||
|
|
||||||
columns = [col[0] for col in cursor.description]
|
|
||||||
# Use fetchmany(50) instead of LLM-generated FETCH FIRST to support older Oracle versions
|
|
||||||
rows = cursor.fetchmany(50)
|
rows = cursor.fetchmany(50)
|
||||||
|
|
||||||
cursor.close()
|
|
||||||
connection.close()
|
|
||||||
|
|
||||||
return columns, rows
|
return columns, rows
|
||||||
except Exception as e:
|
finally:
|
||||||
error_text = str(e)
|
try:
|
||||||
if current_app:
|
cursor.close()
|
||||||
current_app.logger.warning(f"Oracle direct query failed: {error_text}")
|
finally:
|
||||||
return ["Error"], [[error_text]]
|
connection.close()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def execute_sql_page(cls, sql: str, *, page: int = 1, page_size: int = 100):
|
||||||
|
safe_page = max(1, int(page or 1))
|
||||||
|
safe_page_size = max(1, min(200, int(page_size or 100)))
|
||||||
|
offset = (safe_page - 1) * safe_page_size
|
||||||
|
paged_sql = cls._build_paged_query_sql(sql, safe_page_size, offset=offset)
|
||||||
|
connection, cursor, columns, error_rows = cls._execute_sql_internal(paged_sql)
|
||||||
|
if columns == ["Error"]:
|
||||||
|
return columns, error_rows
|
||||||
|
try:
|
||||||
|
raw_columns = [name for name in columns if str(name).upper() != "PREVIEW_ROWNUM__"]
|
||||||
|
visible_len = len(raw_columns)
|
||||||
|
raw_rows = cursor.fetchall()
|
||||||
|
rows = [tuple(list(row)[:visible_len]) for row in raw_rows]
|
||||||
|
return raw_columns, rows
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
cursor.close()
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_total_count_for_sql(cls, sql: str) -> int | None:
|
||||||
|
count_sql = cls._build_generic_total_count_sql(sql)
|
||||||
|
columns, rows = cls.execute_sql_page(count_sql, page=1, page_size=1)
|
||||||
|
if columns == ["Error"] or not rows or not rows[0]:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return int(rows[0][0])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def format_result(cls, columns, rows, sql, original_query, agent=None):
|
def format_result(cls, columns, rows, sql, original_query, agent=None):
|
||||||
@@ -1013,17 +1153,47 @@ ORDER BY faj.faj02
|
|||||||
return f"{summary_text}\n\n{sql_details}"
|
return f"{summary_text}\n\n{sql_details}"
|
||||||
|
|
||||||
display_columns = cls._localize_asset_columns(columns, original_query, sql, agent=agent)
|
display_columns = cls._localize_asset_columns(columns, original_query, sql, agent=agent)
|
||||||
|
display_rows = cls._localize_asset_rows(columns, rows, original_query, sql, agent=agent)
|
||||||
header = "| " + " | ".join(display_columns) + " |"
|
header = "| " + " | ".join(display_columns) + " |"
|
||||||
separator = "| " + " | ".join(["---"] * len(display_columns)) + " |"
|
separator = "| " + " | ".join(["---"] * len(display_columns)) + " |"
|
||||||
|
|
||||||
body = []
|
body = []
|
||||||
for row in rows:
|
for row in display_rows:
|
||||||
body.append("| " + " | ".join([cls._stringify_value(val) for val in row]) + " |")
|
body.append("| " + " | ".join([cls._stringify_value(val) for val in row]) + " |")
|
||||||
|
|
||||||
table_str = "\n".join([header, separator] + body)
|
table_str = "\n".join([header, separator] + body)
|
||||||
|
|
||||||
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def build_query_preview_payload(cls, columns, rows, sql, original_query, agent=None):
|
||||||
|
if columns == ["Error"] or not columns:
|
||||||
|
return None
|
||||||
|
total_count = cls._query_asset_total_count(original_query, sql, agent=agent)
|
||||||
|
if total_count is None:
|
||||||
|
total_count = len(rows or [])
|
||||||
|
preview_row_count = len(rows or [])
|
||||||
|
previewable = total_count > preview_row_count
|
||||||
|
return {
|
||||||
|
"kind": "text2sql_result_preview",
|
||||||
|
"previewable": previewable,
|
||||||
|
"query": original_query,
|
||||||
|
"sql": cls._sanitize_sql_text(sql),
|
||||||
|
"total_count": total_count,
|
||||||
|
"preview_row_count": preview_row_count,
|
||||||
|
"display_columns": cls._localize_asset_columns(columns, original_query, sql, agent=agent),
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_preview_page(cls, *, sql: str, query: str, page: int = 1, page_size: int = 100, agent=None, total_count: int | None = None):
|
||||||
|
raw_columns, raw_rows = cls.execute_sql_page(sql, page=page, page_size=page_size)
|
||||||
|
if raw_columns == ["Error"]:
|
||||||
|
return raw_columns, raw_rows, total_count
|
||||||
|
resolved_total = total_count if total_count is not None else cls.get_total_count_for_sql(sql)
|
||||||
|
display_columns = cls._localize_asset_columns(raw_columns, query, sql, agent=agent)
|
||||||
|
display_rows = cls._localize_asset_rows(raw_columns, raw_rows, query, sql, agent=agent)
|
||||||
|
return display_columns, display_rows, resolved_total
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def stream_chat(query: str, user, agent, conversation_id: str = None, session_id: str | None = None):
|
def stream_chat(query: str, user, agent, conversation_id: str = None, session_id: str | None = None):
|
||||||
"""Yields SSE events to frontend just like DifyService"""
|
"""Yields SSE events to frontend just like DifyService"""
|
||||||
@@ -1090,6 +1260,7 @@ ORDER BY faj.faj02
|
|||||||
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
|
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
|
||||||
stage_start = time.time()
|
stage_start = time.time()
|
||||||
result_text = Text2SQLService.format_result(columns, rows, sql, query, agent=agent)
|
result_text = Text2SQLService.format_result(columns, rows, sql, query, agent=agent)
|
||||||
|
result_preview_payload = Text2SQLService.build_query_preview_payload(columns, rows, sql, query, agent=agent)
|
||||||
format_result_ms = int((time.time() - stage_start) * 1000)
|
format_result_ms = int((time.time() - stage_start) * 1000)
|
||||||
latency = int((time.time() - start_time) * 1000)
|
latency = int((time.time() - start_time) * 1000)
|
||||||
if current_app:
|
if current_app:
|
||||||
@@ -1125,6 +1296,7 @@ ORDER BY faj.faj02
|
|||||||
session_id=session_id,
|
session_id=session_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=result_text,
|
answer=result_text,
|
||||||
|
payload=result_preview_payload,
|
||||||
tokens_used=0,
|
tokens_used=0,
|
||||||
latency=latency,
|
latency=latency,
|
||||||
)
|
)
|
||||||
@@ -1141,6 +1313,7 @@ ORDER BY faj.faj02
|
|||||||
'answer': result_text,
|
'answer': result_text,
|
||||||
'replace_answer': True,
|
'replace_answer': True,
|
||||||
'chat_log_id': chat_log_id,
|
'chat_log_id': chat_log_id,
|
||||||
'conversation_id': final_conversation_id
|
'conversation_id': final_conversation_id,
|
||||||
|
'payload': result_preview_payload,
|
||||||
}
|
}
|
||||||
yield f"data: {json.dumps(end_data)}\n\n"
|
yield f"data: {json.dumps(end_data)}\n\n"
|
||||||
@@ -43,6 +43,16 @@ export interface ChatUploadResult {
|
|||||||
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
|
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ChatQueryPreviewPage {
|
||||||
|
columns: string[];
|
||||||
|
rows: any[][];
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
|
total: number;
|
||||||
|
has_more: boolean;
|
||||||
|
query?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export const listChatSessions = (agentId: number) =>
|
export const listChatSessions = (agentId: number) =>
|
||||||
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
|
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
|
||||||
|
|
||||||
@@ -98,3 +108,16 @@ export const uploadChatFile = (agentId: number, file: File) => {
|
|||||||
headers: getAuthHeaders(),
|
headers: getAuthHeaders(),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getChatQueryPreviewPage = (
|
||||||
|
agentId: number,
|
||||||
|
chatLogId: number,
|
||||||
|
query: { page?: number; page_size?: number } = {},
|
||||||
|
) => {
|
||||||
|
const qs = new URLSearchParams({
|
||||||
|
agent_id: String(agentId),
|
||||||
|
page: String(query.page ?? 1),
|
||||||
|
page_size: String(query.page_size ?? 100),
|
||||||
|
});
|
||||||
|
return requestJson<ChatQueryPreviewPage>(`/api/chat/query-preview/${chatLogId}?${qs.toString()}`, auth());
|
||||||
|
};
|
||||||
@@ -131,6 +131,9 @@ const applyEventMetadata = (msg: ChatMessage, data: any) => {
|
|||||||
addAttributionParts(msg, metadata?.annotation_reply);
|
addAttributionParts(msg, metadata?.annotation_reply);
|
||||||
addAttributionParts(msg, data?.citation);
|
addAttributionParts(msg, data?.citation);
|
||||||
addAttributionParts(msg, metadata?.citation);
|
addAttributionParts(msg, metadata?.citation);
|
||||||
|
if (data?.payload && typeof data.payload === 'object') {
|
||||||
|
msg.payload = data.payload;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useChat() {
|
export function useChat() {
|
||||||
|
|||||||
+197
-12
@@ -35,6 +35,7 @@ import {
|
|||||||
deleteChatSession,
|
deleteChatSession,
|
||||||
listChatMessages,
|
listChatMessages,
|
||||||
saveLocalChatMessage,
|
saveLocalChatMessage,
|
||||||
|
getChatQueryPreviewPage,
|
||||||
resolveChatSourceFile,
|
resolveChatSourceFile,
|
||||||
listOaEmployees,
|
listOaEmployees,
|
||||||
uploadChatFile,
|
uploadChatFile,
|
||||||
@@ -92,6 +93,103 @@ const DEFAULT_KB = '企业知识库';
|
|||||||
const ERP_KB = 'ERP知识库';
|
const ERP_KB = 'ERP知识库';
|
||||||
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
|
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
|
||||||
|
|
||||||
|
type QueryPreviewPayload = {
|
||||||
|
kind: 'text2sql_result_preview';
|
||||||
|
previewable?: boolean;
|
||||||
|
total_count?: number;
|
||||||
|
preview_row_count?: number;
|
||||||
|
query?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const showQueryPreviewDialog = ref(false);
|
||||||
|
const queryPreviewLoading = ref(false);
|
||||||
|
const queryPreviewError = ref('');
|
||||||
|
const queryPreviewState = ref({
|
||||||
|
chatLogId: 0,
|
||||||
|
title: '',
|
||||||
|
query: '',
|
||||||
|
columns: [] as string[],
|
||||||
|
rows: [] as any[][],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 100,
|
||||||
|
total: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const getQueryPreviewPayload = (msg: any): QueryPreviewPayload | null => {
|
||||||
|
const payload = msg?.payload;
|
||||||
|
if (!payload || typeof payload !== 'object') return null;
|
||||||
|
if ((payload as any).kind !== 'text2sql_result_preview') return null;
|
||||||
|
return payload as QueryPreviewPayload;
|
||||||
|
};
|
||||||
|
|
||||||
|
const canOpenQueryPreview = (msg: any) => {
|
||||||
|
const payload = getQueryPreviewPayload(msg);
|
||||||
|
return !!(payload?.previewable && Number(msg?.chat_log_id) > 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getQueryPreviewSummary = (msg: any) => {
|
||||||
|
const payload = getQueryPreviewPayload(msg);
|
||||||
|
const total = Number(payload?.total_count || 0);
|
||||||
|
if (total > 0) return `查看全部预览(共 ${total} 条)`;
|
||||||
|
return '查看全部预览';
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeQueryPreviewDialog = () => {
|
||||||
|
showQueryPreviewDialog.value = false;
|
||||||
|
queryPreviewError.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadQueryPreviewPage = async (chatLogId: number, page = 1) => {
|
||||||
|
if (!currentAgentId.value) {
|
||||||
|
queryPreviewError.value = '当前 Agent 未就绪,请稍后重试';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
queryPreviewLoading.value = true;
|
||||||
|
queryPreviewError.value = '';
|
||||||
|
try {
|
||||||
|
const result = await getChatQueryPreviewPage(currentAgentId.value, chatLogId, { page, page_size: queryPreviewState.value.pageSize });
|
||||||
|
queryPreviewState.value = {
|
||||||
|
...queryPreviewState.value,
|
||||||
|
chatLogId,
|
||||||
|
title: String(result.query || queryPreviewState.value.title || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||||
|
query: String(result.query || '').trim(),
|
||||||
|
columns: Array.isArray(result.columns) ? result.columns : [],
|
||||||
|
rows: Array.isArray(result.rows) ? result.rows : [],
|
||||||
|
page: Number(result.page || page || 1),
|
||||||
|
pageSize: Number(result.page_size || queryPreviewState.value.pageSize || 100),
|
||||||
|
total: Number(result.total || 0),
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
queryPreviewError.value = error?.message || '加载全量预览失败';
|
||||||
|
} finally {
|
||||||
|
queryPreviewLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openQueryPreviewDialog = async (msgObj: any) => {
|
||||||
|
const chatLogId = Number(msgObj?.chat_log_id || 0);
|
||||||
|
if (!chatLogId) return;
|
||||||
|
const payload = getQueryPreviewPayload(msgObj);
|
||||||
|
queryPreviewState.value = {
|
||||||
|
...queryPreviewState.value,
|
||||||
|
chatLogId,
|
||||||
|
title: String(payload?.query || msgObj?.content || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||||
|
query: String(payload?.query || '').trim(),
|
||||||
|
page: 1,
|
||||||
|
total: Number(payload?.total_count || 0),
|
||||||
|
};
|
||||||
|
showQueryPreviewDialog.value = true;
|
||||||
|
await loadQueryPreviewPage(chatLogId, 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const changeQueryPreviewPage = async (delta: number) => {
|
||||||
|
const nextPage = queryPreviewState.value.page + delta;
|
||||||
|
if (nextPage < 1) return;
|
||||||
|
const totalPages = Math.max(1, Math.ceil((queryPreviewState.value.total || 0) / (queryPreviewState.value.pageSize || 100)));
|
||||||
|
if (nextPage > totalPages) return;
|
||||||
|
await loadQueryPreviewPage(queryPreviewState.value.chatLogId, nextPage);
|
||||||
|
};
|
||||||
|
|
||||||
const selectedKb = ref(DEFAULT_KB);
|
const selectedKb = ref(DEFAULT_KB);
|
||||||
const showKbDropdown = ref(false);
|
const showKbDropdown = ref(false);
|
||||||
const kbMenuRef = ref<HTMLElement | null>(null);
|
const kbMenuRef = ref<HTMLElement | null>(null);
|
||||||
@@ -891,7 +989,11 @@ const selectKb = (option: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
watch(canSelectErpKnowledgeBase, (allowed) => {
|
watch(canSelectErpKnowledgeBase, (allowed) => {
|
||||||
if (!allowed && selectedKb.value === ERP_KB) {
|
if (allowed) {
|
||||||
|
selectedKb.value = ERP_KB;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (selectedKb.value === ERP_KB) {
|
||||||
selectedKb.value = DEFAULT_KB;
|
selectedKb.value = DEFAULT_KB;
|
||||||
}
|
}
|
||||||
if (!allowed) {
|
if (!allowed) {
|
||||||
@@ -2223,10 +2325,6 @@ const normalizeBrowserInput = (value: string) => {
|
|||||||
return '';
|
return '';
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleBrowserPanel = () => {
|
|
||||||
browserPanelOpen.value = !browserPanelOpen.value;
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadBrowserPage = () => {
|
const loadBrowserPage = () => {
|
||||||
const normalized = normalizeBrowserInput(browserDraftUrl.value);
|
const normalized = normalizeBrowserInput(browserDraftUrl.value);
|
||||||
if (!normalized) {
|
if (!normalized) {
|
||||||
@@ -4015,6 +4113,8 @@ const resetChatStateForAgentChange = () => {
|
|||||||
currentAgent.value = null;
|
currentAgent.value = null;
|
||||||
copiedIndex.value = null;
|
copiedIndex.value = null;
|
||||||
showAttachmentMenu.value = false;
|
showAttachmentMenu.value = false;
|
||||||
|
browserPanelOpen.value = false;
|
||||||
|
closeQueryPreviewDialog();
|
||||||
filePreviewVisible.value = false;
|
filePreviewVisible.value = false;
|
||||||
previewFile.value = null;
|
previewFile.value = null;
|
||||||
};
|
};
|
||||||
@@ -4812,6 +4912,19 @@ const showChatRating = ref(false);
|
|||||||
@click="handleChatMarkdownClick"
|
@click="handleChatMarkdownClick"
|
||||||
v-html="renderMarkdown(msg.content)"
|
v-html="renderMarkdown(msg.content)"
|
||||||
></div>
|
></div>
|
||||||
|
<div
|
||||||
|
v-if="msg.role === 'assistant' && canOpenQueryPreview(msg)"
|
||||||
|
class="mt-4"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||||
|
@click="openQueryPreviewDialog(msg)"
|
||||||
|
>
|
||||||
|
<LayoutGrid class="h-3.5 w-3.5" />
|
||||||
|
{{ getQueryPreviewSummary(msg) }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="isShippingNoticeAgent && msg.shipping_actions?.length"
|
v-if="isShippingNoticeAgent && msg.shipping_actions?.length"
|
||||||
class="mt-4 space-y-2 border-t border-default pt-4"
|
class="mt-4 space-y-2 border-t border-default pt-4"
|
||||||
@@ -5126,13 +5239,6 @@ const showChatRating = ref(false);
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
|
||||||
@click="toggleBrowserPanel"
|
|
||||||
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
|
|
||||||
>
|
|
||||||
<Globe class="h-3.5 w-3.5 text-brand-500" />
|
|
||||||
{{ browserPanelOpen ? $t('chat.collapseBrowser') : $t('chat.openBrowser') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
@click="handleSend"
|
@click="handleSend"
|
||||||
@@ -5262,6 +5368,85 @@ const showChatRating = ref(false);
|
|||||||
showGeneralFeedbackDialog = false;
|
showGeneralFeedbackDialog = false;
|
||||||
}"
|
}"
|
||||||
/>
|
/>
|
||||||
|
<div
|
||||||
|
v-if="showQueryPreviewDialog"
|
||||||
|
class="dialog-overlay z-[120] items-center"
|
||||||
|
@click.self="closeQueryPreviewDialog"
|
||||||
|
>
|
||||||
|
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,1280px)] max-w-[1280px] flex-col">
|
||||||
|
<div class="dialog-header">
|
||||||
|
<div>
|
||||||
|
<h3 class="section-title">查询结果全量预览</h3>
|
||||||
|
<p class="section-desc mt-1">{{ queryPreviewState.query || queryPreviewState.title }}</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="closeQueryPreviewDialog">
|
||||||
|
<X class="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3 text-sm text-secondary">
|
||||||
|
<div>共 {{ queryPreviewState.total || 0 }} 条,当前第 {{ queryPreviewState.page }} / {{ Math.max(1, Math.ceil((queryPreviewState.total || 0) / (queryPreviewState.pageSize || 100))) }} 页</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
:disabled="queryPreviewLoading || queryPreviewState.page <= 1"
|
||||||
|
@click="changeQueryPreviewPage(-1)"
|
||||||
|
>
|
||||||
|
上一页
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
:disabled="queryPreviewLoading || queryPreviewState.page >= Math.max(1, Math.ceil((queryPreviewState.total || 0) / (queryPreviewState.pageSize || 100)))"
|
||||||
|
@click="changeQueryPreviewPage(1)"
|
||||||
|
>
|
||||||
|
下一页
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="queryPreviewError" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||||
|
{{ queryPreviewError }}
|
||||||
|
</div>
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
|
||||||
|
<div v-if="queryPreviewLoading" class="flex h-56 items-center justify-center">
|
||||||
|
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
|
||||||
|
</div>
|
||||||
|
<div v-else-if="!queryPreviewState.columns.length" class="flex h-56 items-center justify-center text-sm text-muted">
|
||||||
|
暂无可预览数据
|
||||||
|
</div>
|
||||||
|
<table v-else class="min-w-full border-collapse text-sm">
|
||||||
|
<thead class="sticky top-0 z-10 bg-slate-50">
|
||||||
|
<tr>
|
||||||
|
<th
|
||||||
|
v-for="column in queryPreviewState.columns"
|
||||||
|
:key="`query-preview-col-${column}`"
|
||||||
|
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
|
||||||
|
>
|
||||||
|
{{ column }}
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr
|
||||||
|
v-for="(row, rowIndex) in queryPreviewState.rows"
|
||||||
|
:key="`query-preview-row-${rowIndex}`"
|
||||||
|
class="odd:bg-white even:bg-slate-50/50"
|
||||||
|
>
|
||||||
|
<td
|
||||||
|
v-for="(cell, cellIndex) in row"
|
||||||
|
:key="`query-preview-cell-${rowIndex}-${cellIndex}`"
|
||||||
|
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
|
||||||
|
>
|
||||||
|
<div class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="showLeaveAgentDialog"
|
v-if="showLeaveAgentDialog"
|
||||||
class="dialog-overlay z-[100] items-center"
|
class="dialog-overlay z-[100] items-center"
|
||||||
|
|||||||
Reference in new issue
Block a user