text2ERP
This commit is contained in:
1 parent
fec2fc096e
commit
283ec9e7b3
11 files changed
+1379
-19
No files matched your search
@@ -0,0 +1,314 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from flask import current_app
|
||||
|
||||
class Text2SQLService:
|
||||
_schema_text = None
|
||||
|
||||
@classmethod
|
||||
def get_schema(cls):
|
||||
if cls._schema_text is None:
|
||||
try:
|
||||
# docs is at the project root: c:\Users\PC\Desktop\HX工作目录\hxops\hxops\docs
|
||||
# This file is in backend/app/services/text2sql.py
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
||||
doc_path = os.path.join(base_dir, 'docs', '(表+字段).md')
|
||||
with open(doc_path, 'r', encoding='utf-8') as f:
|
||||
cls._schema_text = f.read()
|
||||
except Exception as e:
|
||||
cls._schema_text = f"Failed to load schema: {e}"
|
||||
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。
|
||||
- 优先选择最相关字段,避免 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 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:
|
||||
# Enable thick mode to support older Oracle versions
|
||||
import platform
|
||||
import tempfile
|
||||
import shutil
|
||||
if platform.system() == 'Windows':
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
||||
oracle_client_dir = os.path.join(base_dir, 'oracle_client')
|
||||
|
||||
# Dynamically find the instantclient folder
|
||||
client_dirs = []
|
||||
if os.path.exists(oracle_client_dir):
|
||||
client_dirs = [
|
||||
os.path.join(oracle_client_dir, d)
|
||||
for d in os.listdir(oracle_client_dir)
|
||||
if d.startswith('instantclient_') and os.path.isdir(os.path.join(oracle_client_dir, d))
|
||||
]
|
||||
|
||||
target_lib_dir = None
|
||||
if client_dirs:
|
||||
target_lib_dir = client_dirs[0]
|
||||
else:
|
||||
target_lib_dir = os.path.join(oracle_client_dir, 'instantclient_19_24')
|
||||
|
||||
# Fix for OCI path issue with Chinese characters (like "HX工作目录")
|
||||
# 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
|
||||
|
||||
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}")
|
||||
|
||||
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:
|
||||
return ["Error"], [[str(e)]]
|
||||
|
||||
@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)
|
||||
|
||||
# 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"
|
||||
Reference in new issue
Block a user