querySegmentChildChunks(String datasetId, String documentId, String segmentId, Integer page, Integer limit, String keyword) {
251 | return ofDocument(true, datasetId, documentId).querySegmentChildChunks(segmentId, page, limit, keyword);
252 | }
253 |
254 | @Override
255 | public Boolean deleteSegmentChildChunks(String datasetId, String documentId, String segmentId, String childChunkId) {
256 | return ofDocument(true, datasetId, documentId).deleteSegmentChildChunks(segmentId, childChunkId);
257 | }
258 |
259 | @Override
260 | public SegmentChildChunk updateSegmentChildChunks(String datasetId, String documentId, String segmentId, String childChunkId, String content) {
261 | return ofDocument(true, datasetId, documentId).updateSegmentChildChunks(segmentId, childChunkId, content);
262 | }
263 |
264 | }
265 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/params/ParamDataset.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.params;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import io.github.yuanbaobaoo.dify.dataset.types.DatasetConsts;
6 | import lombok.Builder;
7 | import lombok.Getter;
8 | import lombok.Setter;
9 |
10 | @Getter
11 | @Setter
12 | @Builder
13 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
14 | public class ParamDataset {
15 | private String name;
16 | private String description;
17 | private DatasetConsts.DocType indexingTechnique;
18 | private DatasetConsts.Permission permission;
19 | private DatasetConsts.Provider provider;
20 | private String externalKnowledgeApiId;
21 | private String externalKnowledgeId;
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/params/ParamDocument.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.params;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import io.github.yuanbaobaoo.dify.dataset.types.DatasetConsts;
6 | import io.github.yuanbaobaoo.dify.dataset.types.ProcessRule;
7 | import lombok.Builder;
8 | import lombok.Getter;
9 | import lombok.Setter;
10 |
11 | import java.util.HashMap;
12 |
13 | @Getter
14 | @Setter
15 | @Builder
16 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
17 | public class ParamDocument {
18 | /**
19 | * 文档名称
20 | */
21 | private String name;
22 |
23 | /**
24 | * 文档内容
25 | */
26 | private String text;
27 |
28 | /**
29 | * 文档类型(选填)
30 | */
31 | private DatasetConsts.DocType docType;
32 |
33 | /**
34 | * 文档元数据(如提供文档类型则必填)。字段因文档类型而异
35 | * 请查看 ...
36 | * 了解各文档类型所需字段的详细信息。
37 | *
38 | * 针对图书 For book:
39 | *
40 | * title 书名 Book title
41 | * language 图书语言 Book language
42 | * author 作者 Book author
43 | * publisher 出版社 Publisher name
44 | * publication_date 出版日期 Publication date
45 | * isbn ISBN号码 ISBN number
46 | * category 图书分类 Book category
47 | *
48 | * 针对网页 For web_page:
49 | *
50 | * title 页面标题 Page title
51 | * url 页面网址 Page URL
52 | * language 页面语言 Page language
53 | * publish_date 发布日期 Publish date
54 | * author/publisher 作者/发布者 Author or publisher
55 | * topic/keywords 主题/关键词 Topic or keywords
56 | * description 页面描述 Page description
57 | *
58 | * 针对"其他"类型文档,接受任何有效的JSON对象
59 | */
60 | private Object docMetadata;
61 |
62 | /**
63 | * 索引方式
64 | */
65 | private DatasetConsts.IndexingTechnique indexingTechnique;
66 |
67 | /**
68 | * 索引内容的形式
69 | */
70 | private DatasetConsts.DocForm docForm;
71 |
72 | /**
73 | * 在 Q&A 模式下,指定文档的语言,例如:English、Chinese
74 | */
75 | private String docLanguage;
76 |
77 | /**
78 | * 处理规则
79 | */
80 | private ProcessRule processRule;
81 |
82 | /**
83 | * To HashMap
84 | */
85 | public HashMap toMap() {
86 | return new HashMap<>() {{
87 | put("name", name);
88 | put("text", text);
89 | put("doc_type", docType);
90 | put("doc_metadata", docMetadata);
91 | put("indexing_technique", indexingTechnique);
92 | put("doc_form", docForm);
93 | put("doc_language", docLanguage);
94 | put("process_rule", processRule);
95 | }};
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/params/ParamUpdateDataset.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.params;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import io.github.yuanbaobaoo.dify.dataset.types.DatasetConsts;
6 | import lombok.Builder;
7 | import lombok.Getter;
8 | import lombok.Setter;
9 |
10 | @Getter
11 | @Setter
12 | @Builder
13 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
14 | public class ParamUpdateDataset {
15 | private String name;
16 | private DatasetConsts.DocType indexingTechnique;
17 | private DatasetConsts.Permission permission;
18 | private String embeddingModelProvider;
19 | private String embeddingModel;
20 | private String retrievalModel;
21 | private String partialMemberList;
22 | }
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/BatchStatus.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import lombok.Getter;
6 | import lombok.Setter;
7 |
8 | @Getter
9 | @Setter
10 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
11 | public class BatchStatus {
12 | private String id;
13 | private String indexingStatus;
14 | private Long processingStartedAt;
15 | private Long parsingCompletedAt;
16 | private Long cleaningCompletedAt;
17 | private Long splittingCompletedAt;
18 | private Long completedAt;
19 | private Long pausedAt;
20 | private String error;
21 | private Long stoppedAt;
22 | private Integer completedSegments;
23 | private Integer totalSegments;
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/DatasetConsts.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types;
2 |
3 | public class DatasetConsts {
4 | /**
5 | * 索引方式
6 | */
7 | public enum IndexingTechnique {
8 | /**
9 | * 高质量:使用 embedding 模型进行嵌入,构建为向量数据库索引
10 | */
11 | high_quality,
12 |
13 | /**
14 | * 经济:使用 keyword table index 的倒排索引进行构建
15 | */
16 | economy,
17 | }
18 |
19 | /**
20 | * 索引内容的形式
21 | */
22 | public enum DocForm {
23 | /**
24 | * text 文档直接 embedding,经济模式默认为该模式
25 | */
26 | text_model,
27 |
28 | /**
29 | * parent-child 模式
30 | */
31 | hierarchical_model,
32 |
33 | /**
34 | * Q&A 模式:为分片文档生成 Q&A 对,然后对问题进行 embedding
35 | */
36 | qa_model,
37 |
38 | }
39 |
40 | /**
41 | * 权限
42 | */
43 | public enum Permission {
44 | /**
45 | * 仅自己
46 | */
47 | only_me,
48 |
49 | /**
50 | * 所有团队成员
51 | */
52 | all_team_members,
53 |
54 | /**
55 | * 部分团队成员
56 | */
57 | partial_members,
58 | }
59 |
60 | /**
61 | * Provider
62 | */
63 | public enum Provider {
64 | /**
65 | * 上传文件
66 | */
67 | vendor ,
68 |
69 | /**
70 | * 外部知识库
71 | */
72 | external ,
73 | }
74 |
75 | /**
76 | * Document type
77 | * book 图书 Book
78 | * web_page 网页 Web page
79 | * paper 学术论文/文章 Academic paper/article
80 | * social_media_post 社交媒体帖子 Social media post
81 | * wikipedia_entry 维基百科条目 Wikipedia entry
82 | * personal_document 个人文档 Personal document
83 | * business_document 商业文档 Business document
84 | * im_chat_log 即时通讯记录 Chat log
85 | * synced_from_notion Notion同步文档 Notion document
86 | * synced_from_github GitHub同步文档 GitHub document
87 | * others 其他文档类型 Other document types
88 | */
89 | public enum DocType {
90 | book,
91 | web_page,
92 | paper,
93 | social_media_post,
94 | wikipedia_entry,
95 | personal_document,
96 | business_document,
97 | im_chat_log,
98 | synced_from_notion,
99 | synced_from_github,
100 | others,
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/DocumentResult.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types;
2 |
3 | import com.alibaba.fastjson2.JSON;
4 | import com.alibaba.fastjson2.JSONObject;
5 | import io.github.yuanbaobaoo.dify.types.ApiConfig;
6 | import io.github.yuanbaobaoo.dify.dataset.entity.Document;
7 | import io.github.yuanbaobaoo.dify.dataset.heros.DocumentHero;
8 | import lombok.Getter;
9 | import lombok.Setter;
10 |
11 | @Getter
12 | @Setter
13 | public class DocumentResult {
14 | private String batch;
15 | private DocumentHero document;
16 |
17 | /**
18 | * 使用JSON字符串创建一个 DocumentResult 对象
19 | * @param result String
20 | */
21 | public static DocumentResult parse(String datasetId, String result, ApiConfig config) {
22 | JSONObject jsonObject = JSON.parseObject(result);
23 |
24 | DocumentResult document = new DocumentResult();
25 | document.setBatch(jsonObject.getString("batch"));
26 | document.setDocument(DocumentHero.of(
27 | datasetId,
28 | JSON.parseObject(jsonObject.getString("document"), Document.class),
29 | config
30 | ));
31 |
32 | return document;
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/ProcessRule.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types;
2 |
3 | import lombok.Builder;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 |
7 | @Getter
8 | @Setter
9 | @Builder
10 | public class ProcessRule {
11 | /**
12 | * 清洗、分段模式
13 | */
14 | private Mode mode;
15 |
16 | /**
17 | * 自定义规则(自动模式下,该字段为空)
18 | * pre_processing_rules (array[object]) 预处理规则
19 | * id (string) 预处理规则的唯一标识符。枚举:
20 | * remove_extra_spaces 替换连续空格、换行符、制表符
21 | * remove_urls_emails 删除 URL、电子邮件地址
22 | * enabled (bool) 是否选中该规则,不传入文档 ID 时代表默认值
23 | * segmentation (object) 分段规则
24 | * separator 自定义分段标识符,目前仅允许设置一个分隔符。默认为 \n
25 | * max_tokens 最大长度(token)默认为 1000
26 | * parent_mode 父分段的召回模式 full-doc 全文召回 / paragraph 段落召回
27 | * subchunk_segmentation (object) 子分段规则
28 | * separator 分段标识符,目前仅允许设置一个分隔符。默认为 ***
29 | * max_tokens 最大长度 (token) 需要校验小于父级的长度
30 | * chunk_overlap 分段重叠指的是在对数据进行分段时,段与段之间存在一定的重叠部分(选填)
31 | */
32 | private Object rules;
33 |
34 | /**
35 | * 清洗、分段模式
36 | */
37 | public enum Mode {
38 | // 自动
39 | automatic ,
40 | // 自定义
41 | custom,
42 | // 层级分段
43 | hierarchical,
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/RetrievalModel.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import lombok.Builder;
6 | import lombok.Getter;
7 | import lombok.Setter;
8 |
9 | @Getter
10 | @Setter
11 | @Builder
12 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
13 | public class RetrievalModel {
14 | /**
15 | * 检索方法
16 | */
17 | private SearchMethod searchMethod;
18 |
19 | /**
20 | * 是否开启rerank
21 | */
22 | private Boolean rerankingEnable;
23 |
24 | /**
25 | * Rerank 模型配置
26 | */
27 | private RerankingModel rerankingModel;
28 |
29 | /**
30 | * 混合检索模式下语意检索的权重设置
31 | */
32 | private Double weights;
33 |
34 | /**
35 | * 召回条数
36 | */
37 | private Integer topK;
38 |
39 | /**
40 | * 是否开启召回分数限制
41 | */
42 | private Boolean scoreThresholdEnabled;
43 |
44 | /**
45 | * 召回分数限制
46 | */
47 | private Double scoreThreshold;
48 |
49 | /**
50 | * 检索方法
51 | */
52 | public enum SearchMethod {
53 | /**
54 | * 混合检索
55 | */
56 | hybrid_search,
57 |
58 | /**
59 | * 语义检索
60 | */
61 | semantic_search,
62 |
63 | /**
64 | * 全文检索
65 | */
66 | full_text_search,
67 |
68 | /**
69 | * 关键字检索
70 | */
71 | keyword_search,
72 | }
73 |
74 | /**
75 | * Rerank 模型配置
76 | */
77 | @Getter
78 | @Setter
79 | @Builder
80 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
81 | public static class RerankingModel {
82 | /**
83 | * Rerank 模型的提供商
84 | */
85 | private String rerankingProviderName;
86 |
87 | /**
88 | * Rerank 模型的名称
89 | */
90 | private String rerankingModelName;
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/RetrieveResult.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types;
2 |
3 | import com.alibaba.fastjson2.JSONObject;
4 | import com.alibaba.fastjson2.PropertyNamingStrategy;
5 | import com.alibaba.fastjson2.annotation.JSONType;
6 | import io.github.yuanbaobaoo.dify.dataset.entity.Segment;
7 | import lombok.Getter;
8 | import lombok.Setter;
9 |
10 | import java.util.List;
11 |
12 | @Getter
13 | @Setter
14 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
15 | public class RetrieveResult {
16 | private JSONObject query;
17 | private List records;
18 |
19 | @Getter
20 | @Setter
21 | public static class Record {
22 | private Double score;
23 | private String tsnePosition;
24 | private Segment segment;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/SegmentResult.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import io.github.yuanbaobaoo.dify.dataset.entity.Segment;
6 | import lombok.Getter;
7 | import lombok.Setter;
8 |
9 | import java.util.List;
10 |
11 | @Getter
12 | @Setter
13 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
14 | public class SegmentResult {
15 | private DatasetConsts.DocForm docForm;
16 | private List data;
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/external/KnowledgeArgs.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types.external;
2 |
3 | import lombok.Getter;
4 | import lombok.Setter;
5 |
6 | @Getter
7 | @Setter
8 | public class KnowledgeArgs {
9 | /**
10 | * 知识库唯一 ID
11 | */
12 | private String knowledge_id;
13 |
14 | /**
15 | * 用户的查询
16 | */
17 | private String query;
18 |
19 | /**
20 | * 知识检索参数
21 | */
22 | private Setting retrieval_setting;
23 |
24 | @Setter
25 | @Getter
26 | public static class Setting {
27 | /**
28 | * 检索结果的最大数量
29 | */
30 | private String top_k;
31 |
32 | /**
33 | * 结果与查询相关性的分数限制,范围:0~1
34 | */
35 | private Double score_threshold;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/external/KnowledgeException.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types.external;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Getter;
5 | import lombok.NoArgsConstructor;
6 | import lombok.Setter;
7 |
8 | import java.util.HashMap;
9 | import java.util.Map;
10 |
11 | @Getter
12 | @Setter
13 | @NoArgsConstructor
14 | @AllArgsConstructor
15 | public class KnowledgeException extends RuntimeException {
16 | /**
17 | * 错误代码
18 | */
19 | private Integer error_code;
20 |
21 | /**
22 | * 错误信息
23 | */
24 | private String error_message;
25 |
26 | /**
27 | * toObject
28 | */
29 | public Object toObject() {
30 | Map obj = new HashMap<>();
31 | obj.put("error_code", error_code);
32 | obj.put("error_message", error_message);
33 |
34 | return obj;
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return "{" +
40 | "error_code: " + error_code +
41 | ", error_message: '" + error_message + '\'' +
42 | '}';
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/dataset/types/external/KnowledgeResult.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.dataset.types.external;
2 |
3 | import lombok.Builder;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 |
7 | import java.util.List;
8 |
9 | @Getter
10 | @Setter
11 | public class KnowledgeResult {
12 | /**
13 | * 从知识库查询的记录列表
14 | */
15 | private List records;
16 |
17 | /**
18 | * constructor
19 | */
20 | public KnowledgeResult() {
21 |
22 | }
23 |
24 | /**
25 | * constructor
26 | * @param data Record
27 | */
28 | public KnowledgeResult(Record data) {
29 | this.records = List.of(data);
30 | }
31 |
32 | /**
33 | * constructor
34 | * @param data List
35 | */
36 | public KnowledgeResult(List data) {
37 | this.records = data;
38 | }
39 |
40 | @Getter
41 | @Setter
42 | @Builder
43 | public static class Record {
44 | /**
45 | * 包含知识库中数据源的文本块
46 | */
47 | private String content;
48 |
49 | /**
50 | * 结果与查询的相关性分数,范围:0~1
51 | */
52 | private Double score;
53 |
54 | /**
55 | * 文档标题
56 | */
57 | private String title;
58 |
59 | /**
60 | * 包含数据源中文档的元数据属性及其值
61 | */
62 | private Object metadata;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/routes/AppRoutes.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.routes;
2 |
3 | import io.github.yuanbaobaoo.dify.types.DifyRoute;
4 | import io.github.yuanbaobaoo.dify.types.HttpMethod;
5 |
6 | public class AppRoutes {
7 | public static final DifyRoute INFO = new DifyRoute(
8 | "/info",
9 | HttpMethod.GET
10 | );
11 |
12 | public static final DifyRoute PARAMETERS = new DifyRoute(
13 | "/parameters",
14 | HttpMethod.GET
15 | );
16 |
17 | public static final DifyRoute META_INFO = new DifyRoute(
18 | "/meta",
19 | HttpMethod.GET
20 | );
21 |
22 | public static final DifyRoute FILE_UPLOAD = new DifyRoute(
23 | "/files/upload",
24 | HttpMethod.POST
25 | );
26 |
27 | public static final DifyRoute MESSAGES = new DifyRoute(
28 | "/messages",
29 | HttpMethod.GET
30 | );
31 |
32 | public static final DifyRoute CHAT_CONVERSATIONS = new DifyRoute(
33 | "/conversations",
34 | HttpMethod.GET
35 | );
36 |
37 | public static final DifyRoute CHAT_MESSAGES = new DifyRoute(
38 | "/chat-messages",
39 | HttpMethod.POST
40 | );
41 |
42 | public static final DifyRoute AUDIO_TO_TEXT = new DifyRoute(
43 | "/audio-to-text",
44 | HttpMethod.POST
45 | );
46 |
47 | public static final DifyRoute TEXT_TO_AUDIO = new DifyRoute(
48 | "/text-to-audio",
49 | HttpMethod.POST
50 | );
51 |
52 | public static final DifyRoute WORKFLOW_RUN = new DifyRoute(
53 | "/workflows/run",
54 | HttpMethod.POST
55 | );
56 |
57 | public static final DifyRoute WORKFLOW_TASK = new DifyRoute(
58 | "/workflows/task",
59 | HttpMethod.POST
60 | );
61 |
62 | public static final DifyRoute WORKFLOW_LOGS = new DifyRoute(
63 | "/workflows/logs",
64 | HttpMethod.GET
65 | );
66 |
67 | public static final DifyRoute COMPLETION_MESSAGES = new DifyRoute(
68 | "/completion-messages",
69 | HttpMethod.POST
70 | );
71 |
72 | public static final DifyRoute ANNOTATION_GET = new DifyRoute(
73 | "/apps/annotations",
74 | HttpMethod.GET
75 | );
76 |
77 | public static final DifyRoute ANNOTATION_ADD = new DifyRoute(
78 | "/apps/annotations",
79 | HttpMethod.POST
80 | );
81 |
82 | public static final DifyRoute ANNOTATION_SET = new DifyRoute(
83 | "/apps/annotations/${annotationId}",
84 | HttpMethod.PUT
85 | );
86 |
87 | public static final DifyRoute ANNOTATION_DEL = new DifyRoute(
88 | "/apps/annotations/${annotationId}",
89 | HttpMethod.DELETE
90 | );
91 |
92 | public static final DifyRoute ANNOTATION_REPLY_SET = new DifyRoute(
93 | "/apps/annotation-reply/${action}",
94 | HttpMethod.POST
95 | );
96 |
97 | public static final DifyRoute ANNOTATION_REPLY_GET = new DifyRoute(
98 | "/apps/annotation-reply/${action}/status/${jobId}",
99 | HttpMethod.GET
100 | );
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/routes/ConsoleRoutes.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.routes;
2 |
3 | import io.github.yuanbaobaoo.dify.types.DifyRoute;
4 | import io.github.yuanbaobaoo.dify.types.HttpMethod;
5 |
6 | public class ConsoleRoutes {
7 | // 登录
8 | public static final DifyRoute LOGIN = new DifyRoute(
9 | "/console/api/login",
10 | HttpMethod.POST
11 | );
12 |
13 | // 应用列表
14 | public static final DifyRoute APPS = new DifyRoute(
15 | "/console/api/apps",
16 | HttpMethod.GET
17 | );
18 |
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/routes/DatasetRoutes.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.routes;
2 |
3 | import io.github.yuanbaobaoo.dify.types.DifyRoute;
4 | import io.github.yuanbaobaoo.dify.types.HttpMethod;
5 |
6 | public class DatasetRoutes {
7 | public static final DifyRoute MODELS_TEXT_EMBEDDING = new DifyRoute(
8 | "/workspaces/current/models/model-types/text-embedding",
9 | HttpMethod.GET
10 | );
11 |
12 | public static final DifyRoute DATASETS = new DifyRoute(
13 | "/datasets",
14 | HttpMethod.POST
15 | );
16 |
17 | public static final DifyRoute DATASETS_INFO = new DifyRoute(
18 | "/datasets/${datasetId}",
19 | HttpMethod.GET
20 | );
21 |
22 | public static final DifyRoute DATASETS_UPDATE = new DifyRoute(
23 | "/datasets/${datasetId}",
24 | HttpMethod.PATCH
25 | );
26 |
27 | public static final DifyRoute DATASETS_DELETE = new DifyRoute(
28 | "/datasets/${datasetId}",
29 | HttpMethod.DELETE
30 | );
31 |
32 | public static final DifyRoute DATASETS_RETRIEVE = new DifyRoute(
33 | "/datasets/${datasetId}/retrieve",
34 | HttpMethod.POST
35 | );
36 |
37 | public static final DifyRoute DATASETS_CREATE_DOC_TEXT = new DifyRoute(
38 | "/datasets/${datasetId}/document/create-by-text",
39 | HttpMethod.POST
40 | );
41 |
42 | public static final DifyRoute DATASETS_CREATE_DOC_FILE = new DifyRoute(
43 | "/datasets/${datasetId}/document/create-by-file",
44 | HttpMethod.POST
45 | );
46 |
47 | public static final DifyRoute DATASETS_DOCS = new DifyRoute(
48 | "/datasets/${datasetId}/documents",
49 | HttpMethod.GET
50 | );
51 |
52 | public static final DifyRoute DATASETS_INDEXING_STATUS = new DifyRoute(
53 | "/datasets/${datasetId}/documents/${batch}/indexing-status",
54 | HttpMethod.GET
55 | );
56 |
57 | public static final DifyRoute DATASETS_DOCS_UPDATE_TEXT = new DifyRoute(
58 | "/datasets/${datasetId}/documents/${documentId}/update-by-text",
59 | HttpMethod.POST
60 | );
61 |
62 | public static final DifyRoute DATASETS_DOCS_UPDATE_FILE = new DifyRoute(
63 | "/datasets/${datasetId}/documents/${documentId}/update-by-file",
64 | HttpMethod.POST
65 | );
66 |
67 | public static final DifyRoute DATASETS_DOCS_DELETE = new DifyRoute(
68 | "/datasets/${datasetId}/documents/${documentId}",
69 | HttpMethod.DELETE
70 | );
71 |
72 | public static final DifyRoute DATASETS_DOCS_FILE_INFO = new DifyRoute(
73 | "/datasets/${datasetId}/documents/${documentId}/upload-file",
74 | HttpMethod.GET
75 | );
76 |
77 |
78 | public static final DifyRoute DATASETS_DOCS_SEGMENTS = new DifyRoute(
79 | "/datasets/${datasetId}/documents/${documentId}/segments",
80 | HttpMethod.GET
81 | );
82 |
83 | public static final DifyRoute DATASETS_DOCS_SEGMENTS_ADD = new DifyRoute(
84 | DATASETS_DOCS_SEGMENTS.getUrl(),
85 | HttpMethod.POST
86 | );
87 |
88 | public static final DifyRoute DATASETS_DOCS_SEGMENTS_DEL = new DifyRoute(
89 | "/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}",
90 | HttpMethod.DELETE
91 | );
92 |
93 | public static final DifyRoute DATASETS_DOCS_SEGMENTS_UPDATE = new DifyRoute(
94 | "/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}",
95 | HttpMethod.POST
96 | );
97 |
98 | public static final DifyRoute DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_GET = new DifyRoute(
99 | "/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}/child_chunks",
100 | HttpMethod.GET
101 | );
102 |
103 | public static final DifyRoute DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_ADD = new DifyRoute(
104 | "/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}/child_chunks",
105 | HttpMethod.POST
106 | );
107 |
108 | public static final DifyRoute DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_DEL = new DifyRoute(
109 | "/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}/child_chunks/${childChunkId}",
110 | HttpMethod.POST
111 | );
112 |
113 | public static final DifyRoute DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_SET = new DifyRoute(
114 | "/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}/child_chunks/${childChunkId}",
115 | HttpMethod.PATCH
116 | );
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/ApiConfig.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | import lombok.Builder;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 |
7 | @Getter
8 | @Setter
9 | @Builder
10 | public class ApiConfig {
11 | /**
12 | * Dify Server Address
13 | */
14 | private String server;
15 |
16 | /**
17 | * Api Key
18 | */
19 | private String apiKey;
20 |
21 | /**
22 | * refreshToken
23 | */
24 | private String refreshToken;
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/AudioFile.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | import lombok.Builder;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 |
7 | @Getter
8 | @Setter
9 | @Builder
10 | public class AudioFile {
11 | /**
12 | * 返回的文件Content-Type
13 | */
14 | private String type;
15 |
16 | /**
17 | * 文件默认后缀
18 | */
19 | private String suffix;
20 |
21 | /**
22 | * 文件内容
23 | */
24 | private byte[] data;
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/DifyClientException.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | public class DifyClientException extends RuntimeException {
4 | /**
5 | * Constructs a new runtime exception with {@code null} as its
6 | */
7 | public DifyClientException() {
8 | super();
9 | }
10 |
11 | /**
12 | * Constructs a new runtime exception with the specified detail message.
13 | * @param message String
14 | */
15 | public DifyClientException(String message) {
16 | super(message);
17 | }
18 |
19 | /**
20 | * Constructs a new runtime exception with the specified detail message and Throwable
21 | * @param message String
22 | * @param cause Throwable
23 | */
24 | public DifyClientException(String message, Throwable cause) {
25 | super(message, cause);
26 | }
27 |
28 | /**
29 | * Constructs a new runtime exception with the Throwable
30 | * @param cause Throwable
31 | */
32 | public DifyClientException(Throwable cause) {
33 | super(cause);
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/DifyException.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | import com.alibaba.fastjson2.JSON;
4 | import com.alibaba.fastjson2.JSONObject;
5 | import lombok.Getter;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * Dify exception type
12 | */
13 | public class DifyException extends RuntimeException {
14 | /**
15 | * original dify response
16 | */
17 | @Getter
18 | private String original;
19 |
20 | /**
21 | * response status | http status
22 | */
23 | private Integer status;
24 |
25 | /**
26 | * dify response -> code
27 | */
28 | @Getter
29 | private String code;
30 |
31 | /**
32 | * dify response -> message
33 | */
34 | private String message;
35 |
36 | /**
37 | * dify response -> params
38 | */
39 | @Getter
40 | private String params;
41 |
42 | /**
43 | * constructor
44 | */
45 | public DifyException() {
46 | super();
47 | }
48 |
49 | /**
50 | * constructor
51 | * @param response String
52 | * @param status http status
53 | */
54 | public DifyException(String response, Integer status) {
55 | try {
56 | JSONObject object = JSON.parseObject(response);
57 |
58 | this.status = object.getInteger("status");
59 | this.code = object.getString("code");
60 | this.message = object.getString("message");
61 | this.params = object.getString("params");
62 | } catch (Exception e) {
63 | this.status = status;
64 | this.message = response;
65 | }
66 |
67 | this.original = response;
68 | }
69 |
70 | @Override
71 | public String getMessage() {
72 | return message;
73 | }
74 |
75 | @Override
76 | public String toString() {
77 | Map map = new HashMap<>();
78 | map.put("status", status);
79 | map.put("code", code);
80 | map.put("message", message);
81 | map.put("params", params);
82 | return JSON.toJSONString(map);
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/DifyPage.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import lombok.Getter;
6 | import lombok.Setter;
7 |
8 | import java.io.Serial;
9 | import java.io.Serializable;
10 | import java.util.List;
11 |
12 | @Getter
13 | @Setter
14 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
15 | public class DifyPage implements Serializable {
16 | @Serial
17 | private static final long serialVersionUID = 1L;
18 |
19 | private int page;
20 | private int limit;
21 | private long total;
22 | private long totalPages;
23 | private List data;
24 | private Boolean hasMore;
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/DifyRoute.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Builder;
5 | import lombok.Getter;
6 | import lombok.NoArgsConstructor;
7 | import org.apache.commons.text.StringSubstitutor;
8 |
9 | import java.util.Map;
10 |
11 | @Getter
12 | @Builder
13 | @NoArgsConstructor
14 | @AllArgsConstructor
15 | public class DifyRoute {
16 | /**
17 | * API URL
18 | */
19 | private String url;
20 |
21 | /**
22 | * HTTP METHOD
23 | */
24 | private HttpMethod method;
25 |
26 | /**
27 | * Replace url placeholder. 替换URL模板参数
28 | *
29 | * @param params Map
30 | */
31 | public DifyRoute format(Map params) {
32 | String u = StringSubstitutor.replace(url, params);
33 | return DifyRoute.builder().url(u).method(method).build();
34 | }
35 |
36 | /**
37 | * build get route info
38 | *
39 | * @param url API URL
40 | */
41 | public static DifyRoute buildGet(String url) {
42 | return DifyRoute.builder().url(url).method(HttpMethod.GET).build();
43 | }
44 |
45 | /**
46 | * build post route info
47 | *
48 | * @param url API URL
49 | */
50 | public static DifyRoute buildPost(String url) {
51 | return DifyRoute.builder().url(url).method(HttpMethod.POST).build();
52 | }
53 |
54 | /**
55 | * build delete route info
56 | *
57 | * @param url API URL
58 | */
59 | public static DifyRoute buildDelete(String url) {
60 | return DifyRoute.builder().url(url).method(HttpMethod.DELETE).build();
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/HttpMethod.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | public enum HttpMethod {
4 | POST,
5 | GET,
6 | PUT,
7 | DELETE,
8 | PATCH,
9 | HEAD,
10 | OPTIONS,
11 | TRACE,
12 | CONNECT
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/types/WebConfig.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.types;
2 |
3 | import lombok.Builder;
4 | import lombok.Getter;
5 | import lombok.Setter;
6 |
7 | @Getter
8 | @Setter
9 | @Builder
10 | public class WebConfig {
11 | /**
12 | * Dify Server Address
13 | */
14 | private String server;
15 |
16 | /**
17 | * 用户名
18 | */
19 | private String userName;
20 |
21 | /**
22 | * 密码
23 | */
24 | private String password;
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/utils/AppClientBuilder.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.utils;
2 |
3 | import io.github.yuanbaobaoo.dify.app.IAppBaseClient;
4 | import io.github.yuanbaobaoo.dify.app.IAppChatClient;
5 | import io.github.yuanbaobaoo.dify.app.IAppCompletion;
6 | import io.github.yuanbaobaoo.dify.app.IAppFlowClient;
7 | import io.github.yuanbaobaoo.dify.app.impl.AppBaseClientImpl;
8 | import io.github.yuanbaobaoo.dify.app.impl.AppChatClientImpl;
9 | import io.github.yuanbaobaoo.dify.app.impl.AppCompletionImpl;
10 | import io.github.yuanbaobaoo.dify.app.impl.AppFlowClientImpl;
11 | import io.github.yuanbaobaoo.dify.types.ApiConfig;
12 |
13 | /**
14 | * Dify Client builder
15 | */
16 | public class AppClientBuilder {
17 | private String apiKey;
18 | private String baseUrl;
19 |
20 | /**
21 | * builder
22 | * @return DifyAppClientBuilder
23 | */
24 | public static AppClientBuilder builder() {
25 | return new AppClientBuilder();
26 | }
27 |
28 | /**
29 | * builder
30 | * @return DifyAppClientBuilder
31 | */
32 | public static AppClientBuilder builder(String server, String apiKey) {
33 | return new AppClientBuilder(server, apiKey);
34 | }
35 |
36 | /**
37 | * constructor
38 | */
39 | private AppClientBuilder() {
40 |
41 | }
42 |
43 | /**
44 | * constructor
45 | */
46 | private AppClientBuilder(String server, String apiKey) {
47 | this.baseUrl = server;
48 | this.apiKey = apiKey;
49 | }
50 |
51 | /**
52 | * create dify base client
53 | */
54 | public Builder base() {
55 | return new Builder<>(AppBaseClientImpl.class);
56 | }
57 |
58 | /**
59 | * create dify chat client
60 | */
61 | public Builder chat() {
62 | return new Builder<>(AppChatClientImpl.class);
63 | }
64 |
65 | /**
66 | * create dify flow client
67 | */
68 | public Builder flow() {
69 | return new Builder<>(AppFlowClientImpl.class);
70 | }
71 |
72 | /**
73 | * create dify completion client
74 | */
75 | public Builder completion() {
76 | return new Builder<>(AppCompletionImpl.class);
77 | }
78 |
79 | /**
80 | * Builder
81 | * @param
82 | * @param
83 | */
84 | public class Builder {
85 | private final Class type;
86 |
87 | /**
88 | * constructor
89 | * @param type Class
90 | */
91 | public Builder(Class type) {
92 | this.type = type;
93 | }
94 |
95 | /**
96 | * config
97 | * @param config DifyConfig
98 | */
99 | public Builder config(ApiConfig config) {
100 | baseUrl = config.getServer();
101 | apiKey = config.getApiKey();
102 | return this;
103 | }
104 |
105 | /**
106 | * dify server base url
107 | * @param baseUrl String
108 | */
109 | public Builder baseUrl(String baseUrl) {
110 | AppClientBuilder.this.baseUrl = baseUrl;
111 | return this;
112 | }
113 |
114 | /**
115 | * dify app api key
116 | * @param key String
117 | */
118 | public Builder apiKey(String apiKey) {
119 | AppClientBuilder.this.apiKey = apiKey;
120 | return this;
121 | }
122 |
123 | /**
124 | * build
125 | */
126 | public R build() {
127 | if (baseUrl == null || apiKey == null) {
128 | throw new RuntimeException("Dify App Client Build Error: params is not defined");
129 | }
130 |
131 | try {
132 | return type.getConstructor(String.class, String.class).newInstance(baseUrl, apiKey);
133 | } catch (Exception e) {
134 | throw new RuntimeException("Dify App Client Build Error: class is not defined", e);
135 | }
136 | }
137 | }
138 |
139 | }
140 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/utils/DatasetBuilder.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.utils;
2 |
3 | import io.github.yuanbaobaoo.dify.dataset.IDatasetClient;
4 | import io.github.yuanbaobaoo.dify.dataset.heros.DatasetHero;
5 | import io.github.yuanbaobaoo.dify.dataset.heros.DocumentHero;
6 | import io.github.yuanbaobaoo.dify.dataset.impl.DatasetClientImpl;
7 | import io.github.yuanbaobaoo.dify.types.ApiConfig;
8 |
9 | /**
10 | * Dify 知识库 builder
11 | */
12 | public class DatasetBuilder {
13 | private String apiKey;
14 | private String baseUrl;
15 |
16 | /**
17 | * builder
18 | */
19 | public static DatasetBuilder builder() {
20 | return new DatasetBuilder();
21 | }
22 |
23 | /**
24 | * builder
25 | * @param server Dify 服务地址
26 | * @param apiKey 知识库 Api Key
27 | */
28 | public static DatasetBuilder builder(String server, String apiKey) {
29 | return new DatasetBuilder(server, apiKey);
30 | }
31 |
32 | /**
33 | * constructor
34 | */
35 | private DatasetBuilder() {
36 |
37 | }
38 |
39 | /**
40 | * constructor
41 | * @param server Dify 服务地址
42 | * @param apiKey 知识库 Api Key
43 | */
44 | private DatasetBuilder(String server, String apiKey) {
45 | this.apiKey = apiKey;
46 | this.baseUrl = server;
47 | }
48 |
49 | /**
50 | * config
51 | * @param config DifyConfig
52 | */
53 | public DatasetBuilder config(ApiConfig config) {
54 | this.baseUrl = config.getServer();
55 | this.apiKey = config.getApiKey();
56 | return this;
57 | }
58 |
59 | /**
60 | * dify server base url
61 | * @param baseUrl String
62 | */
63 | public DatasetBuilder baseUrl(String baseUrl) {
64 | this.baseUrl = baseUrl;
65 | return this;
66 | }
67 |
68 | /**
69 | * dify app api key
70 | * @param apiKey String
71 | */
72 | public DatasetBuilder apiKey(String apiKey) {
73 | this.apiKey = apiKey;
74 | return this;
75 | }
76 |
77 | /**
78 | * build
79 | */
80 | public IDatasetClient build() {
81 | if (baseUrl == null || apiKey == null) {
82 | throw new RuntimeException("Dify Dataset Client Build Error: params is not defined");
83 | }
84 |
85 | try {
86 | return DatasetClientImpl.build(baseUrl, apiKey);
87 | } catch (Exception e) {
88 | throw new RuntimeException("Dify Dataset Client Build Error: class is not defined", e);
89 | }
90 | }
91 |
92 | /**
93 | * 快捷构建一个Dataset对象
94 | * @param datasetId 知识库ID
95 | */
96 | public DatasetHero of(String datasetId) {
97 | return DatasetHero.of(datasetId, ApiConfig.builder().server(baseUrl).apiKey(apiKey).build());
98 | }
99 |
100 | /**
101 | * 快捷创建一个Document对象
102 | * @param datasetId 知识库ID
103 | * @param documentId 文档ID
104 | */
105 | public DocumentHero ofDocument(String datasetId, String documentId) {
106 | return DocumentHero.of(datasetId, documentId, ApiConfig.builder().server(baseUrl).apiKey(apiKey).build());
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/utils/WebClientBuilder.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.utils;
2 |
3 | import io.github.yuanbaobaoo.dify.types.DifyClientException;
4 | import io.github.yuanbaobaoo.dify.types.DifyException;
5 | import io.github.yuanbaobaoo.dify.types.WebConfig;
6 | import io.github.yuanbaobaoo.dify.web.WebAuthService;
7 | import io.github.yuanbaobaoo.dify.web.IWebConsoleClient;
8 | import io.github.yuanbaobaoo.dify.web.entity.TokenList;
9 | import io.github.yuanbaobaoo.dify.web.impl.WebClientImpl;
10 |
11 | /**
12 | * Dify Web Client Builder
13 | */
14 | public class WebClientBuilder {
15 | private String server;
16 | private String userName;
17 | private String password;
18 |
19 | /**
20 | * builder
21 | */
22 | public static WebClientBuilder builder() {
23 | return new WebClientBuilder();
24 | }
25 |
26 | /**
27 | * builder
28 | * @param server Dify 服务地址
29 | * @param userName 用户名
30 | * @param password 账号密码
31 | */
32 | public static WebClientBuilder builder(String server, String userName, String password) {
33 | return new WebClientBuilder(server, userName, password);
34 | }
35 |
36 | /**
37 | * constructor
38 | */
39 | private WebClientBuilder() {
40 |
41 | }
42 |
43 | /**
44 | * constructor
45 | * @param server Dify 服务地址
46 | * @param userName 用户名
47 | * @param password 账号密码
48 | */
49 | private WebClientBuilder(String server, String userName, String password) {
50 | this.server = server;
51 | this.userName = userName;
52 | this.password = password;
53 | }
54 |
55 | /**
56 | * dify server base url
57 | * @param baseUrl String
58 | */
59 | public WebClientBuilder baseUrl(String baseUrl) {
60 | this.server = baseUrl;
61 | return this;
62 | }
63 |
64 | /**
65 | * dify login user name
66 | * @param userName String
67 | */
68 | public WebClientBuilder user(String userName) {
69 | this.userName = userName;
70 | return this;
71 | }
72 |
73 | /**
74 | * dify login password
75 | * @param password String
76 | */
77 | public WebClientBuilder password(String password) {
78 | this.password = password;
79 | return this;
80 | }
81 |
82 | /**
83 | * build.
84 | * 创建IWebClient对象时,会默认执行登录
85 | */
86 | public IWebConsoleClient connect() {
87 | if (server == null || userName == null || password == null) {
88 | throw new RuntimeException("Dify Web Client Connect Error: params is not defined");
89 | }
90 |
91 | try {
92 | WebConfig config = WebConfig.builder().server(server).userName(userName).password(password).build();
93 | TokenList tokenList = WebAuthService.login(config);
94 | return new WebClientImpl(server, tokenList);
95 | } catch (DifyClientException | DifyException e) {
96 | throw e;
97 | } catch (Exception e) {
98 | throw new RuntimeException("Dify Web Client Connect Error: ", e);
99 | }
100 | }
101 |
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/web/IWebConsoleClient.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.web;
2 |
3 | import com.alibaba.fastjson2.JSONObject;
4 | import io.github.yuanbaobaoo.dify.SimpleHttpClient;
5 | import io.github.yuanbaobaoo.dify.types.DifyPage;
6 | import io.github.yuanbaobaoo.dify.web.entity.TokenList;
7 |
8 | public interface IWebConsoleClient {
9 | /**
10 | * 获取一个Simple http client对象
11 | */
12 | SimpleHttpClient httpClient();
13 |
14 | /**
15 | * 获取登录的Access token
16 | */
17 | String token();
18 | /**
19 | * 获取登录的Refresh token
20 | */
21 | String refreshToken();
22 | /**
23 | * 查询应用列表
24 | * @param page int
25 | * @param limit int
26 | * @param name 名称 (可选)
27 | */
28 | DifyPage queryApps(int page, int limit, String name);
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/web/WebAuthService.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.web;
2 |
3 | import com.alibaba.fastjson2.JSON;
4 | import com.alibaba.fastjson2.PropertyNamingStrategy;
5 | import com.alibaba.fastjson2.annotation.JSONType;
6 | import io.github.yuanbaobaoo.dify.routes.ConsoleRoutes;
7 | import io.github.yuanbaobaoo.dify.types.DifyClientException;
8 | import io.github.yuanbaobaoo.dify.SimpleHttpClient;
9 | import io.github.yuanbaobaoo.dify.types.WebConfig;
10 | import io.github.yuanbaobaoo.dify.web.entity.TokenList;
11 | import lombok.Getter;
12 | import lombok.Setter;
13 | import lombok.extern.slf4j.Slf4j;
14 |
15 | import java.util.HashMap;
16 |
17 | @Slf4j
18 | public class WebAuthService {
19 | @Getter
20 | @Setter
21 | private static class LoginResult {
22 | private TokenList data;
23 | private String result;
24 | }
25 |
26 | /**
27 | * 登录
28 | * @param config DifyWebConfig
29 | */
30 | public static TokenList login(WebConfig config) {
31 | SimpleHttpClient client = SimpleHttpClient.newHttpClient(config.getServer());
32 |
33 | String result = client.requestJson(ConsoleRoutes.LOGIN, null, new HashMap<>() {{
34 | put("email", config.getUserName());
35 | put("password", config.getPassword());
36 | put("language", "zh-Hans");
37 | put("remember_me", "zh-true");
38 | }});
39 |
40 | LoginResult loginResult = JSON.parseObject(result, LoginResult.class);
41 |
42 | if ("success".equals(loginResult.getResult())) {
43 | return loginResult.getData();
44 | }
45 |
46 | throw new DifyClientException("登录失败: " + result);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/web/entity/TokenList.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.web.entity;
2 |
3 | import com.alibaba.fastjson2.PropertyNamingStrategy;
4 | import com.alibaba.fastjson2.annotation.JSONType;
5 | import lombok.Getter;
6 | import lombok.Setter;
7 |
8 | @Getter
9 | @Setter
10 | @JSONType(naming = PropertyNamingStrategy.SnakeCase)
11 | public class TokenList {
12 | private String accessToken;
13 | private String refreshToken;
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/io/github/yuanbaobaoo/dify/web/impl/WebClientImpl.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify.web.impl;
2 |
3 | import com.alibaba.fastjson2.JSON;
4 | import com.alibaba.fastjson2.JSONObject;
5 | import com.alibaba.fastjson2.TypeReference;
6 | import io.github.yuanbaobaoo.dify.routes.ConsoleRoutes;
7 | import io.github.yuanbaobaoo.dify.types.DifyPage;
8 | import io.github.yuanbaobaoo.dify.types.ApiConfig;
9 | import io.github.yuanbaobaoo.dify.SimpleHttpClient;
10 | import io.github.yuanbaobaoo.dify.types.DifyRoute;
11 | import io.github.yuanbaobaoo.dify.web.IWebConsoleClient;
12 | import io.github.yuanbaobaoo.dify.web.entity.TokenList;
13 | import lombok.extern.slf4j.Slf4j;
14 |
15 | import java.util.HashMap;
16 | import java.util.Map;
17 |
18 | @Slf4j
19 | public class WebClientImpl implements IWebConsoleClient {
20 | private final ApiConfig config;
21 |
22 | /**
23 | * constructor
24 | *
25 | * @param server Dify 服务地址
26 | * @param token Dify access token
27 | */
28 | public WebClientImpl(String server, TokenList token) {
29 | config = ApiConfig.builder().server(server).apiKey(token.getAccessToken()).refreshToken(token.getRefreshToken()).build();
30 | }
31 |
32 | @Override
33 | public SimpleHttpClient httpClient() {
34 | return SimpleHttpClient.get(config);
35 | }
36 |
37 | @Override
38 | public String token() {
39 | return config.getApiKey();
40 | }
41 |
42 | @Override
43 | public String refreshToken() {
44 | return config.getRefreshToken();
45 | }
46 |
47 | @Override
48 | public DifyPage queryApps(int page, int limit, String name) {
49 | String result = SimpleHttpClient.get(config).requestJson(ConsoleRoutes.APPS, new HashMap<>() {{
50 | put("page", page);
51 | put("limit", limit);
52 | put("name", name);
53 | }});
54 |
55 | return JSON.parseObject(result, new TypeReference>() {});
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/src/test/java/io/github/yuanbaobaoo/dify/DatasetClientTest.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify;
2 |
3 | import com.alibaba.fastjson2.JSON;
4 | import io.github.yuanbaobaoo.dify.dataset.IDatasetClient;
5 | import io.github.yuanbaobaoo.dify.dataset.entity.*;
6 | import io.github.yuanbaobaoo.dify.dataset.heros.DatasetHero;
7 | import io.github.yuanbaobaoo.dify.dataset.heros.DocumentHero;
8 | import io.github.yuanbaobaoo.dify.dataset.params.ParamDataset;
9 | import io.github.yuanbaobaoo.dify.dataset.params.ParamDocument;
10 | import io.github.yuanbaobaoo.dify.dataset.types.*;
11 | import io.github.yuanbaobaoo.dify.types.DifyException;
12 | import io.github.yuanbaobaoo.dify.types.DifyPage;
13 | import org.junit.jupiter.api.Test;
14 |
15 | import java.io.File;
16 | import java.util.ArrayList;
17 | import java.util.List;
18 |
19 | public class DatasetClientTest {
20 | IDatasetClient client = DifyClientBuilder.dataset()
21 | .baseUrl("https://api.dify.ai/v1")
22 | .apiKey("dataset-")
23 | .build();
24 |
25 | @Test
26 | public void testCreate() {
27 | try {
28 | ParamDataset dataset = ParamDataset.builder()
29 | .name("test6")
30 | .build();
31 |
32 | DatasetHero set = client.create(dataset);
33 | System.out.println("ok: " + JSON.toJSONString(set));
34 |
35 | ParamDocument document = ParamDocument.builder()
36 | .name("测试文档")
37 | .text("你好啊你好吧")
38 | .indexingTechnique(DatasetConsts.IndexingTechnique.high_quality)
39 | .processRule(ProcessRule.builder().mode(ProcessRule.Mode.automatic).build())
40 | .build();
41 |
42 | DocumentResult doc = set.insertText(document);
43 | System.out.println("ok: " + JSON.toJSONString(doc));
44 | } catch (DifyException e) {
45 | System.out.println("error dify: " + e.toString());
46 | } catch (Exception e) {
47 | e.printStackTrace();
48 | }
49 | }
50 |
51 | @Test
52 | public void testList() {
53 | try {
54 | DifyPage sets = client.list(1, 20);
55 | System.out.println("ok: " + JSON.toJSONString(sets));
56 | } catch (DifyException e) {
57 | System.out.println("error dify: " + e.toString());
58 | } catch (Exception e) {
59 | e.printStackTrace();
60 | }
61 | }
62 |
63 | @Test
64 | public void testDelete() {
65 | try {
66 | client.delete("f779a91f-1f89-4581-bc26-95a2d50239d6");
67 | } catch (DifyException e) {
68 | System.out.println("error dify: " + e.toString());
69 | } catch (Exception e) {
70 | e.printStackTrace();
71 | }
72 | }
73 |
74 | @Test
75 | public void testCreateByText() {
76 | try {
77 | ParamDocument document = ParamDocument.builder()
78 | .name("测试文档")
79 | .text("你好啊你好吧")
80 | .indexingTechnique(DatasetConsts.IndexingTechnique.economy)
81 | .processRule(ProcessRule.builder().mode(ProcessRule.Mode.automatic).build())
82 | .build();
83 |
84 | DatasetHero set = client.ofDataset("7a07305e-2663-4ae5-82aa-4e6297aaa946");
85 | DocumentResult doc = set.insertText(document);
86 |
87 | System.out.println("ok: " + JSON.toJSONString(doc));
88 | } catch (DifyException e) {
89 | System.out.println("error dify: " + e.toString());
90 | } catch (Exception e) {
91 | e.printStackTrace();
92 | }
93 | }
94 |
95 | @Test
96 | public void testBatchIndexStatus() {
97 | try {
98 |
99 | DatasetHero set = client.ofDataset("7a07305e-2663-4ae5-82aa-4e6297aaa946");
100 | List bs = set.queryBatchStatus("20250318080900526712");
101 |
102 | System.out.println("ok: " + JSON.toJSONString(bs));
103 | } catch (DifyException e) {
104 | System.out.println("error dify: " + e.toString());
105 | } catch (Exception e) {
106 | e.printStackTrace();
107 | }
108 | }
109 |
110 | @Test
111 | public void testCreateByFile() {
112 | try {
113 | ParamDocument document = ParamDocument.builder()
114 | .indexingTechnique(DatasetConsts.IndexingTechnique.economy)
115 | .processRule(ProcessRule.builder().mode(ProcessRule.Mode.automatic).build())
116 | .build();
117 |
118 | DatasetHero set = client.ofDataset("7a07305e-2663-4ae5-82aa-4e6297aaa946");
119 | DocumentResult doc = set.insertFile(new File("C:\\Users\\Hodge\\Desktop\\测试.txt"), document);
120 |
121 | System.out.println("ok: " + JSON.toJSONString(doc));
122 | } catch (DifyException e) {
123 | System.out.println("error dify: " + e.getOriginal());
124 | } catch (Exception e) {
125 | e.printStackTrace();
126 | }
127 | }
128 |
129 | @Test
130 | public void testDocList() {
131 | try {
132 | DatasetHero set = client.ofDataset("7a07305e-2663-4ae5-82aa-4e6297aaa946");
133 | DifyPage docs = set.documents();
134 | System.out.println("ok: " + JSON.toJSONString(docs));
135 |
136 | DifyPage docs2 = set.documents(1, 1, null);
137 | System.out.println("ok: " + JSON.toJSONString(docs2));
138 | } catch (DifyException e) {
139 | System.out.println("error dify: " + e.getOriginal());
140 | } catch (Exception e) {
141 | e.printStackTrace();
142 | }
143 | }
144 |
145 | @Test
146 | public void testRetrieve() {
147 | try {
148 | DatasetHero set = client.ofDataset("c74c5f4b-77c6-4572-a16f-576073f03a1a");
149 | RetrieveResult res = set.retrieve("1");
150 |
151 | System.out.println("ok: " + JSON.toJSONString(res));
152 | } catch (DifyException e) {
153 | System.out.println("error dify: " + e.getOriginal());
154 | } catch (Exception e) {
155 | e.printStackTrace();
156 | }
157 | }
158 |
159 | @Test
160 | public void testDocUpdateByText() {
161 | try {
162 | DocumentHero document = client.ofDocument(
163 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
164 | "2fd22db4-dea9-48d4-89c2-44bf67a2f313"
165 | );
166 |
167 | DocumentResult res = document.updateByText(ParamDocument.builder()
168 | .name("测试.txt2")
169 | .text("又疑瑶台近,飞上青云端")
170 | .build()
171 | );
172 |
173 | System.out.println("ok: " + JSON.toJSONString(res));
174 | } catch (DifyException e) {
175 | System.out.println("error dify: " + e.getOriginal());
176 | } catch (Exception e) {
177 | e.printStackTrace();
178 | }
179 | }
180 |
181 | @Test
182 | public void testDocUpdateByFile() {
183 | try {
184 | DocumentHero document = client.ofDocument(
185 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
186 | "2fd22db4-dea9-48d4-89c2-44bf67a2f313"
187 | );
188 |
189 | DocumentResult res = document.updateByFile(
190 | new File("C:\\Users\\Hodge\\Desktop\\测试.txt"),
191 | ProcessRule.builder().mode(ProcessRule.Mode.automatic).build()
192 | );
193 |
194 | System.out.println("ok: " + JSON.toJSONString(res));
195 | } catch (DifyException e) {
196 | System.out.println("error dify: " + e.getOriginal());
197 | } catch (Exception e) {
198 | e.printStackTrace();
199 | }
200 | }
201 |
202 | @Test
203 | public void testDocDelete() {
204 | try {
205 | DocumentHero document = client.ofDocument(
206 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
207 | "2fd22db4-dea9-48d4-89c2-44bf67a2f313"
208 | );
209 |
210 | Boolean res = document.delete();
211 |
212 | System.out.println("ok: " + JSON.toJSONString(res));
213 | } catch (DifyException e) {
214 | System.out.println("error dify: " + e.getOriginal());
215 | } catch (Exception e) {
216 | e.printStackTrace();
217 | }
218 | }
219 |
220 | @Test
221 | public void testDocSegList() {
222 | try {
223 | DocumentHero document = client.ofDocument(
224 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
225 | "3094bc50-6356-406f-a3ae-c2541eb406cd"
226 | );
227 |
228 | SegmentResult res = document.querySegments();
229 | System.out.println("ok: " + JSON.toJSONString(res));
230 |
231 | SegmentResult res1 = document.querySegments("Copy");
232 | System.out.println("ok: " + JSON.toJSONString(res1));
233 |
234 | SegmentResult res2 = document.querySegments(null, "completed");
235 | System.out.println("ok: " + JSON.toJSONString(res2));
236 |
237 | } catch (DifyException e) {
238 | System.out.println("error dify: " + e.getOriginal());
239 | } catch (Exception e) {
240 | e.printStackTrace();
241 | }
242 | }
243 |
244 | @Test
245 | public void testDocSegAdd() {
246 | try {
247 | DocumentHero document = client.ofDocument(
248 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
249 | "3094bc50-6356-406f-a3ae-c2541eb406cd"
250 | );
251 |
252 | Segment segment = Segment.builder().content("你好").keywords(new ArrayList<>() {{
253 | add("你");
254 | add("好");
255 | add("吗");
256 | }}).build();
257 |
258 | SegmentResult res = document.insertSegment(List.of(segment));
259 | System.out.println("ok: " + JSON.toJSONString(res));
260 | } catch (DifyException e) {
261 | System.out.println("error dify: " + e.getOriginal());
262 | } catch (Exception e) {
263 | e.printStackTrace();
264 | }
265 | }
266 |
267 | @Test
268 | public void testDocSegDel() {
269 | try {
270 | DocumentHero document = client.ofDocument(
271 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
272 | "3094bc50-6356-406f-a3ae-c2541eb406cd"
273 | );
274 |
275 | Boolean res = document.deleteSegment("84ab19cb-8be5-4f50-a699-3c40e9839169");
276 | System.out.println("ok: " + JSON.toJSONString(res));
277 | } catch (DifyException e) {
278 | System.out.println("error dify: " + e.getOriginal());
279 | } catch (Exception e) {
280 | e.printStackTrace();
281 | }
282 | }
283 |
284 | @Test
285 | public void testDocSegUpdate() {
286 | try {
287 | DocumentHero document = client.ofDocument(
288 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
289 | "3094bc50-6356-406f-a3ae-c2541eb406cd"
290 | );
291 |
292 | SegmentResult res = document.updateSegment("5f765e3f-633e-49c2-a862-8d2eecb6dbca", "你好吧", false);
293 | System.out.println("ok: " + JSON.toJSONString(res));
294 |
295 | SegmentResult res1 = document.updateSegment(
296 | Segment.builder()
297 | .id("5f765e3f-633e-49c2-a862-8d2eecb6dbca")
298 | .content("我不好")
299 | .build(),
300 | false
301 | );
302 | System.out.println("ok: " + JSON.toJSONString(res1));
303 | } catch (DifyException e) {
304 | System.out.println("error dify: " + e.getOriginal());
305 | } catch (Exception e) {
306 | e.printStackTrace();
307 | }
308 | }
309 |
310 | @Test
311 | public void testDocFileInfo() {
312 | try {
313 | DocumentHero document = client.ofDocument(
314 | "7a07305e-2663-4ae5-82aa-4e6297aaa946",
315 | "3094bc50-6356-406f-a3ae-c2541eb406cd"
316 | );
317 |
318 | DocFileInfo info = document.queryFileInfo();
319 | System.out.println("ok: " + JSON.toJSONString(info));
320 | } catch (DifyException e) {
321 | System.out.println("error dify: " + e.getOriginal());
322 | } catch (Exception e) {
323 | e.printStackTrace();
324 | }
325 | }
326 |
327 | }
328 |
--------------------------------------------------------------------------------
/src/test/java/io/github/yuanbaobaoo/dify/DifyAppClientTest.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify;
2 |
3 | import com.alibaba.fastjson2.JSON;
4 | import com.alibaba.fastjson2.JSONObject;
5 | import io.github.yuanbaobaoo.dify.app.IAppBaseClient;
6 | import io.github.yuanbaobaoo.dify.routes.AppRoutes;
7 | import io.github.yuanbaobaoo.dify.types.DifyException;
8 | import org.junit.jupiter.api.Test;
9 |
10 | import java.util.concurrent.CompletableFuture;
11 |
12 | public class DifyAppClientTest {
13 | IAppBaseClient client = DifyClientBuilder.app()
14 | .base()
15 | .baseUrl("https://api.dify.ai/v1")
16 | .apiKey("app-")
17 | .build();
18 |
19 | @Test
20 | public void blockTest() {
21 | JSONObject object = JSON.parseObject("""
22 | {
23 | "inputs": {
24 | "name": "元宝宝"
25 | },
26 | "user": "abc-123",
27 | "query": "测试方法有哪些"
28 |
29 | }
30 | """);
31 |
32 | try {
33 | String res = client.requestBlocking(AppRoutes.CHAT_MESSAGES, null, object);
34 | System.out.println("ok: " + JSON.parse(res).toString());
35 | } catch (DifyException e) {
36 | System.out.println("error dify: " + e.toString());
37 | } catch (Exception e) {
38 | e.printStackTrace();
39 | }
40 | }
41 |
42 | @Test
43 | public void streamTest() {
44 | JSONObject object = JSON.parseObject("""
45 | {
46 | "inputs": {
47 | "name":"元宝宝"
48 | },
49 | "user": "abc-123",
50 | "query": "测试方法有哪些"
51 |
52 | }
53 | """);
54 |
55 | try {
56 | CompletableFuture future = client.requestStreaming(AppRoutes.CHAT_MESSAGES, null, object, (s) -> {
57 | System.out.println("ok: " + JSON.parse(s).toString());
58 | });
59 |
60 | future.join();
61 | } catch (Exception e) {
62 | Throwable cause = e.getCause();
63 | if (cause instanceof DifyException) {
64 | System.out.println("error dify: " + cause);
65 | } else {
66 | e.printStackTrace();
67 | }
68 | }
69 | }
70 |
71 | @Test
72 | public void testFeed() {
73 | try {
74 | Boolean b = client.feedbacks("a915e09b-ec5e-49b6-9be2-8b8f0f806ac7", "like","abc-1234", "a");
75 | System.out.println(b);
76 | } catch (DifyException e) {
77 | System.out.println("error dify: " + e.toString());
78 | } catch (Exception e) {
79 | Throwable cause = e.getCause();
80 | if (cause instanceof DifyException) {
81 | System.out.println("error dify: " + cause);
82 | } else {
83 | e.printStackTrace();
84 | }
85 | }
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/test/java/io/github/yuanbaobaoo/dify/DifyWebClientTest.java:
--------------------------------------------------------------------------------
1 | package io.github.yuanbaobaoo.dify;
2 |
3 | import com.alibaba.fastjson2.JSON;
4 | import com.alibaba.fastjson2.JSONObject;
5 | import io.github.yuanbaobaoo.dify.types.DifyClientException;
6 | import io.github.yuanbaobaoo.dify.types.DifyException;
7 | import io.github.yuanbaobaoo.dify.types.DifyPage;
8 | import io.github.yuanbaobaoo.dify.web.IWebConsoleClient;
9 | import org.junit.jupiter.api.Test;
10 |
11 | public class DifyWebClientTest {
12 |
13 | @Test
14 | public void testApps() {
15 | try {
16 | IWebConsoleClient client = connect();
17 | System.out.println(client.token());
18 |
19 | DifyPage res = client.queryApps(1, 30, null);
20 | System.out.println("ok: " + JSON.toJSONString(res));
21 | } catch (DifyException | DifyClientException e) {
22 | System.out.println("error dify: " + e.toString());
23 | } catch (Exception e) {
24 | e.printStackTrace();
25 | }
26 | }
27 |
28 | /**
29 | * connect to dify server
30 | */
31 | private IWebConsoleClient connect() {
32 | return DifyClientBuilder.web(
33 | "http://127.0.0.1:8080",
34 | "user",
35 | "password"
36 | ).connect();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------