更新环境配置,添加gevent和gunicorn依赖;新增chat_dify_by_workorder.py文件以处理工单对话逻辑;优化PgSql类中的异常处理,确保连接失败时抛出异常;改进意图识别API,使用单例模式管理意图识别器实例,增强线程安全性;新增workflow_chat.py文件以支持新工作流对话功能。
This commit is contained in:
@@ -4,16 +4,32 @@ from dotenv import load_dotenv
|
||||
from rag2_0.intent_recognition import IntentRecognizer
|
||||
import json
|
||||
import time
|
||||
import threading
|
||||
import datetime
|
||||
|
||||
# 加载环境变量
|
||||
load_dotenv()
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# 初始化意图识别器
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
base_url = os.getenv("OPENAI_API_BASE")
|
||||
model_name = os.getenv("LLM_MODEL_NAME", "gpt-3.5-turbo")
|
||||
recognizer = IntentRecognizer(api_key=api_key, base_url=base_url, model_name=model_name)
|
||||
# 创建线程锁,用于保护共享资源
|
||||
recognizer_lock = threading.Lock()
|
||||
|
||||
# 使用单例模式创建意图识别器
|
||||
class RecognizerSingleton:
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls):
|
||||
if cls._instance is None:
|
||||
with cls._lock:
|
||||
if cls._instance is None:
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
base_url = os.getenv("OPENAI_API_BASE")
|
||||
model_name = os.getenv("LLM_MODEL_NAME", "gpt-3.5-turbo")
|
||||
cls._instance = IntentRecognizer(api_key=api_key, base_url=base_url, model_name=model_name)
|
||||
return cls._instance
|
||||
|
||||
@app.route('/intent_recognize', methods=['POST'])
|
||||
def intent_recognize():
|
||||
@@ -22,10 +38,16 @@ def intent_recognize():
|
||||
query = data.get('query')
|
||||
if not query:
|
||||
return Response(json.dumps({"error": "缺少query参数"}, ensure_ascii=False), content_type='application/json; charset=utf-8', status=400)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# 获取单例实例并使用线程锁保护关键操作
|
||||
recognizer = RecognizerSingleton.get_instance()
|
||||
result = recognizer.process_query_with_slots(query)
|
||||
|
||||
end_time = time.time()
|
||||
print(f"意图识别耗时: {end_time - start_time:.2f}秒")
|
||||
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S %z")
|
||||
print(f"[{current_time}] [{os.getpid()}] [INFO] 意图识别耗时: {end_time - start_time:.2f}秒")
|
||||
|
||||
# 提取分类信息
|
||||
classification = result["classification"]
|
||||
@@ -63,7 +85,10 @@ def intent_recognize():
|
||||
}
|
||||
return Response(json.dumps(response_result, ensure_ascii=False), content_type='application/json; charset=utf-8')
|
||||
except Exception as e:
|
||||
print(f"意图识别出错: {str(e)}")
|
||||
return Response(json.dumps({"error": str(e)}, ensure_ascii=False), content_type='application/json; charset=utf-8', status=500)
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="0.0.0.0", port=8001)
|
||||
# 开发环境使用Flask内置服务器
|
||||
# 生产环境使用gunicorn支持高并发 poetry run gunicorn -w 10 -k gevent -b 0.0.0.0:8001 rag2_0.dify.intent_recognition_api:app
|
||||
app.run(host="0.0.0.0", port=8001, threaded=True)
|
||||
Reference in New Issue
Block a user