目录

使用dify的api连接外部知识库,dify连接ragflow的知识库附java代码

使用dify的api连接外部知识库,dify连接ragflow的知识库(附java代码)

dify的知识库一般般,但是ragflow的知识库很强大,今天教大家如何使用dify连接ragflow的知识库

1.在ragflow建立一个知识库, 拿到知识库的id ,红框圈出来的地方就是这个知识库的id,后面要用到

https://i-blog.csdnimg.cn/direct/c8c2c3faa78f4254b3f3aedd540999c6.png

拿到ragflow的api的key

https://i-blog.csdnimg.cn/direct/024427429c6041729431c30893eaaa47.png

这里我使用的是Java代码,本地直接新建一个空的springboot项目,然后将以下代码复制粘贴,修改下参数即可

实体类(无需修改)

public class RetrievalSetting {
    @NotNull
    private int top_k;
    @NotNull
    private float score_threshold;

    // Getters and Setters
    public int getTop_k() {
        return top_k;
    }

    public void setTop_k(int top_k) {
        this.top_k = top_k;
    }

    public float getScore_threshold() {
        return score_threshold;
    }

    public void setScore_threshold(float score_threshold) {
        this.score_threshold = score_threshold;
    }
}
public class RetrievalRequest {
    @NotBlank
    private String knowledge_id;
    @NotBlank
    private String query;
    @NotNull
    private RetrievalSetting retrieval_setting;

    // Getters and Setters
    public String getKnowledge_id() {
        return knowledge_id;
    }

    public void setKnowledge_id(String knowledge_id) {
        this.knowledge_id = knowledge_id;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public RetrievalSetting getRetrieval_setting() {
        return retrieval_setting;
    }

    public void setRetrieval_setting(RetrievalSetting retrieval_setting) {
        this.retrieval_setting = retrieval_setting;
    }
}
@RestController
@RequestMapping("/")
public class RetrievalController {
    private static final String ORIGINAL_API_URL = "http://你的ragflowapi的主机和端口/api/v1/retrieval";

    @PostMapping("/retrieval")
    public ResponseEntity<Map<String, List<Map<String, Object>>>> retrieveChunks(
            @RequestBody RetrievalRequest requestData,
            @RequestHeader("Authorization") String authorization) {
        // 验证 Authorization 头
        if (!authorization.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
        String apiKey = authorization.split(" ")[1];

        // 构建请求体
        Map<String, Object> payload = new HashMap<>();
        payload.put("question", requestData.getQuery());
        payload.put("dataset_ids", Collections.singletonList(requestData.getKnowledge_id()));
        payload.put("top_k", requestData.getRetrieval_setting().getTop_k());
        payload.put("similarity_threshold", requestData.getRetrieval_setting().getScore_threshold());

        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<Map> response = restTemplate.exchange(
                    ORIGINAL_API_URL,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            if (response.getStatusCode() != HttpStatus.OK) {
                return ResponseEntity.status(response.getStatusCode()).body(null);
            }

            // 处理响应数据
            Map<String, Object> originalData = response.getBody();
            Map<String, Object> data = (Map<String, Object>) originalData.get("data");
            List<Map<String, Object>> chunks = (List<Map<String, Object>>) data.get("chunks");

            List<Map<String, Object>> records = new ArrayList<>();
            if (chunks != null) {
                for (Map<String, Object> chunk : chunks) {
                    Map<String, Object> record = new HashMap<>();
                    record.put("content", chunk.get("content"));
                    record.put("score", chunk.get("similarity"));
                    record.put("title", chunk.getOrDefault("document_keyword", "Unknown Document"));
                    Map<String, Object> metadata = new HashMap<>();
                    metadata.put("document_id", chunk.get("document_id"));
                    record.put("metadata", metadata);
                    records.add(record);
                }
            }

            Map<String, List<Map<String, Object>>> result = new HashMap<>();
            result.put("records", records);
            return ResponseEntity.ok(result);
        } catch (HttpClientErrorException e) {
            return ResponseEntity.status(e.getStatusCode()).body(null);
        }
    }
}

在controller中修改主机和端口,能在这里找到: https://i-blog.csdnimg.cn/direct/c2d2ec88e60746849e1a4cdd0ae24d8e.png

完事可以用api工具测试一下这个接口通不通

https://i-blog.csdnimg.cn/direct/9b621cf4e30043dfb0af416f0f92e8de.png

https://i-blog.csdnimg.cn/direct/151db5e918d44d35805bb7ce93c96297.png 注意这里请求头要加一个Bearer 然后接上apikey,中间有个空格

1.rag先连接

https://i-blog.csdnimg.cn/direct/b3accc7a77a543f0ac80cb1b2b5431f7.png

https://i-blog.csdnimg.cn/direct/2a4a96c15818435a8604b66ab80906ce.png

2.新建知识库

https://i-blog.csdnimg.cn/direct/c5128dc7aef54c159ee09c1b51eeaec3.png

https://i-blog.csdnimg.cn/direct/8866fc976eb2488a9249c84033ddc5f7.png 3.进行召回测试

https://i-blog.csdnimg.cn/direct/b7d29af71c4e47289d88fefe58252e02.png

这里是我运行的结果,完美

https://i-blog.csdnimg.cn/direct/5d7f8a6ff35c437d81a9306042e21ef6.png 至此结束,撒花