Files
syops/backend/app/services/text2sql.py
T

623 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import os
import re
import time
from pathlib import Path
from flask import current_app
class Text2SQLService:
_schema_text = None
_oracle_client_initialized = False
_jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar"
@staticmethod
def _backend_dir() -> str:
return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
@classmethod
def _project_root(cls) -> str:
return os.path.dirname(cls._backend_dir())
@classmethod
def _find_oracle_client_dir(cls) -> str | None:
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 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 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)
@staticmethod
def _prepend_env_path(var_name: str, path_value: str):
if not path_value:
return
current = os.getenv(var_name, "")
parts = [p for p in current.split(os.pathsep) if p]
if path_value in parts:
return
os.environ[var_name] = path_value + (os.pathsep + current if current else "")
@classmethod
def _prepare_oracle_runtime_env(cls, target_lib_dir: str | None):
if not target_lib_dir:
return
try:
import platform
system_name = platform.system()
if system_name == "Linux":
cls._prepend_env_path("LD_LIBRARY_PATH", target_lib_dir)
elif system_name == "Darwin":
cls._prepend_env_path("DYLD_LIBRARY_PATH", target_lib_dir)
elif system_name == "Windows":
cls._prepend_env_path("PATH", target_lib_dir)
except Exception as exc:
cls._log("warning", f"Failed to prepare Oracle runtime env: {exc}")
@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
cls._prepare_oracle_runtime_env(target_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_oracle_client_dir(cls) -> str | None:
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
if env_dir and os.path.exists(env_dir):
return env_dir
linux_candidates = [
"/opt/oracle/instantclient",
"/opt/oracle/instantclient_19_28",
"/opt/oracle/instantclient_19_27",
]
for path in linux_candidates:
if os.path.exists(path):
return path
return cls._find_oracle_client_dir()
@classmethod
def _init_oracle_client(cls, oracledb) -> None:
if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
return
import platform
import shutil
import tempfile
target_lib_dir = cls._get_oracle_client_dir()
if platform.system() == 'Windows' and target_lib_dir:
# OCI C-library fails to load if path contains non-ASCII.
if 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_initialized = True
@classmethod
def _jdbc_dir(cls) -> Path:
return Path(cls._backend_dir()) / "jdbc"
@classmethod
def _ensure_jdbc_driver_jar(cls) -> str:
env_path = (os.getenv("ERP_JDBC_JAR") or "").strip()
if env_path and os.path.exists(env_path):
return env_path
jar_dir = cls._jdbc_dir()
jar_dir.mkdir(parents=True, exist_ok=True)
jar_path = jar_dir / "ojdbc8-19.25.0.0.jar"
if jar_path.exists():
return str(jar_path)
import requests
driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url
with requests.get(driver_url, stream=True, timeout=120) as resp:
resp.raise_for_status()
with open(jar_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=1024 * 256):
if chunk:
f.write(chunk)
return str(jar_path)
@staticmethod
def _dsn_to_jdbc_url(dsn: str) -> str:
dsn = (dsn or "").strip()
if not dsn:
raise ValueError("ERP_DB_DSN is empty")
if dsn.startswith("jdbc:oracle:thin:@"):
return dsn
if dsn.startswith("("):
return f"jdbc:oracle:thin:@{dsn}"
match = re.match(r"^(?P<host>[^:/]+)(?::(?P<port>\d+))?/(?P<service>.+)$", dsn)
if match:
host = match.group("host")
port = match.group("port") or "1521"
service = match.group("service")
return f"jdbc:oracle:thin:@//{host}:{port}/{service}"
return f"jdbc:oracle:thin:@{dsn}"
@classmethod
def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str):
import jaydebeapi
jar_path = cls._ensure_jdbc_driver_jar()
jdbc_url = cls._dsn_to_jdbc_url(dsn)
connection = jaydebeapi.connect(
"oracle.jdbc.OracleDriver",
jdbc_url,
{
"user": user,
"password": password,
"oracle.jdbc.timezoneAsRegion": "false",
},
jar_path,
)
cursor = connection.cursor()
try:
cursor.execute(sql)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchall() if columns else []
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_schema(cls):
if cls._schema_text is None:
schema_filename = '(表+字段).md'
env_path = (os.getenv("TEXT2SQL_SCHEMA_PATH") or "").strip()
candidate_paths = []
if env_path:
candidate_paths.append(env_path)
candidate_paths.extend([
os.path.join(cls._backend_dir(), 'docs', schema_filename),
os.path.join(cls._project_root(), 'docs', schema_filename),
os.path.join(os.getcwd(), 'docs', schema_filename),
])
unique_paths = []
seen = set()
for path in candidate_paths:
normalized = os.path.normpath(path)
if normalized not in seen:
seen.add(normalized)
unique_paths.append(path)
for doc_path in unique_paths:
try:
if not os.path.exists(doc_path):
continue
with open(doc_path, 'r', encoding='utf-8') as f:
cls._schema_text = f.read()
cls._log("info", f"Loaded Text2SQL schema from {doc_path}")
break
except Exception as exc:
cls._log("warning", f"Failed to load Text2SQL schema from {doc_path}: {exc}")
if cls._schema_text is None:
tried = ", ".join(unique_paths)
cls._schema_text = f"Failed to load schema: schema file not found. Tried: {tried}"
cls._log("warning", cls._schema_text)
return cls._schema_text
@staticmethod
def _clean_llm_output(content: str) -> str:
cleaned = (content or "").strip()
cleaned = re.sub(r"^```(?:sql|json)?\s*", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"\s*```$", "", cleaned)
return cleaned.strip()
@classmethod
def _get_llm_client(cls):
try:
from openai import OpenAI
except ImportError:
return None, "OpenAI SDK not installed"
api_key = os.getenv("GJL_API_KEY", "")
base_url = os.getenv("GJL_API_BASE", "https://api.siliconflow.cn/v1")
if not api_key:
return None, "Missing GJL_API_KEY. Please configure it in .env to enable Text-to-SQL"
return OpenAI(api_key=api_key, base_url=base_url), None
@classmethod
def _chat_completion(cls, system_prompt: str, user_prompt: str, temperature: float = 0):
client, error = cls._get_llm_client()
if error:
raise RuntimeError(error)
response = client.chat.completions.create(
model=os.getenv("GJL_MODEL", "deepseek-ai/DeepSeek-V3"),
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=temperature,
)
content = response.choices[0].message.content or ""
return cls._clean_llm_output(content)
@staticmethod
def _escape_sql_message(message: str) -> str:
safe = (message or "").replace("'", "''").replace("\n", " ").strip()
return safe or "Unknown error"
@staticmethod
def _is_safe_query(sql: str) -> bool:
sql = (sql or "").strip()
if not re.match(r"(?is)^(select|with)\b", sql):
return False
return not re.search(r"(?is)\b(insert|update|delete|merge|alter|drop|truncate|create|grant|revoke)\b", sql)
@staticmethod
def _stringify_value(value):
if value is None:
return "NULL"
return str(value)
@classmethod
def _serialize_results_for_llm(cls, columns, rows, max_rows: int = 30) -> str:
preview_rows = rows[:max_rows]
preview = []
for row in preview_rows:
preview.append({columns[idx]: cls._stringify_value(value) for idx, value in enumerate(row)})
payload = {
"columns": columns,
"row_count": len(rows),
"preview_row_count": len(preview_rows),
"truncated": len(rows) > max_rows,
"rows": preview,
}
return json.dumps(payload, ensure_ascii=False)
@classmethod
def summarize_result(cls, query: str, columns, rows) -> str:
if columns == ["Error"]:
error_message = rows[0][0] if rows and rows[0] else "未知错误"
return f"- 直击答案:查询执行失败,当前无法返回结果。\n- 异常提醒:数据库返回错误 `{error_message}`,请检查筛选条件、表名或字段名。"
if not rows:
return "- 直击答案:当前未查询到符合条件的数据。\n- 趋势发现:当前结果未体现明显趋势。\n- 异常提醒:当前结果未体现明显异常,建议调整筛选条件后重试。"
system_prompt = f"""你是一位资深的业务分析师。
任务:根据下方的数据库查询结果,为用户提供一份简洁、直观的分析汇总。
汇总要求:
- 直击答案:第一句话直接回答用户的核心问题。
- 趋势发现:如果有时间维度,请指出增长或下降趋势。
- 异常提醒:如果数据中有显著的极值或异常,请标注。
- 语言风格:专业且易懂,避免直接念数字,要讲出数字背后的业务含义。
- 格式:使用 Markdown 列表。
- 如果查询结果没有体现明显趋势或异常,请明确写出“当前结果未体现明显趋势”或“当前结果未体现明显异常”,不要编造。
- 结合用户原始问题组织语言,不要重复输出 SQL,也不要复述字段名清单。"""
user_prompt = f"""原始问题:{query}
查询数据:{cls._serialize_results_for_llm(columns, rows)}"""
try:
summary = cls._chat_completion(system_prompt, user_prompt, temperature=0.2)
return summary or cls._fallback_summary(columns, rows)
except Exception:
return cls._fallback_summary(columns, rows)
@classmethod
def _fallback_summary(cls, columns, rows) -> str:
if not rows:
return "- 直击答案:当前未查询到符合条件的数据。\n- 趋势发现:当前结果未体现明显趋势。\n- 异常提醒:当前结果未体现明显异常。"
if len(rows) == 1 and len(columns) == 1:
return (
f"- 直击答案:{columns[0]} 为 {cls._stringify_value(rows[0][0])}。\n"
"- 趋势发现:当前结果未体现明显趋势。\n"
"- 异常提醒:当前结果未体现明显异常。"
)
return (
f"- 直击答案:本次共返回 {len(rows)} 条记录,可结合下方明细进一步查看。\n"
"- 趋势发现:当前结果未体现明显趋势。\n"
"- 异常提醒:当前结果未体现明显异常。"
)
@classmethod
def generate_sql(cls, query: str) -> str:
schema = cls.get_schema()
try:
system_prompt = f"""你是一个专业的 Oracle SQL 专家和数据分析助手。你的任务是将用户的自然语言转换为准确的 Oracle 查询语句。
数据库结构 (Schema):
{schema}
约束要求:
- 只输出 SQL,不要解释。
- 日期查询请优先使用 CURRENT_DATE 进行计算。
- 如果用户问题模糊,请选择最合理的关联方式,优先使用 LEFT JOIN 补充维度信息。
- 严禁生成任何 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。"""
user_prompt = f"用户问题:{query}"
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'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:
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]
rows = cursor.fetchall()
cursor.close()
connection.close()
return columns, rows
except Exception as e:
error_text = str(e)
if current_app:
current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}")
if "DPY-3010" in error_text or "DPI-1047" in error_text:
try:
return cls._execute_sql_via_jdbc(sql, user, password, dsn)
except Exception as jdbc_error:
return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]]
return ["Error"], [[error_text]]
@classmethod
def format_result(cls, columns, rows, sql, original_query):
summary_text = cls.summarize_result(original_query, columns, rows)
sql_details = f"<details>\n<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">执行的SQL</summary>\n\n```sql\n{sql}\n```\n</details>"
if columns == ["Error"]:
error_message = rows[0][0] if rows and rows[0] else "未知错误"
return f"{summary_text}\n\n**错误详情**\n\n`{error_message}`\n\n{sql_details}"
if not columns or not rows:
return f"{summary_text}\n\n{sql_details}"
header = "| " + " | ".join(columns) + " |"
separator = "| " + " | ".join(["---"] * len(columns)) + " |"
body = []
for row in rows:
body.append("| " + " | ".join([cls._stringify_value(val) for val in row]) + " |")
table_str = "\n".join([header, separator] + body)
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
"""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)
latency = int((time.time() - start_time) * 1000)
# Create ChatLog
from app.models import ChatLog, db
chat_log_id = None
try:
chat_log = ChatLog(
user_id=user_id,
agent_id=agent.id,
conversation_id=final_conversation_id,
query=query,
answer=result_text,
tokens_used=0,
latency=latency,
)
db.session.add(chat_log)
db.session.commit()
chat_log_id = chat_log.id
except Exception as e:
if current_app:
current_app.logger.error(f'Failed to log text2sql chat: {e}')
db.session.rollback()
end_data = {
'event': 'message_end',
'answer': result_text,
'replace_answer': True,
'chat_log_id': chat_log_id,
'conversation_id': final_conversation_id
}
yield f"data: {json.dumps(end_data)}\n\n"