This commit is contained in:
runny committed 2026-05-12 14:33:48 +08:00
1 parent 08a19ebe96
commit dea3b39048
6 files changed
+240 -33

No files matched your search

+30 -2
View File
@@ -37,6 +37,35 @@ from app.services.integration_api import IntegrationApiService
class DifyService:
"""Dify service wrapper."""
@staticmethod
def _build_chat_messages_url(base_url: str) -> str:
"""
Build the Dify chat-messages endpoint URL from a base URL.
Our config/agent base_url may be:
- https://api.dify.ai/v1
- http://host:port
- http://host:port/v1
- (user mistake) http://host:port/v1/chat-messages
This helper normalizes common mistakes and prevents duplicate `/v1/v1/...`.
"""
base = str(base_url or "").strip().rstrip("/")
if not base:
# Keep old behavior: downstream will fail with a request error.
return "/v1/chat-messages"
# User mistake hardening: strip endpoint suffix if someone stored it as base_url.
if base.endswith("/v1/chat-messages"):
base = base[: -len("/v1/chat-messages")].rstrip("/")
elif base.endswith("/chat-messages"):
base = base[: -len("/chat-messages")].rstrip("/")
# Config.DIFY_API_BASE defaults to ".../v1". Avoid double "/v1".
if base.endswith("/v1"):
return f"{base}/chat-messages"
return f"{base}/v1/chat-messages"
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
"""
@@ -60,8 +89,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
base_url = base_url.rstrip('/')
url = f"{base_url}/v1/chat-messages"
url = DifyService._build_chat_messages_url(base_url)
headers = {
'Authorization': f'Bearer {agent.dify_api_key}',
+13
View File
@@ -3,6 +3,7 @@ Integration API client for resolving original source-file download links.
"""
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import requests
from flask import current_app, has_app_context, has_request_context, request
@@ -13,6 +14,11 @@ from app.config import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _is_loopback_url(url: str) -> bool:
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
return host in {"127.0.0.1", "localhost", "::1"}
@staticmethod
def get_api_key() -> str:
if has_app_context():
@@ -32,6 +38,13 @@ class IntegrationApiService:
public_base = ""
if mode != "external":
# For server-side lookups inside containers/workers, an explicit integration
# endpoint is more reliable than a public loopback URL like 127.0.0.1:5002.
if configured and (
not has_request_context()
or IntegrationApiService._is_loopback_url(public_base)
):
return configured
if public_base:
return public_base
if has_request_context():
+130 -22
View File
@@ -2,10 +2,13 @@ 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:
@@ -33,6 +36,122 @@ class Text2SQLService:
return client_dirs[0]
return None
@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:
@@ -211,27 +330,8 @@ class Text2SQLService:
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()
# 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()
# 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}")
@@ -249,7 +349,15 @@ class Text2SQLService:
return columns, rows
except Exception as e:
return ["Error"], [[str(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):