Merge branch 'dev' into test

This commit is contained in:
sophie committed 2026-05-12 15:31:51 +08:00
commit 3f25de0e4f
6 files changed
+189 -58

No files matched your search

+5
View File
@@ -2,6 +2,11 @@ FROM python:3.12-slim
WORKDIR /app
# Oracle Instant Client runtime dependencies for thick mode.
RUN apt-get update \
&& apt-get install -y --no-install-recommends libaio1 libnsl2 \
&& rm -rf /var/lib/apt/lists/*
# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
+5 -5
View File
@@ -62,7 +62,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
return False
def _fetch_preview_source_bytes(file_url: str):
def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024 * 1024):
"""
从上游文件 URL 拉取二进制内容(供预览接口复用)。
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
@@ -178,8 +178,7 @@ def _fetch_preview_source_bytes(file_url: str):
return None, None, (f'upstream returned status {upstream.status_code}', 502)
content = upstream.content or b''
max_size = 15 * 1024 * 1024
if len(content) > max_size:
if max_size is not None and len(content) > max_size:
return None, None, ('file too large for online preview', 413)
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
@@ -717,7 +716,9 @@ def preview_file_raw():
name = (request.args.get('name') or '').strip()
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
ext = url_path_ext or name_ext
content, content_type, err = _fetch_preview_source_bytes(file_url)
is_download = request.args.get('download') == '1'
max_size = None if is_download else 15 * 1024 * 1024
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
if err:
msg, code = err
return jsonify({'error': msg}), code
@@ -755,7 +756,6 @@ def preview_file_raw():
encoded_filename = quote(filename)
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f'preview.{ext or "bin"}'
is_download = request.args.get('download') == '1'
disposition_type = 'attachment' if is_download else 'inline'
resp = Response(content, status=200, mimetype=mime)
+146 -32
View File
@@ -2,10 +2,13 @@ import json
import os
import re
import time
from flask import current_app
from flask import current_app, has_app_context
class Text2SQLService:
_schema_text = None
_oracle_client_init_attempted = False
_oracle_client_init_error = None
_oracle_client_mode = "unknown"
@staticmethod
def _backend_dir() -> str:
@@ -17,22 +20,109 @@ class Text2SQLService:
@classmethod
def _find_oracle_client_dir(cls) -> str | None:
candidate_roots = [
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
candidate_roots = []
if env_dir:
candidate_roots.append(env_dir)
candidate_roots.extend([
os.path.join(cls._backend_dir(), 'oracle_client'),
os.path.join(cls._project_root(), 'oracle_client'),
]
os.path.join(os.getcwd(), 'oracle_client'),
'/app/oracle_client',
'/opt/oracle',
])
library_markers = {'oci.dll', 'libclntsh.so', 'libclntsh.dylib'}
for oracle_client_dir in candidate_roots:
if not os.path.exists(oracle_client_dir):
if not oracle_client_dir or not os.path.exists(oracle_client_dir):
continue
try:
entries = os.listdir(oracle_client_dir)
except OSError:
continue
entry_names = {name.lower() for name in entries}
if library_markers & entry_names:
return oracle_client_dir
client_dirs = [
os.path.join(oracle_client_dir, d)
for d in os.listdir(oracle_client_dir)
for d in entries
if d.startswith('instantclient_') and os.path.isdir(os.path.join(oracle_client_dir, d))
]
if client_dirs:
return client_dirs[0]
return None
@staticmethod
def _log(level: str, message: str):
if has_app_context():
getattr(current_app.logger, level, current_app.logger.info)(message)
@classmethod
def _ensure_oracle_client_initialized(cls, oracledb):
if cls._oracle_client_init_attempted:
return cls._oracle_client_mode == "thick"
cls._oracle_client_init_attempted = True
try:
if not getattr(oracledb, "is_thin_mode", lambda: True)():
cls._oracle_client_mode = "thick"
return True
import platform
import shutil
import tempfile
target_lib_dir = cls._find_oracle_client_dir()
if platform.system() == 'Windows' and target_lib_dir and not target_lib_dir.isascii():
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
os.makedirs(temp_dir, exist_ok=True)
shutil.copytree(target_lib_dir, safe_lib_dir)
target_lib_dir = safe_lib_dir
if target_lib_dir:
oracledb.init_oracle_client(lib_dir=target_lib_dir)
else:
oracledb.init_oracle_client()
cls._oracle_client_mode = "thin" if getattr(oracledb, "is_thin_mode", lambda: True)() else "thick"
if cls._oracle_client_mode == "thick":
cls._log("info", f"Oracle thick mode initialized successfully. lib_dir={target_lib_dir or 'system-default'}")
return True
cls._oracle_client_init_error = "Oracle client initialized but driver is still in thin mode"
except Exception as exc:
cls._oracle_client_init_error = str(exc)
cls._oracle_client_mode = "thin"
cls._log("warning", f"Failed to init Oracle thick mode: {exc}")
return False
@classmethod
def _format_connection_error(cls, error_message: str) -> str:
message = (error_message or "").strip()
if "DPY-3010" in message or "DPY-6005" in message:
init_error = cls._oracle_client_init_error or "未找到可用的 Oracle Instant Client"
return (
"Oracle 连接失败:当前驱动仍在 thin mode,而该 ERP Oracle 版本需要 thick mode。"
"请在部署环境提供 Oracle Instant Client,并将项目根目录的 oracle_client 挂载到 /app/oracle_client "
"或设置 ORACLE_CLIENT_LIB_DIR。"
f"当前 thick mode 初始化错误:{init_error}"
)
return message or "未知数据库错误"
@staticmethod
def _extract_invalid_identifier(error_message: str) -> str:
match = re.search(r'ORA-00904:\s*"?(?P<name>[A-Za-z0-9_#$]+)"?\s*:\s*invalid identifier', error_message or "", re.IGNORECASE)
return (match.group("name") if match else "").upper()
@staticmethod
def _is_repairable_sql_error(error_message: str) -> bool:
text = (error_message or "").upper()
return any(code in text for code in ("ORA-00904", "ORA-00942", "INVALID IDENTIFIER", "TABLE OR VIEW DOES NOT EXIST"))
@classmethod
def get_schema(cls):
if cls._schema_text is None:
@@ -184,6 +274,7 @@ class Text2SQLService:
- 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。
- 仅允许输出单条 SELECT 或 WITH 开头的查询。
- 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。
- 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。
- 优先选择最相关字段,避免 SELECT *。
- 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。
- 如果问题无法仅依据当前 Schema 回答,请输出安全的 SELECT 语句说明原因,例如 SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL。"""
@@ -199,6 +290,45 @@ class Text2SQLService:
except Exception as e:
return f"SELECT '{cls._escape_sql_message(f'LLM Error: {e}')}' AS error FROM DUAL"
@classmethod
def repair_sql(cls, query: str, failed_sql: str, error_message: str) -> str:
schema = cls.get_schema()
invalid_identifier = cls._extract_invalid_identifier(error_message)
invalid_hint = f"本次报错的非法字段/标识符是:{invalid_identifier}。" if invalid_identifier else ""
system_prompt = f"""你是一个专业的 Oracle SQL 修复助手。你的任务是根据执行失败的 SQL、数据库报错和当前 Schema,修复成一条可执行的 Oracle 查询语句。
数据库结构 (Schema):
{schema}
修复要求:
- 只输出 SQL,不要解释。
- 必须保留用户问题的原始意图。
- 必须只使用 Schema 中真实存在的表名和字段名。
- 严禁创造 FILE_TYPE、STATUS_NAME 这类 Schema 中不存在的字段。
- 如果当前 Schema 无法支持该问题,请输出:SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL
- 严禁输出任何非 SELECT / WITH 语句。"""
user_prompt = f"""用户问题:{query}
执行失败的 SQL:
```sql
{failed_sql}
```
数据库错误:{error_message}
{invalid_hint}
请根据上述错误修复 SQL,并确保只使用当前 Schema 中真实存在的表和字段。"""
try:
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
sql = sql.rstrip(";")
if not cls._is_safe_query(sql):
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
return sql
except Exception as e:
return f"SELECT '{cls._escape_sql_message(f'SQL Repair Error: {e}')}' AS error FROM DUAL"
@classmethod
def execute_sql(cls, sql: str):
try:
@@ -208,33 +338,9 @@ class Text2SQLService:
user = "EXT_VIEW_USER"
password = "extviewuser"
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
try:
# Enable thick mode to support older Oracle versions
import platform
import tempfile
import shutil
if platform.system() == 'Windows':
target_lib_dir = cls._find_oracle_client_dir()
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
# Fix for OCI path issue with Chinese characters (like "HX工作目录")
# OCI C-library fails to load if path contains non-ASCII
if target_lib_dir and not target_lib_dir.isascii():
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
os.makedirs(temp_dir, exist_ok=True)
shutil.copytree(target_lib_dir, safe_lib_dir)
target_lib_dir = safe_lib_dir
if target_lib_dir:
oracledb.init_oracle_client(lib_dir=target_lib_dir)
else:
oracledb.init_oracle_client()
except Exception as e:
if current_app:
current_app.logger.warning(f"Failed to init thick mode: {e}")
cls._ensure_oracle_client_initialized(oracledb)
try:
connection = oracledb.connect(user=user, password=password, dsn=dsn)
@@ -249,7 +355,7 @@ class Text2SQLService:
return columns, rows
except Exception as e:
return ["Error"], [[str(e)]]
return ["Error"], [[cls._format_connection_error(str(e))]]
@classmethod
def format_result(cls, columns, rows, sql, original_query):
@@ -287,6 +393,14 @@ class Text2SQLService:
# 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"
+2
View File
@@ -17,6 +17,7 @@ services:
- DATABASE_URL=${DATABASE_URL}
- FLASK_APP=${FLASK_APP:-run.py}
- FLASK_ENV=${FLASK_ENV:-production}
- ORACLE_CLIENT_LIB_DIR=${ORACLE_CLIENT_LIB_DIR:-/app/oracle_client}
# 允许容器访问宿主机服务 (如数据库)
extra_hosts:
- "host.docker.internal:host-gateway"
@@ -29,6 +30,7 @@ services:
# 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。
volumes:
- ./backend/.env:/app/.env
- ./oracle_client:/app/oracle_client:ro
networks:
- ai-platform
+7 -1
View File
@@ -105,6 +105,7 @@ const iframeSrc = computed(() => {
const close = () => emit('update:modelValue', false);
const isDownloading = ref(false);
const previewTooLarge = computed(() => /file too large for online preview/i.test(error.value));
const downloadFile = async () => {
if (!props.file?.url || !props.agentId) return;
@@ -373,7 +374,12 @@ watch(
<div class="flex-1 overflow-auto p-4 bg-slate-50 dark:bg-slate-950">
<div v-if="isLoading" class="text-sm text-slate-500 dark:text-slate-400">加载中...</div>
<div v-else-if="error" class="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg p-3">
预览失败:{{ error }}
<template v-if="previewTooLarge">
文件较大,暂不支持在线预览,请直接点击上方“下载文件”获取原文件。
</template>
<template v-else>
预览失败:{{ error }}
</template>
</div>
<div
v-else-if="resolvedMode === 'markdown'"
+24 -20
View File
@@ -569,9 +569,28 @@ const syncLeaveDuration = (form: LeaveRequestFormData) => {
const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, '');
const isLeaveIntent = (content: string) => {
const isStrongLeaveIntent = (content: string) => {
const normalized = getLeaveIntentNormalized(content);
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程|请假流程)/.test(normalized);
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程)/.test(normalized);
};
const startLocalLeaveFlow = (content: string) => {
const formId = newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
form: createLeaveFormData(),
submitting: false,
confirmationGenerated: false,
};
messages.value.push({ role: 'user', content, type: 'text' });
messages.value.push({
role: 'assistant',
type: 'leave-form',
content: '已为你生成请假申请表,请直接在下方填写并提交。',
payload,
local_id: formId,
local_only: true,
});
};
const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => (
@@ -726,26 +745,11 @@ const handleSend = async (textOrEvent?: string | Event) => {
// Clear input if sending from input box (not resending/regenerating)
if (typeof textOrEvent !== 'string') input.value = '';
if (isLeaveIntent(content)) {
const formId = newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
form: createLeaveFormData(),
submitting: false,
confirmationGenerated: false,
};
messages.value.push({ role: 'user', content, type: 'text' });
messages.value.push({
role: 'assistant',
type: 'leave-form',
content: '已为你生成请假申请表,请直接在下方填写并提交。',
payload,
local_id: formId,
local_only: true,
});
if (isStrongLeaveIntent(content)) {
startLocalLeaveFlow(content);
return;
}
await sendMessage(content, agentId, selectedKb.value);
// 发送完成后刷新历史记录,确保新会话出现