qfrjava
7 天以前 002aac2eb465e9b41a6209b71c241b214ac30258
JAVA/SMTAIServer/src/main/java/com/smtaiserver/smtaiserver/control/SMTJavaAIControl.java
@@ -1,24 +1,5 @@
package com.smtaiserver.smtaiserver.control;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.smtaiserver.smtaiserver.attach.SMTAIAttachMetricDef;
import com.smtaiserver.smtaiserver.attach.SMTAIAttachTableDef;
import com.smtaiserver.smtaiserver.attach.SMTAIAttachTableDef.SMTAIAttachTableColumn;
@@ -39,9 +20,62 @@
import com.smtservlet.util.Json;
import com.smtservlet.util.SMTJsonWriter;
import com.smtservlet.util.SMTStatic;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
public class SMTJavaAIControl 
{
   private class SMTCallAgentArgStreamView implements View
   {
      private SMTAIServerRequest    _tranReq;
      public SMTCallAgentArgStreamView(SMTAIServerRequest tranReq)
      {
         _tranReq = tranReq;
         _tranReq.setChunkedMode(true);
      }
      @Override
      public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception
      {
         String agentId = _tranReq.convParamToString("agent_id", true);
         Json jsonArgs = _tranReq.convParamToJson("call_args", true);
         response.setCharacterEncoding("UTF-8");
         response.setContentType("text/plain;charset=UTF-8");
         response.setHeader("smtstream", "chunked");
         try
         {
            SMTQwenAgent agent = SMTAIServerApp.getApp().getQwenAgentManager().getAgentById(agentId);
            if(agent == null)
               throw new Exception("can't find agent : " + agentId);
            SMTLLMConnect llm = SMTAIServerApp.getApp().allocLLMConnect(null);
            if(!jsonArgs.has("question"))
               jsonArgs.set("question", "");
            String loginUserId = _tranReq.getLoginUserId();
            agent.callAgents("/", jsonArgs, llm, "", _tranReq);
         }
         catch(Exception ex)
         {
            _tranReq.traceLLMDebug("call chat stream excetion : \n" + SMTStatic.toString(ex));
            _tranReq.sendChunkedBlock("error", ex.getMessage());
         }
         _tranReq.sendChunkedBlock("finish", "");
      }
   }
   private class SMTAgentStreamView implements View
   {
      private SMTAIServerRequest    _tranReq;
@@ -96,10 +130,14 @@
               {
                  for(MultipartFile file : files)
                  {
                     String fileId = SMTStatic.newUUID();
                     String fileText="";
                     String fileSuffix = (String) SMTAIServerApp.getApp().getGlobalConfig("file_suffix", false);
                     String fileName = new File(file.getOriginalFilename()).getName();
                     byte[] fileData = readAttachFile(file);
                     String fileText = new String(fileData, "UTF-8");
                     if (fileSuffix.contains(fileName.substring(fileName.lastIndexOf(".") + 1))) {
                        fileText = SMTAIServerApp.fileTranslTxt(file);
                     }
                     String fileId = SMTStatic.newUUID();
                     db.executeSQL(
                          " INSERT INTO chat_history_attach(attach_id, attach_type, attach_title, attach_bytes)"
                        + " VALUES(?,?,?,?)", new Object[] {
@@ -127,7 +165,13 @@
            tranReq.setAttachTables(jsonTables);
            _mustRawMode = true;
         }
         Json jsonMetrics = tranReq.convParamToJson("metrics", false);
         if(jsonMetrics != null)
         {
            tranReq.setJsonAttachMetrics(jsonMetrics);
            _mustRawMode = true;
         }
         _tranReq = tranReq;
         _tranReq.setChunkedMode(true);
      }
@@ -251,7 +295,313 @@
      
      return tranReq.returnJson(jsonWr);
   }
  public ModelAndView createOrder(SMTAIServerRequest tranReq) throws Exception {
//    String title = tranReq.convParamToString("title", true);
//    String wstypeid = tranReq.convParamToString("wstypeid", false);
//    String wstypename = tranReq.convParamToString("wstypename", false);
//    String urgencylevel = tranReq.convParamToString("urgencylevel", false);
//    String shape = tranReq.convParamToString("shape", false);
//    String deadline = tranReq.convParamToString("deadline", false);
//    String stepstatus = tranReq.convParamToString("stepstatus", false);
//    String originatetypetext = tranReq.convParamToString("originatetypetext", false);
//    String content = tranReq.convParamToString("content", false);
//    String address = tranReq.convParamToString("address", false);
//    String stepid = tranReq.convParamToString("stepid", false);
//    String org = tranReq.convParamToString("org", false);
//    String deptname = tranReq.convParamToString("deptname", false);
//    String dealtime = tranReq.convParamToString("dealtime", false);
//    String username = tranReq.convParamToString("username", false);
//    String contactname = tranReq.convParamToString("contactname", false);
//    String contactphone = tranReq.convParamToString("contactphone", false);
//    String acceptuserid = tranReq.convParamToString("acceptuserid", false);
//    String acceptusername = tranReq.convParamToString("acceptusername", false);
//    String acceptuseraccount = tranReq.convParamToString("acceptuseraccount", false);
//    String dealuserid = tranReq.convParamToString("dealuserid", false);
//    String dealusername = tranReq.convParamToString("dealusername", false);
//    String dealuseraccount = tranReq.convParamToString("dealuseraccount", false);
//    String flowstatus = tranReq.convParamToString("flowstatus", false);
//    String attachment = tranReq.convParamToString("attachment", false);
//    String creator = tranReq.convParamToString("creator", false);
//    String createtime = tranReq.convParamToString("createtime", false);
//    String isplan = tranReq.convParamToString("isplan", false);
//    String originateid = tranReq.convParamToString("originateid", false);
//    String appointstarttime = tranReq.convParamToString("appointstarttime", false);
//    String appointendtime = tranReq.convParamToString("appointendtime", false);
//    String parentid = tranReq.convParamToString("parentid", false);
//    String relateids = tranReq.convParamToString("relateids", false);
//    String oname = tranReq.convParamToString("oname", false);
//    String otype = tranReq.convParamToString("otype", false);
//
//    SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
//    try {
//      db.executeSQL(
//          "INSERT INTO work_order_list("
//              + "order_id, title, wstypeid, wstypename, urgencylevel, shape, deadline, stepstatus, "
//              + "originatetypetext, content, address, step_id, org, deptname, dealtime, username, contactname, "
//              + "contactphone, acceptuserid, acceptusername, acceptuseraccount, dealuserid, dealusername, "
//              + "dealuseraccount, flowstatus, attachment, creator, createtime, isplan, originateid, "
//              + "appointstarttime, appointendtime, parentid, relateids,is_notify,oname,otype"
//              + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)",
//          new Object[] {
//            SMTStatic.newUUID(),
//            title,
//            wstypeid,
//            wstypename,
//            urgencylevel,
//            shape,
//            deadline,
//            stepstatus,
//            originatetypetext,
//            content,
//            address,
//            stepid,
//            org,
//            deptname,
//            dealtime,
//            username,
//            contactname,
//            contactphone,
//            acceptuserid,
//            acceptusername,
//            acceptuseraccount,
//            dealuserid,
//            dealusername,
//            dealuseraccount,
//            flowstatus,
//            attachment,
//            creator,
//            new Date(),
//            isplan,
//            originateid,
//            appointstarttime,
//            appointendtime,
//            parentid,
//            relateids,
//            "N",
//            oname,
//            otype
//          });
//    } catch (Exception e) {
//      throw new Exception("数据库错误", e);
//    }
//
//    return tranReq.returnJsonState(true, null, null);
     return tranReq.returnJsonState(true, null, null);
  }
  public ModelAndView updateOrderStatus(SMTAIServerRequest tranReq) throws Exception {
    String id = tranReq.convParamToString("id", true);
    String shape = tranReq.convParamToString("shape", false);
    Integer stepstatus = tranReq.convParamToInteger("stepstatus", true); // 状态代号,如已完成
    SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
    try {
        DBRecords dbRecords =
            db.querySQL("select * from work_order_list where order_id = ?", new Object[] {id});
      Integer statusBeforeModification = dbRecords.getRecords().get(0).getInteger("stepstatus");
   if (shape == null||SMTStatic.isNullOrEmpty(shape)){
       shape =(String) dbRecords.getRecords().get(0).getValue("shape");
   }
      db.executeSQL(
          "UPDATE work_order_list SET stepstatus = ? , status_update_time = ? , is_notify = 'N',shape=ST_GeomFromText(?) WHERE order_id = ?",
          new Object[] {stepstatus,  new Date(),shape,id});
      String sql = "INSERT INTO ai_sys.work_order_detail (order_id, status_before_modification, status_after_modification,createTime) VALUES (?, ?, ?, ?)";
      db.executeSQL(sql, new Object[] {id, statusBeforeModification, stepstatus, new Date()});
    } catch (Exception e) {
      throw new Exception("更新工单状态失败", e);
    } finally {
      db.close();
   }
    return tranReq.returnJsonState(true, null, null);
  }
   public ModelAndView updateOrder(SMTAIServerRequest tranReq) throws Exception {
      String title = tranReq.convParamToString("title", true);
      String orderId = tranReq.convParamToString("orderId", true);
      String wstypeid = tranReq.convParamToString("wstypeid", false);
      String wstypename = tranReq.convParamToString("wstypename", false);
      String urgencylevel = tranReq.convParamToString("urgencylevel", false);
      String shape = tranReq.convParamToString("shape", false);
      String deadline = tranReq.convParamToString("deadline", false);
      String stepstatus = tranReq.convParamToString("stepstatus", false);
      String originatetypetext = tranReq.convParamToString("originatetypetext", false);
      String content = tranReq.convParamToString("content", false);
      String address = tranReq.convParamToString("address", false);
      String stepid = tranReq.convParamToString("stepid", false);
      String org = tranReq.convParamToString("org", false);
      String deptname = tranReq.convParamToString("deptname", false);
      String dealtime = tranReq.convParamToString("dealtime", false);
      String username = tranReq.convParamToString("username", false);
      String contactname = tranReq.convParamToString("contactname", false);
      String contactphone = tranReq.convParamToString("contactphone", false);
      String acceptuserid = tranReq.convParamToString("acceptuserid", false);
      String acceptusername = tranReq.convParamToString("acceptusername", false);
      String acceptuseraccount = tranReq.convParamToString("acceptuseraccount", false);
      String dealuserid = tranReq.convParamToString("dealuserid", false);
      String dealusername = tranReq.convParamToString("dealusername", false);
      String dealuseraccount = tranReq.convParamToString("dealuseraccount", false);
      String flowstatus = tranReq.convParamToString("flowstatus", false);
      String attachment = tranReq.convParamToString("attachment", false);
      String creator = tranReq.convParamToString("creator", false);
      String isplan = tranReq.convParamToString("isplan", false);
      String originateid = tranReq.convParamToString("originateid", false);
      String appointstarttime = tranReq.convParamToString("appointstarttime", false);
      String appointendtime = tranReq.convParamToString("appointendtime", false);
      String parentid = tranReq.convParamToString("parentid", false);
      String relateids = tranReq.convParamToString("relateids", false);
      String oname = tranReq.convParamToString("oname", false);
      String otype = tranReq.convParamToString("otype", false);
      SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
      try {
         db.executeSQL(
               "UPDATE work_order_list SET "
                     + "title = ?, "
                     + "wstypeid = ?, "
                     + "wstypename = ?, "
                     + "urgencylevel = ?, "
                     + "shape = ?, "
                     + "deadline = ?, "
                     + "stepstatus = ?, "
                     + "originatetypetext = ?, "
                     + "content = ?, "
                     + "address = ?, "
                     + "step_id = ?, "
                     + "org = ?, "
                     + "deptname = ?, "
                     + "dealtime = ?, "
                     + "username = ?, "
                     + "contactname = ?, "
                     + "contactphone = ?, "
                     + "acceptuserid = ?, "
                     + "acceptusername = ?, "
                     + "acceptuseraccount = ?, "
                     + "dealuserid = ?, "
                     + "dealusername = ?, "
                     + "dealuseraccount = ?, "
                     + "flowstatus = ?, "
                     + "attachment = ?, "
                     + "creator = ?, "
                     + "createtime = ?, "
                     + "isplan = ?, "
                     + "originateid = ?, "
                     + "appointstarttime = ?, "
                     + "appointendtime = ?, "
                     + "parentid = ?, "
                     + "relateids = ?, "
                     + "is_notify = ?, "
                     + "oname = ?, "
                     + "otype = ? "
                     + "WHERE order_id = ?",
               new Object[]{
                     title,
                     wstypeid,
                     wstypename,
                     urgencylevel,
                     shape,
                     deadline,
                     stepstatus,
                     originatetypetext,
                     content,
                     address,
                     stepid,
                     org,
                     deptname,
                     dealtime,
                     username,
                     contactname,
                     contactphone,
                     acceptuserid,
                     acceptusername,
                     acceptuseraccount,
                     dealuserid,
                     dealusername,
                     dealuseraccount,
                     flowstatus,
                     attachment,
                     creator,
                     new Date(),
                     isplan,
                     originateid,
                     appointstarttime,
                     appointendtime,
                     parentid,
                     relateids,
                     "N",
                     oname,
                     otype,
                     orderId
               });
      } finally {
         db.close();
      }
      return tranReq.returnJsonState(true, null, null);
   }
  /**
   * 节点状态更新
   *
   * @param tranReq
   * @return
   * @throws Exception
   */
  public ModelAndView updateOrderFlowStatus(SMTAIServerRequest tranReq) throws Exception {
    String id = tranReq.convParamToString("id", true);
    Integer flowstatus = tranReq.convParamToInteger("flowstatus", true);
    SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
    try {
      db.executeSQL(
          "UPDATE work_order_list SET flowstatus = ? WHERE order_id = ?",
          new Object[] {flowstatus, id});
    } catch (Exception e) {
      throw new Exception("节点状态更新失败", e);
    } finally {
      db.close();
    }
    return tranReq.returnJsonState(true, null, null);
  }
  public ModelAndView getOrderList(SMTAIServerRequest tranReq) throws Exception {
    SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
    SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
    try {
      DBRecords recs =
          db.querySQL(
              "SELECT *,ST_AsText(address_shape) as address_shape_str  ,ST_AsText(shape) as shape_str FROM work_order_list",
              null);
      if (recs.getRowCount() != 0) {
        jsonWr.beginArray("values"); // 开始一个数组,key为 "values"
        for (DBRecord rec : recs.getRecords()) {
          jsonWr.beginMap(null); // 每条记录是一个对象
          for (String colName : rec.getColNames()) {
            jsonWr.addKeyValue(colName, rec.getString(colName)); // 添加每个字段
          }
          jsonWr.endMap(); // 结束一个对象
        }
        jsonWr.endArray(); // 结束数组
        return tranReq.returnJson(jsonWr);
      } else {
        return tranReq.returnJsonState(false, "未找到工单", null);
      }
    } catch (Exception e) {
      throw new Exception("查询工单失败", e);
    }
  }
   public ModelAndView disconnectBroadcastChat(SMTAIServerRequest tranReq) throws Exception 
   {
      String userId = tranReq.getLoginUserId();
@@ -349,7 +699,7 @@
          String sampleId = tranReq.convParamToString("sample_id", false);
          String llmId = tranReq.convParamToString("llm_id", false);
          String historyGroupId = tranReq.convParamToString("history_group_id", true);
          String question = java.net.URLDecoder.decode(tranReq.convParamToString("question", true), "UTF-8");
          String question = tranReq.convParamToString("question", true);
          String processId = tranReq.convParamToString("process_id", false);
          String sRawMode = tranReq.convParamToString("raw_mode", false);
          String prevQuestion = tranReq.convParamToString("prev_question", false);
@@ -358,8 +708,6 @@
   
          if(SMTStatic.isNullOrEmpty(groupType))
             groupType = "业务场景";
          else
             groupType = java.net.URLDecoder.decode(groupType, "UTF-8");
          
          tranReq.setCurQuestionPos(curPos);
          tranReq.setCurGroupType(groupType);
@@ -404,53 +752,62 @@
   {
      tranReq.sendChunkedBlock("begin", "分析[" + jsonSummary.safeGetStr("title", "") + "]的数据");
      
      StringBuilder sbQuestion = new StringBuilder();
      sbQuestion.append("以下是[" + jsonSummary.safeGetStr("title", "") + "]的数据,请对其进行分析,并提炼出最精简的结果。\n");
      
      boolean isFirst = true;
      int maxCol = 0;
      for(Json jsonCol : jsonSummary.getJson("cols").asJsonList())
      boolean set = tranReq.setSendStarStream(true);
      try
      {
         if(isFirst)
            isFirst = false;
         else
            sbQuestion.append(",");
         sbQuestion.append(jsonCol.safeGetStr("title", "值"));
         maxCol ++;
      }
      sbQuestion.append("\n");
      for(Json jsonRow : jsonSummary.getJson("values").asJsonList())
      {
         List<Json> listJsonRow = jsonRow.asJsonList();
         for(int i = 0; i < maxCol; i ++)
         StringBuilder sbQuestion = new StringBuilder();
         sbQuestion.append("以下是[" + jsonSummary.safeGetStr("title", "") + "]的数据,请对其进行分析,并提炼出最精简的结果。\n");
         boolean isFirst = true;
         int maxCol = 0;
         for(Json jsonCol : jsonSummary.getJson("cols").asJsonList())
         {
            if(i > 0)
               sbQuestion.append(",");
            Json jsonValue = listJsonRow.get(i);
            if(jsonValue.isNull())
            {
               sbQuestion.append("");
            }
            if(isFirst)
               isFirst = false;
            else
            {
               sbQuestion.append(listJsonRow.get(i).asString());
            }
               sbQuestion.append(",");
            sbQuestion.append(jsonCol.safeGetStr("title", "值"));
            maxCol ++;
         }
         sbQuestion.append("\n");
         
         if(sbQuestion.length() > 4096)
            break;
         for(Json jsonRow : jsonSummary.getJson("values").asJsonList())
         {
            List<Json> listJsonRow = jsonRow.asJsonList();
            for(int i = 0; i < maxCol; i ++)
            {
               if(i > 0)
                  sbQuestion.append(",");
               Json jsonValue = listJsonRow.get(i);
               if(jsonValue.isNull())
               {
                  sbQuestion.append("");
               }
               else
               {
                  sbQuestion.append(listJsonRow.get(i).asString());
               }
            }
            sbQuestion.append("\n");
            if(sbQuestion.length() > 4096)
               break;
         }
         String answer = llm.callWithMessage(null, sbQuestion.toString(), tranReq).replace("\r", "");
         jsonWrConclusion.beginMap(null);
         {
            jsonWrConclusion.addKeyValue("agent_key", agentKey);
            jsonWrConclusion.addKeyValue("report", answer);
         }
         jsonWrConclusion.endMap();
      }
      String answer = llm.callWithMessage(null, sbQuestion.toString(), tranReq).replace("\r", "");
      jsonWrConclusion.beginMap(null);
      finally
      {
         jsonWrConclusion.addKeyValue("agent_key", agentKey);
         jsonWrConclusion.addKeyValue("report", answer);
         tranReq.setSendStarStream(set);
      }
      jsonWrConclusion.endMap();
      
      return null;
   }
@@ -1239,10 +1596,12 @@
       String attachTableId = tranReq.convParamToString("id", true);
       Json jsonFilters = tranReq.convParamToJson("filter", false);
       Json jsonOrders = tranReq.convParamToJson("order", false);
       Integer limit = tranReq.convParamToInteger("limit", false);
       SMTAIAttachTableDef attachTableDef = (SMTAIAttachTableDef) SMTAIServerApp.getApp().getAttachTableDef(attachTableId);
       if (limit==null)
         limit=100;
       SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
       attachTableDef.queryRecordsToJson(jsonFilters, jsonOrders, jsonWr);
       attachTableDef.queryRecordsToJson(jsonFilters, jsonOrders, jsonWr,limit);
       
       return tranReq.returnJson(jsonWr);
       
@@ -1288,14 +1647,122 @@
       Date startTime = tranReq.convParamToDate("start_time", true);
          Date endTime = tranReq.convParamToDate("end_time", true);
       Json jsonQuotaKeys = tranReq.convParamToJson("quota_keys", true);
       Integer limit = tranReq.convParamToInteger("limit", false);
      if (limit==null)
         limit=100;
       SMTAIAttachMetricDef attachMetricDef = SMTAIServerApp.getApp().getAttachMetricDef(attachMetricId);
       
       SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
       jsonWr.beginArray("values");
       attachMetricDef.queryValueToJson(startTime, endTime, jsonQuotaKeys, jsonWr);
       jsonWr.endArray();
       attachMetricDef.queryValueToJson(startTime, endTime, jsonQuotaKeys, jsonWr,limit);
       
       return tranReq.returnJson(jsonWr);
    }
    public ModelAndView callLLM(SMTAIServerRequest tranReq) throws Exception
    {
       String llmId = tranReq.convParamToString("llm_id", false);
       Json jsonSystems = tranReq.convParamToJson("system_json", false);
       String question = tranReq.convParamToString("question", true);
       boolean answerIsJson = tranReq.convParamToBoolean("answer_is_json", true);
       SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
       SMTLLMConnect conn = SMTAIServerApp.getApp().allocLLMConnect(llmId);
       List<String> listSystem = new ArrayList<>();
       if(jsonSystems != null)
       {
          for(Json jsonSystem : jsonSystems.asJsonList())
          {
             listSystem.add(jsonSystem.asString());
          }
       }
       String answer = conn.callWithMessage(listSystem, question, tranReq);
       if(answerIsJson)
       {
          jsonWr.addKeyRaw("answer", SMTStatic.convLLMAnswerToJson(answer, false));
       }
       else
       {
          jsonWr.addKeyValue("answer", answer);
       }
      return tranReq.returnJson(jsonWr);
    }
   public ModelAndView downloadFileByFileId(SMTAIServerRequest tranReq, HttpServletResponse response) throws Exception {
      String fileId = tranReq.convParamToString("file_id", true);  // 获取请求中的file_id
      SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
      try {
         // 查询指定file_id的文件记录
         DBRecords dbRecords = db.querySQL("SELECT * FROM ai_times.chat_history_attach WHERE attach_id=?", new Object[]{fileId});
         if (dbRecords.getRecords().isEmpty()) {
            throw new Exception("文件不存在");
         }
         // 获取文件信息
         DBRecord fileRecord = dbRecords.getRecords().get(0);
         String attachTitle = fileRecord.getString("attach_title");  // 获取文件标题
         String extension = attachTitle.substring(attachTitle.lastIndexOf(".") + 1);
         // 扩展名和 MIME 类型映射
         Object fileTypeMapping = SMTAIServerApp.getApp().getGlobalConfig("file_type_mapping", false);
         Json json = Json.read(fileTypeMapping.toString());
         Map<String, Object> mimeTypes = json.asMap();
         String mimeType = (String) mimeTypes.getOrDefault(extension.toLowerCase(), "application/octet-stream");
         // 获取文件的字节数据,假设返回的是字节数组
         byte[] bytes = (byte[]) fileRecord.getValue("attach_bytes");  // 获取字节数据
         return tranReq.returnDownloadByteArray(bytes, attachTitle, mimeType);
//         // 设置响应头和文件名
//         String fileName = attachTitle != null ? attachTitle : "downloaded_file";
//         response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//         response.setContentType("application/octet-stream");
//         response.getOutputStream().write(bytes);  // 写入字节数据
//         response.getOutputStream().flush();
      } catch (Exception e) {
         throw new Exception("Error processing file download: " + e.getMessage());
      }
   }
   public ModelAndView chatCallAgent(SMTAIServerRequest tranReq) throws Exception
   {
      String agentId = tranReq.convParamToString("agent_id", true);
      Json jsonArgs = tranReq.convParamToJson("args", false);
      SMTQwenAgent agent = SMTAIServerApp.getApp().getQwenAgentManager().getAgentById(agentId);
      if(agent == null)
         throw new Exception("can't find agent : " + agentId);
      SMTLLMConnect llm = SMTAIServerApp.getApp().allocLLMConnect(null);
      if(jsonArgs == null)
         jsonArgs = Json.object("question", "");
      if(!jsonArgs.has("question"))
         jsonArgs.set("question", "");
      agent.callAgents("/", jsonArgs, llm, "", tranReq);
      List<SMTJsonWriter> listResult = tranReq.getResultJsonWrList();
      SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
      jsonWr.beginArray("results");
      if(listResult != null && listResult.size() > 0)
      {
         for(SMTJsonWriter jsonWrResult : listResult)
         {
            jsonWr.addKeyRaw(null, jsonWrResult.getRootJson());
         }
      }
      jsonWr.endArray();
      return tranReq.returnJson(jsonWr);
   }
   public ModelAndView callAgentArgStream(SMTAIServerRequest tranReq) throws Exception
   {
       return new ModelAndView(new SMTCallAgentArgStreamView(tranReq));
   }
}