package com.smtaiserver.smtaiserver.control;
|
|
import com.smtaiserver.smtaiserver.core.SMTAIServerApp;
|
import com.smtaiserver.smtaiserver.core.SMTAIServerRequest;
|
import com.smtaiserver.smtaiserver.core.SMTCheckChatStreamView;
|
import com.smtaiserver.smtaiserver.database.SMTDatabase;
|
import com.smtaiserver.smtaiserver.database.SMTDatabase.DBRecord;
|
import com.smtaiserver.smtaiserver.database.SMTDatabase.DBRecords;
|
import com.smtaiserver.smtaiserver.javaai.qwen.agent.SMTQwenAgent;
|
import com.smtservlet.core.SMTRequest;
|
import com.smtservlet.util.Json;
|
import com.smtservlet.util.SMTJsonWriter;
|
import com.smtservlet.util.SMTStatic;
|
import java.util.*;
|
import java.util.regex.Pattern;
|
import okhttp3.OkHttpClient;
|
import okhttp3.Request;
|
import okhttp3.Response;
|
import org.apache.logging.log4j.LogManager;
|
import org.apache.logging.log4j.Logger;
|
import org.dom4j.Document;
|
import org.springframework.web.servlet.ModelAndView;
|
|
public class SMTWorkflowManagerControl
|
{
|
|
private static final Logger _logger = LogManager.getLogger(SMTWorkflowManagerControl.class);
|
private static String[] _flowFuncNames = new String[] {
|
"assessment", "评估"
|
};
|
|
public ModelAndView publishWorkflowAgent(SMTAIServerRequest tranReq) throws Exception
|
{
|
String id = tranReq.convParamToString("agent_id", true);
|
String publish = tranReq.convParamToString("publish", true);
|
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
DBRecords recs = db.querySQL("SELECT * FROM ai_agent_workflow WHERE agent_id=?", new Object[] {
|
id
|
});
|
if(recs.getRowCount() == 0)
|
return tranReq.returnJsonState(false, "未发现工作流id", null);
|
|
String errmsg = null;
|
|
// 检查工作流是否合法,如果不合法直接设置为"N"
|
try
|
{
|
DBRecord rec = recs.getRecord(0);
|
SMTQwenAgent agent = (SMTQwenAgent) Class.forName(rec.getString("clz_name")).newInstance();
|
agent.initInstance(rec);
|
}
|
catch(Exception ex)
|
{
|
errmsg = "工作流配置错误 : " + SMTStatic.toString(ex);
|
_logger.error("工作流配置错误 : " + SMTStatic.toString(ex));
|
publish = "N";
|
}
|
|
db.executeSQL("UPDATE ai_agent_workflow SET agent_order=? WHERE agent_id=?", new Object[] {
|
"Y".equals(publish) ? 1 : 0,
|
id
|
});
|
|
String curPublish = (recs.getRecord(0).getInteger("agent_order") > 0) ? "Y" : "N";
|
if(!publish.equals(curPublish))
|
SMTAIServerApp.getApp().clearQwenAgentManager();
|
|
SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, errmsg, null);
|
jsonWr.addKeyValue("publish", publish);
|
return tranReq.returnJson(jsonWr);
|
}
|
finally
|
{
|
db.close();
|
}
|
}
|
|
public ModelAndView getFlowJsonFuncNames(SMTAIServerRequest tranReq) throws Exception
|
{
|
SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
|
jsonWr.beginArray("funcs");
|
{
|
for(int i = 0; i < _flowFuncNames.length; i += 2)
|
{
|
jsonWr.beginMap(null);
|
{
|
jsonWr.addKeyValue("id", _flowFuncNames[i + 0]);
|
jsonWr.addKeyValue("title", _flowFuncNames[i + 1]);
|
}
|
jsonWr.endMap();
|
}
|
}
|
jsonWr.endArray();
|
|
return tranReq.returnJson(jsonWr);
|
}
|
|
public ModelAndView checkWorkflowAgentValidate(SMTAIServerRequest tranReq) throws Exception
|
{
|
String agentId = tranReq.convParamToString("agent_id", true);
|
String question = tranReq.convParamToString("question", true);
|
|
DBRecords recs;
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
recs = db.querySQL("SELECT * FROM ai_agent_workflow WHERE agent_id=?", new Object[] {
|
agentId
|
});
|
if(recs.getRowCount() == 0)
|
return tranReq.returnJsonState(false, "未发现记录", null);
|
}
|
finally
|
{
|
db.close();
|
}
|
|
DBRecord rec = recs.getRecord(0);
|
SMTQwenAgent agent = (SMTQwenAgent) Class.forName(rec.getString("clz_name")).newInstance();
|
agent.initInstance(rec);
|
Map<String, SMTQwenAgent> mapId2Agent = new HashMap<>();
|
mapId2Agent.put(agent.getAgentId(), agent);
|
|
return new ModelAndView(new SMTCheckChatStreamView(tranReq, question, mapId2Agent));
|
|
}
|
|
public ModelAndView getFlowJsonAgentNames(SMTRequest tranReq) throws Exception
|
{
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
DBRecords recs = db.querySQL(
|
" SELECT agent_id, agent_title FROM ("
|
+ " SELECT agent_id, agent_title FROM ai_agent_amis"
|
+ " UNION ALL"
|
+ " SELECT knowlg_id, knowlg_title FROM ai_agent_knowlg"
|
+ " UNION ALL"
|
+ " SELECT agent_id, agent_title FROM ai_agent_metrics"
|
+ " UNION ALL"
|
+ " SELECT agent_id, agent_title FROM ai_agent_workflow"
|
+ ") T WHERE agent_title IS NOT NULL ORDER BY agent_title"
|
, null);
|
|
SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
|
jsonWr.beginArray("agents");
|
for(DBRecord rec : recs.getRecords())
|
{
|
jsonWr.beginMap(null);
|
{
|
jsonWr.addKeyValue("id", rec.getString("agent_id"));
|
jsonWr.addKeyValue("title", rec.getString("agent_title"));
|
}
|
jsonWr.endMap();
|
}
|
jsonWr.endArray();
|
|
|
return tranReq.returnJson(jsonWr);
|
}
|
finally
|
{
|
db.close();
|
}
|
|
}
|
|
public ModelAndView updateWorkflowJsonFlow(SMTRequest tranReq) throws Exception
|
{
|
String agentId = tranReq.convParamToString("agent_id", true);
|
String sJson = tranReq.convParamToString("json_flow", true);
|
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
DBRecords recs = db.querySQL("SELECT * FROM ai_agent_workflow WHERE agent_id=?", new Object[] {
|
agentId
|
});
|
if(recs.getRowCount() == 0)
|
return tranReq.returnJsonState(false, "未发现工作流id", null);
|
|
db.executeSQL("UPDATE ai_agent_workflow SET clz_arguments = ? WHERE agent_id=?", new Object[] {
|
sJson,
|
agentId
|
});
|
|
if(recs.getRecord(0).getInteger("agent_order") > 0)
|
SMTAIServerApp.getApp().clearQwenAgentManager();
|
|
return tranReq.returnJsonState(true, null, null);
|
}
|
finally
|
{
|
db.close();
|
}
|
}
|
|
public ModelAndView getWorkflowJsonFlow(SMTRequest tranReq) throws Exception
|
{
|
String agentId = tranReq.convParamToString("agent_id", true);
|
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
DBRecords recs = db.querySQL("SELECT clz_arguments FROM ai_agent_workflow WHERE agent_id=?", new Object[] {
|
agentId
|
});
|
|
if(recs.getRowCount() == 0)
|
throw new Exception("can't find agent");
|
|
String sJson = recs.getRecord(0).getString("clz_arguments");
|
if(SMTStatic.isNullOrEmpty(sJson))
|
return tranReq.returnJsonState(true, null, null);
|
|
SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
|
jsonWr.addKeyRaw("json_flow", sJson);
|
|
return tranReq.returnJson(jsonWr);
|
}
|
finally
|
{
|
db.close();
|
}
|
}
|
|
|
public ModelAndView updateWorkflowAgent(SMTRequest tranReq) throws Exception
|
{
|
String agentId = tranReq.convParamToString("agent_id", true);
|
String title = tranReq.convParamToString("title", true);
|
String prompt = tranReq.convParamToString("prompt", true);
|
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
db.executeSQL("UPDATE ai_agent_workflow SET agent_title=?, agent_xml=?, update_time=? WHERE agent_id=?", new Object[] {
|
title,
|
"<TITLE>" + SMTStatic.convHtmlBodyToString(prompt) + "</TITLE>",
|
new Date(),
|
agentId
|
});
|
|
return tranReq.returnJsonState(true, null, null);
|
}
|
finally
|
{
|
db.close();
|
}
|
}
|
|
public ModelAndView deleteWorkflowAgent(SMTRequest tranReq) throws Exception
|
{
|
String agentId = tranReq.convParamToString("agent_id", true);
|
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
db.executeSQL("DELETE FROM ai_agent_workflow WHERE agent_id=?", new Object[] {agentId});
|
|
return tranReq.returnJsonState(true, null, null);
|
}
|
finally
|
{
|
db.close();
|
}
|
}
|
|
public ModelAndView addWorkflowAgent(SMTRequest tranReq) throws Exception
|
{
|
String groupId = tranReq.convParamToString("group_id", true);
|
String title = tranReq.convParamToString("title", true);
|
String prompt = tranReq.convParamToString("prompt", true);
|
String innerCall = tranReq.convParamToString("inner_call", true);
|
String agentId = "a_" + SMTStatic.newUUID();
|
Date time = new Date();
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
db.executeSQL(
|
" INSERT INTO ai_agent_workflow"
|
+ " (agent_id,agent_group,agent_type,agent_title,agent_xml,clz_name,clz_arguments,agent_order,is_debug,create_user,create_time,update_time,agent_note,inner_call)"
|
+ " VALUES"
|
+ " (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
|
, new Object[] {
|
agentId,
|
groupId,
|
"query",
|
title,
|
"<TITLE>" + SMTStatic.convHtmlBodyToString(prompt) + "</TITLE>",
|
"com.smtaiserver.smtaiserver.javaai.qwen.agent.SMTQwenAgentJsonWorkflow",
|
null,
|
0,
|
null,
|
tranReq.getLoginUserId(),
|
time,
|
time,
|
null,
|
innerCall
|
});
|
|
SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
|
jsonWr.addKeyValue("agent_id", agentId);
|
|
return tranReq.returnJson(jsonWr);
|
}
|
finally
|
{
|
db.close();
|
}
|
|
}
|
|
|
public ModelAndView getWorkflowAgentList(SMTRequest tranReq) throws Exception
|
{
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
DBRecords recs = db.querySQL(
|
" SELECT A.agent_id, A.agent_title, A.agent_xml, A.clz_arguments, A.create_time, A.update_time, A.agent_note, A.agent_order, A.agent_group, A.inner_call, B.user_name"
|
+ " FROM (SELECT * FROM ai_agent_workflow WHERE clz_name='com.smtaiserver.smtaiserver.javaai.qwen.agent.SMTQwenAgentJsonWorkflow') "
|
+ " A LEFT JOIN sys_user_info B ON A.create_user=B.user_id", null);
|
|
SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
|
|
jsonWr.beginArray("values");
|
for(DBRecord rec : recs.getRecords())
|
{
|
jsonWr.beginMap(null);
|
{
|
jsonWr.addKeyValue("id", rec.getString("agent_id"));
|
jsonWr.addKeyValue("title", rec.getString("agent_title"));
|
jsonWr.addKeyValue("create_user", rec.getString("user_name"));
|
jsonWr.addKeyValue("create_time", rec.getString("create_time"));
|
jsonWr.addKeyValue("note", rec.getString("agent_note"));
|
jsonWr.addKeyValue("agent_group", rec.getString("agent_group"));
|
jsonWr.addKeyValue("inner_call", rec.getString("inner_call"));
|
jsonWr.addKeyValue("published", (rec.getInteger("agent_order") > 0) ? "Y" : "N");
|
|
jsonWr.beginMap("supervisor");
|
{
|
Document doc = SMTStatic.convStrToXmlDoc("<ROOT>" + rec.getString("agent_xml") + "</ROOT>");
|
String prompt = SMTStatic.trimStrLines(doc.selectSingleNode("ROOT/TITLE").getText());
|
jsonWr.addKeyValue("prompt", prompt);
|
}
|
jsonWr.endMap();
|
}
|
jsonWr.endMap();
|
}
|
jsonWr.endArray();
|
|
return tranReq.returnJson(jsonWr);
|
}
|
finally
|
{
|
db.close();
|
}
|
}
|
|
public ModelAndView getLLMInfoList(SMTRequest tranReq) throws Exception
|
{
|
SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
|
try
|
{
|
DBRecords recsFactory = db.querySQL("SELECT * FROM ai_llm_factory", null);
|
DBRecords recsConnection = db.querySQL("SELECT * FROM ai_llm_connect", null);
|
|
SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
|
|
jsonWr.beginArray("factorys");
|
for(DBRecord rec : recsFactory.getRecords())
|
{
|
jsonWr.beginMap(null);
|
{
|
jsonWr.addKeyValue("factory_id", rec.getString("factory_id"));
|
jsonWr.addKeyValue("factory_title", rec.getString("factory_title"));
|
}
|
jsonWr.endMap();
|
}
|
jsonWr.endArray();
|
|
jsonWr.beginArray("connections");
|
for(DBRecord rec : recsConnection.getRecords())
|
{
|
jsonWr.beginMap(null);
|
{
|
jsonWr.addKeyValue("connect_id", rec.getString("connect_id"));
|
jsonWr.addKeyValue("factory_id", rec.getString("factory_id"));
|
jsonWr.addKeyValue("connect_title", rec.getString("connect_title"));
|
}
|
jsonWr.endMap();
|
}
|
jsonWr.endArray();
|
|
|
return tranReq.returnJson(jsonWr);
|
}
|
finally
|
{
|
db.close();
|
}
|
}
|
|
/**
|
* 查询n8n工作流列表
|
* @param tranReq
|
* @return
|
* @throws Exception
|
*/
|
public ModelAndView getN8NNameList(SMTRequest tranReq) throws Exception {
|
String active = tranReq.convParamToString("active", true);
|
String tags = tranReq.convParamToString("tags", false);
|
String name = tranReq.convParamToString("name", false);
|
String projectId = tranReq.convParamToString("projectId", false);
|
String excludePinnedData = tranReq.convParamToString("excludePinnedData", false);
|
int limit = 250; // 上限250条
|
|
// 构建请求URL
|
String requestUrl = SMTAIServerApp.buildUrl(active, tags, name, projectId, excludePinnedData, limit);
|
|
// 创建OkHttpClient对象
|
OkHttpClient client = new OkHttpClient();
|
|
String n8nApiKey = (String) SMTAIServerApp.getApp().getGlobalConfig("n8n_api_key", null);
|
// 创建请求头
|
Request request = new Request.Builder()
|
.url(requestUrl)
|
.addHeader("X-N8N-API-KEY", n8nApiKey)
|
.addHeader("accept", "application/json")
|
.build();
|
Response response = client.newCall(request).execute();
|
String res = response.body().string();
|
Json.Reader reader = new Json.Reader();
|
Json read = (Json) reader.read(res, null);
|
SMTJsonWriter jsonWriter = new SMTJsonWriter(false);
|
|
// 构建最终的返回数据结构
|
List<Json> resultList = new ArrayList<>();
|
|
try {
|
if (response.body() != null) {
|
List<Json> data = read.safeGetJsonList("data");
|
for (Json date : data) {
|
String flOWName = date.safeGetStr("name", null);
|
String id = date.safeGetStr("id", null);
|
|
// 创建一个新的 JSON 对象
|
SMTJsonWriter flowObj = new SMTJsonWriter(false);
|
flowObj.addKeyValue("id", id);
|
flowObj.addKeyValue("flow_name", flOWName);
|
|
List<Json> nodeList = date.safeGetJsonList("nodes");
|
for (Json node : nodeList) {
|
String type = node.safeGetStr("type", null);
|
if (type.equals("n8n-nodes-base.webhook")) {
|
Json parameters = node.safeGetJson("parameters");
|
String path = parameters.safeGetStr("path", null);
|
Pattern pattern = Pattern.compile("/:?([^/]+)");
|
List<String> pathRes = SMTAIServerApp.extractParts(path, pattern);
|
flowObj.addKeyValue("parameters", pathRes);
|
}
|
}
|
// 将创建的 flowObj 添加到 resultList 中
|
resultList.add(flowObj.getRootJson());
|
}
|
|
// 将 resultList 设置为 "data" 键的值
|
jsonWriter.addKeyValue("data", resultList);
|
}
|
jsonWriter.addKeyValue("json_ok", true);
|
return tranReq.returnJson(jsonWriter);
|
} catch (Exception e) {
|
throw new Exception(e);
|
}
|
}
|
}
|