admin
2025-06-09 4eb46966002c6ca24cbb8cc8b519a05610e81649
0606
2个文件已修改
79 ■■■■■ 已修改文件
aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/config/DifyStreamClient.java 44 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/controller/AiBotController.java 35 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/config/DifyStreamClient.java
@@ -3,10 +3,12 @@
import com.agentsflex.core.message.AiMessage;
import com.agentsflex.core.prompt.HistoriesPrompt;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import com.mybatisflex.core.query.QueryWrapper;
import okhttp3.*;
import okio.BufferedSource;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import tech.aiflowy.ai.entity.AiBotMessage;
import tech.aiflowy.ai.service.AiBotMessageService;
@@ -131,6 +133,9 @@
                                    JsonElement dataElement = jsonObject.get("data");
                                    if (dataElement != null && !dataElement.isJsonNull()) {
                                        JsonObject dataObject = dataElement.getAsJsonObject();
                                        if (dataObject != null && dataObject.has("node_type")) {
                                            continue;
                                        }
                                        if (dataObject != null && dataObject.has("title")) {
                                            JsonElement titleElement = dataObject.get("title");
                                            if (titleElement != null && !titleElement.isJsonNull()) {
@@ -178,32 +183,37 @@
        return future;
    }
    public String fileUpload(String userId, String filePath){
        // 要上传的文件路径,替换为实际的文件路径
//        String filePath = "C:\\Users\\admin\\Desktop\\国务院政策文件库.xlsx";
        // 用户标识,替换为实际的用户标识,要和发送消息接口的 user 保持一致
    public String fileUpload(String userId, MultipartFile file) {
        // 用户标识,要和发送消息接口的 user 保持一致
        String user = userId;
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在:" + filePath);
            return user;
        // 判断文件是否为空
        if (file.isEmpty()) {
            System.out.println("上传文件为空");
            return "上传文件为空";
        }
        OkHttpClient client = new OkHttpClient();
        // 构建 multipart/form-data 请求体
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .addFormDataPart("user", user)
                .build();
        MultipartBody.Builder requestBodyBuilder = null;
        try {
            requestBodyBuilder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    // 添加上传文件,这里直接用 MultipartFile 的字节数组构建请求体
                    .addFormDataPart("file", file.getOriginalFilename(),
                            RequestBody.create(MediaType.parse("application/octet-stream"), file.getBytes()))
                    .addFormDataPart("user", user);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        RequestBody requestBody = requestBodyBuilder.build();
        Request request = new Request.Builder()
                .url(apiUrl)
                .url(apiUrl)  // 替换为实际的接口地址常量
                .post(requestBody)
                .header("Authorization", apiKey)
                .header("Authorization", apiKey)  // 替换为实际的授权密钥常量
                .build();
        try (Response response = client.newCall(request).execute()) {
@@ -216,7 +226,7 @@
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
            return "文件上传失败:" + e.getMessage();
        }
    }
aiflowy-modules/aiflowy-module-ai/src/main/java/tech/aiflowy/ai/controller/AiBotController.java
@@ -28,13 +28,11 @@
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import tech.aiflowy.ai.config.DifyStreamClient;
import tech.aiflowy.ai.config.FileReference;
@@ -55,6 +53,7 @@
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigInteger;
import java.util.*;
@@ -141,13 +140,22 @@
    @Autowired
    private ObjectMapper objectMapper;
//    @PostMapping("chat")
//    public SseEmitter chat2(@JsonBody(value = "prompt", required = true) String prompt,
//                           @JsonBody(value = "botId", required = true) BigInteger botId,
//                           @JsonBody(value = "sessionId", required = true) String sessionId,
//                           @JsonBody(value = "isExternalMsg") int isExternalMsg,
//                           @JsonBody("file") String file,//上传文件
//                           HttpServletResponse response){
//        File file =
//    }
    @PostMapping("chat")
    public SseEmitter chat(@JsonBody(value = "prompt", required = true) String prompt,
                           @JsonBody(value = "botId", required = true) BigInteger botId,
                           @JsonBody(value = "sessionId", required = true) String sessionId,
                           @JsonBody(value = "isExternalMsg") int isExternalMsg,
                           @JsonBody(value = "file") String file,
                           @JsonBody(value = "file") String file,//上传文件
                           HttpServletResponse response) {
        response.setContentType("text/event-stream");
        AiBot aiBot = service.getById(botId);
@@ -165,17 +173,12 @@
                DifyStreamClient client = new DifyStreamClient(apiUrl, apiKey, aiBotMessageService);
                DifyStreamClient uploadClient = new DifyStreamClient(aiBot.getModelAPI()+"/files/upload", apiKey, aiBotMessageService);
                String test = uploadClient.fileUpload(SaTokenUtil.getLoginAccount().getId() + "", file);
                System.out.println(test);
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                JsonObject fileJson = gson.fromJson(test, JsonObject.class);
                String fileId = fileJson.get("id").getAsString();
                String fileId = file;
                // 2. 构建文件参数对象
                Map<String, Object> fileParam = new HashMap<>();
                fileParam.put("transfer_method", "local_file");
                fileParam.put("upload_file_id", fileId);
                String[] split = file.split("\\.");
//                fileParam.put("type", fileJson.get("extension").getAsString()); // 例如 "excel"、"pdf" 等
                fileParam.put("type", "document"); // 例如 "excel"、"pdf" 等
@@ -363,8 +366,8 @@
    }
    @PostMapping("files/upload")
    public Result filesUpload(@JsonBody(value = "botId", required = true) BigInteger botId,
                           String file,
    public Result filesUpload(@RequestParam("botId") BigInteger botId,
                              @RequestParam("file") MultipartFile file,
                           HttpServletResponse response){
        try{
            String userId = SaTokenUtil.getLoginAccount().getId() + "";
@@ -374,10 +377,10 @@
            String apiUrl = aiBot.getModelAPI(); // 替换为实际API URL
            String apiKey = aiBot.getModelKEY(); // 替换为实际API Key
            DifyStreamClient client = new DifyStreamClient(apiUrl, apiKey, aiBotMessageService);
            client.fileUpload(userId,file);
            return Result.success("成功!");
            String s = client.fileUpload(userId, file);
            return Result.success(s);
        }catch (Exception e){
            return Result.fail(400, String.valueOf(e));
            return Result.fail(400,String.valueOf(e));
        }
    }