├── .gitignore ├── LICENSE ├── README.md ├── README_EN.md ├── pom.xml └── src ├── main └── java │ └── io │ └── github │ └── yuanbaobaoo │ └── dify │ ├── DifyClientBuilder.java │ ├── SimpleHttpClient.java │ ├── app │ ├── IAppBaseClient.java │ ├── IAppChatClient.java │ ├── IAppCompletion.java │ ├── IAppFlowClient.java │ ├── impl │ │ ├── AppBaseClientImpl.java │ │ ├── AppChatClientImpl.java │ │ ├── AppCompletionImpl.java │ │ └── AppFlowClientImpl.java │ ├── params │ │ ├── ParamFile.java │ │ └── ParamMessage.java │ └── types │ │ ├── DifyChatEvent.java │ │ ├── DifyChatResult.java │ │ ├── DifyFileResult.java │ │ ├── DifyWorkFlowResult.java │ │ ├── ResponseMode.java │ │ └── WorkflowStatus.java │ ├── dataset │ ├── IDatasetClient.java │ ├── IKnowledgeService.java │ ├── entity │ │ ├── Dataset.java │ │ ├── DocFileInfo.java │ │ ├── Document.java │ │ ├── Segment.java │ │ └── SegmentChildChunk.java │ ├── heros │ │ ├── DatasetHero.java │ │ └── DocumentHero.java │ ├── impl │ │ └── DatasetClientImpl.java │ ├── params │ │ ├── ParamDataset.java │ │ ├── ParamDocument.java │ │ └── ParamUpdateDataset.java │ └── types │ │ ├── BatchStatus.java │ │ ├── DatasetConsts.java │ │ ├── DocumentResult.java │ │ ├── ProcessRule.java │ │ ├── RetrievalModel.java │ │ ├── RetrieveResult.java │ │ ├── SegmentResult.java │ │ └── external │ │ ├── KnowledgeArgs.java │ │ ├── KnowledgeException.java │ │ └── KnowledgeResult.java │ ├── routes │ ├── AppRoutes.java │ ├── ConsoleRoutes.java │ └── DatasetRoutes.java │ ├── types │ ├── ApiConfig.java │ ├── AudioFile.java │ ├── DifyClientException.java │ ├── DifyException.java │ ├── DifyPage.java │ ├── DifyRoute.java │ ├── HttpMethod.java │ └── WebConfig.java │ ├── utils │ ├── AppClientBuilder.java │ ├── DatasetBuilder.java │ └── WebClientBuilder.java │ └── web │ ├── IWebConsoleClient.java │ ├── WebAuthService.java │ ├── entity │ └── TokenList.java │ └── impl │ └── WebClientImpl.java └── test └── java └── io └── github └── yuanbaobaoo └── dify ├── DatasetClientTest.java ├── DifyAppClientTest.java └── DifyWebClientTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | *.iml 3 | target 4 | /src/test/java/io/github/yuanbaobaoo/dify/test/ 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | dify-java-client 2 | --- 3 | 4 |

5 | 6 | maven-central 7 | 8 |   9 | 10 | maven-central 11 | 12 |   13 | 14 | maven-central 15 | 16 |

17 | 18 | 简单易用的 Dify Java客户端,支持在任意Java项目中使用 [Dify](https://dify.ai/) 的工作流、对话助手、Agent、Dataset、文字转语音、语音转文字等开放能力。 19 | 20 | 中文 | [English](./README_EN.md) 21 | 22 | ## 安装依赖 23 | - 环境需求 24 | ```code 25 | Java : >= 17 26 | Dify Version: <= 1.x 27 | ``` 28 | 29 | - maven 30 | ```xml 31 | 32 | io.github.yuanbaobaoo 33 | dify-java-client 34 | 1.4.4 35 | 36 | ``` 37 | 38 | - gradle 39 | ```gradle 40 | implementation group: 'io.github.yuanbaobaoo', name: 'dify-java-client', version: '1.4.4' 41 | ``` 42 | 43 | ## 快速开始 44 | 使用 ```DifyClientBuilder``` 创建各类客户端实例 45 | ```java 46 | /** 47 | * 创建一个对话类型客户端对象,支持 base()、chat()、flow()、completion() 其对应返回类型也是不一致的 48 | */ 49 | IAppChatClient appClient = DifyClientBuilder.app().chat().apiKey("app-xxx").baseUrl("https://api.dify.ai/v1").build(); 50 | 51 | /** 52 | * 创建一个知识库类型客户端对象 53 | */ 54 | IDatasetClient datasetClient = DifyClientBuilder.dataset().apiKey("app-xxx").baseUrl("https://api.dify.ai/v1").build(); 55 | 56 | /** 57 | * 创建一个WebConsole类型客户端对象,用于模拟Dify控制台操作(试验特性) 58 | */ 59 | IWebConsoleClient webClient = DifyClientBuilder.web("${server}", "${userName}", "${password}").connect(); 60 | ``` 61 | 62 | ## 创建 App 类型的 Client 63 | 在代码中,使用 ```DifyClientBuilder.app()``` 即可创建App类型的客户端对象。 64 | App客户端是指适用于 ChatBot、Agent、ChatFlow、Completion 类型的应用,提供了会话相关的API,支持会话的流式返回。主要包含如下: 65 | - [```IAppBaseClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppBaseClient.java) 66 | - [```IAppChatClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppChatClient.java) 67 | - [```IAppFlowClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppFlowClient.java) 68 | - [```IAppCompletion```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppCompletion.java) 69 | 70 | ### 1、IAppBaseClient 71 | 基础Client,提供Dify公共API,具体可查阅 ```IAppBaseClient``` 72 | ```java 73 | IAppBaseClient client = DifyClientBuilder.app().base().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 74 | 75 | // 调用接口 76 | String metaInfo = client.getAppMetaInfo(); 77 | // 上传文件 78 | DifyFileResult result = client.uploadFile(new File("pom.xml"), "abc-123"); 79 | ``` 80 | 81 | ### 2、IAppChatClient 82 | 适用于 ChatBot、Agent、ChatFlow 类型应用,继承自 ```IAppBaseClient```,提供了会话相关的API: 83 | ```java 84 | IAppChatClient client = DifyClientBuilder.app().chat().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 85 | 86 | // 创建消息 87 | ParamMessage m = ParamMessage.builder().query("你是谁").user("abc-123").inputs(Map.of( 88 | "test", "value", 89 | "file1", ParamFile.builder() 90 | .type(ParamFile.FileType.audio) 91 | .transferMethod(ParamFile.TransferMethod.remote_url) 92 | .build() 93 | )).build(); 94 | 95 | // 发送阻塞消息 96 | DifyChatResult result = chatClient.sendMessages(m); 97 | 98 | // 发送流式消息 99 | CompletableFuture future = client.sendMessagesAsync(m, (r) -> { 100 | System.out.println("ok: " + r.getPayload().toJSONString()); 101 | }); 102 | ``` 103 | 104 | ### 3、IAppFlowClient 105 | 适用于 WorkFlow 类型应用,继承自 ```IAppBaseClient```,提供了工作流相关的API: 106 | ```java 107 | IAppFlowClient flowClient = DifyClientBuilder.app().flow().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 108 | 109 | // 创建消息 110 | ParamMessage m = ParamMessage.builder().user("abc-123").inputs(Map.of( 111 | "name", "元宝宝", 112 | "text", "Java为什么叫Java?" 113 | )).build(); 114 | 115 | // 阻塞式运行工作流 116 | DifyChatResult result = flowClient.runBlocking(m); 117 | 118 | // 流式运行工作流 119 | CompletableFuture future = client.runStreaming(m, (r) -> { 120 | System.out.println("ok: " + r.getPayload().toJSONString()); 121 | }); 122 | ``` 123 | 124 | ### 4、IAppCompletion 125 | 适用于 Completion 类型应用,继承自 ```IAppBaseClient```,提供了文本生成相关的API: 126 | ```java 127 | IAppCompletion completion = DifyClientBuilder.completion().flow().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 128 | 129 | // 创建消息 130 | ParamMessage m = ParamMessage.builder().query("Java为什么叫Java").user("abc-123").build(); 131 | 132 | // 阻塞式运行 133 | DifyChatResult result = completion.sendMessages(m); 134 | 135 | // 流式运行 136 | CompletableFuture future = completion.sendMessagesAsync(m, (r) -> { 137 | System.out.println("ok: " + r.getPayload().toJSONString()); 138 | }); 139 | ``` 140 | 141 | ## 创建 知识库 类型的 Client 142 | 当前项目提供了内部知识库Client 与 外部知识库相关类型定义,其中外部知识库并没有做具体实现。 143 | 144 | ### Dify内置知识库: IDifyDatasetClient 145 | 具体API定义,请查阅 [```io.github.yuanbaobaoo.dify.dataset.IDifyDatasetClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/dataset/IDatasetClient.java) 146 | 147 | #### 参考案例 148 | ```java 149 | IDatasetClient client = DifyClientBuilder.dataset().apiKey("dataset-xxxx").baseUrl("https://api.dify.ai/v1").build(); 150 | 151 | // 声明参数 152 | ParamDataset dataset = ParamDataset.builder() 153 | .name("你的知识库名称") 154 | .build(); 155 | 156 | // 创建空知识库 157 | client.create(dataset); 158 | ``` 159 | 160 | #### Hero类 161 | 项目中,针对知识库的工具类,除了提供了基于 ```IDatasetClient``` 的相关方法外,还提供了Hero类对知识库进行操作支持。 162 | 具体使用哪种方式,取决于你的需求。 163 | 164 | - 案例一:新增文档 165 | ```java 166 | // dify 配置 167 | DifyConfig config = DifyConfig.builder().server("https://api.dify.ai/v1").apiKey("dataset-xxxx").build(); 168 | 169 | // 声明参数 170 | ParamDocument document = ParamDocument.builder() 171 | .name("测试文档") 172 | .text("你好啊你好吧") 173 | .indexingTechnique(DatasetConsts.IndexingTechnique.high_quality) 174 | .processRule(ProcessRule.builder().mode(ProcessRule.Mode.automatic).build()) 175 | .build(); 176 | ``` 177 | 方式1、直接使用 IDatasetClient操作API 178 | ```java 179 | IDatasetClient client = DifyClientBuilder.dataset().config(config).build(); 180 | client.insertDocByText("知识库ID", document); 181 | ``` 182 | 方式2、使用 DifyClientBuilder 创建一个 Hero对象 183 | ```java 184 | DatasetHero dataset = DifyClientBuilder.dataset().config(config).of("知识库ID"); 185 | dataset.insertTxt(document); 186 | ``` 187 | 方式3、直接创建Hero对象 188 | ```java 189 | DatasetHero dataset = DatasetHero.of("知识库ID", config); 190 | dataset.insertTxt(document); 191 | ``` 192 | 193 | - 案例2:更新文档 194 | ```java 195 | // dify 配置 196 | DifyConfig config = DifyConfig.builder().server("https://api.dify.ai/v1").apiKey("dataset-xxxx").build(); 197 | 198 | // 声明参数 199 | ParamDocument document = ParamDocument.builder() 200 | .name("测试.txt2") 201 | .text("又疑瑶台近,飞上青云端") 202 | .build(); 203 | ``` 204 | 方式1、直接使用 IDatasetClient操作API 205 | ```java 206 | IDatasetClient client = DifyClientBuilder.dataset().config(config).build(); 207 | client.updateDocByText("知识库ID", "文档ID", dataset); 208 | ``` 209 | 方式2、使用 DifyClientBuilder 创建一个 Hero对象 210 | ```java 211 | DocumentHero documentHero = DifyClientBuilder.dataset().config(config).ofDocument("知识库ID", "文档ID"); 212 | documentHero.updateByText(document); 213 | ``` 214 | 方式3、直接创建Hero对象 215 | ```java 216 | DocumentHero documentHero = DocumentHero.of("知识库ID", "文档ID", config); 217 | documentHero.updateByText(document); 218 | ``` 219 | 220 | ### Dify外部知识库: IKnowledgeService 221 | 当前项目并未对知识库API做实现,只声明了相关参数对象和接口 222 | ```java 223 | public interface IKnowledgeService { 224 | /** 225 | * 知识检索 226 | * @param apiKey Dify传递的API KEY 227 | * @param args KnowledgeArgs 228 | */ 229 | KnowledgeResult retrieval(String apiKey, KnowledgeArgs args); 230 | } 231 | ``` 232 | 如果你有需求,可以基于声明的参数与接口进行实现即可,以下为参考代码“: 233 | - 1、声明一个endpoint 234 | ```java 235 | /** 236 | * 检索本地知识库内容 237 | * @param args KnowledgeArgs 238 | */ 239 | @PostMapping("/retrieval") 240 | public KnowledgeResult retrieval(@RequestBody(required = false) KnowledgeArgs args, HttpServletRequest request) { 241 | return knowledgeService.retrieval(request.getHeader("Authorization"), args); 242 | } 243 | ``` 244 | - 2、实现接口```io.github.yuanbaobaoo.dify.dataset.IKnowledgeService``` 245 | ```java 246 | class KnowledgeService implements IKnowledgeService { 247 | @Override 248 | public KnowledgeResult retrieval(String apiKey, KnowledgeArgs args) { 249 | // TODO 你的本地知识库检索逻辑 250 | } 251 | } 252 | ``` 253 | 254 | ## 创建 WebConsole Client 255 | 用于模拟登录到 Dify Web控制台,并请求控制台的接口。 256 | - 参数 257 | ```java 258 | WebConfig config = WebConfig.builder() 259 | .server("https://api.dify.ai/") 260 | .userName("username") 261 | .password("password") 262 | .build(); 263 | ``` 264 | - 登录 265 | ```java 266 | IWebConsoleClient client = DifyClientBuilder.web(config).connect(); 267 | ``` 268 | - 请求 269 | ```java 270 | /** 271 | * get app list 272 | */ 273 | DifyPage res = client.queryApps(1, 30, null); 274 | 275 | /** 276 | * request custom api 277 | */ 278 | String res = client.httpClient().requestJson(); 279 | ``` 280 | 281 | ## 请求自定义接口 282 | 任意的Client对象,都拥有一个httpClient()方法, 283 | 该方法会返回一个已经注入了 api key 和 server url 或者 login token属性的 SimpleHttpClient 对象,你可以使用该对象进行自定义接口请求。 284 | ```java 285 | SimpleHttpClient http = client.httpClient(); 286 | ``` 287 | 288 | ## 异常处理 289 | - **DifyException** 290 | >默认情况下,当正常的请求返回了 http status >= 400 时,都会抛出一个异常对象 ```DifyException```。 291 | 该对象接收了Dify返回的 ```status```、```code```、```message```、```params``` 这几个属性。 292 | 当然你也可以通过 ```getOriginal()``` 方法获取原始返回内容。 293 | 294 | - **DifyClientException** 295 | >除了 ```DifyException``` 之外,其他所有类型的异常都会被包装成非受检异常 ```DifyClientException``` 抛出 -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 | dify-java-client 2 | --- 3 | 4 |

5 | 6 | maven-central 7 | 8 |   9 | 10 | maven-central 11 | 12 |   13 | 14 | maven-central 15 | 16 |

17 | 18 | The Simple and Easy-to-Use Dify Java Client, Support the use of [Dify](https://dify.ai/) Workflow, Assistant, Agent, Dataset, text to speech, voice to text, etc... 19 | 20 | [中文](./README.md) | English 21 | 22 | ### Installation 23 | - Requirements 24 | ```code 25 | Java : >= 17 26 | Dify Version: <= 1.x 27 | ``` 28 | 29 | - Maven 30 | ```xml 31 | 32 | io.github.yuanbaobaoo 33 | dify-java-client 34 | 1.4.4 35 | 36 | ``` 37 | 38 | - Gradle 39 | ```gradle 40 | implementation group: 'io.github.yuanbaobaoo', name: 'dify-java-client', version: '1.4.4' 41 | ``` 42 | 43 | ## Quick Start 44 | Create client instances using ```DifyClientBuilder``` 45 | ```java 46 | /** 47 | * Create a chat-type client for ChatBot/Agent/ChatFlow/Completion apps 48 | */ 49 | IAppChatClient appClient = DifyClientBuilder.app().chat().apiKey("app-xxx").baseUrl("https://api.dify.ai/v1").build(); 50 | 51 | /** 52 | * Create a dataset client 53 | */ 54 | IDatasetClient datasetClient = DifyClientBuilder.dataset().apiKey("app-xxx").baseUrl("https://api.dify.ai/v1").build(); 55 | 56 | /** 57 | * Create a WebConsole client (experimental) 58 | */ 59 | IWebConsoleClient webClient = DifyClientBuilder.web("${server}", "${userName}", "${password}").connect(); 60 | ``` 61 | 62 | ## App Clients 63 | Use ```DifyClientBuilder.app()``` to create app-type clients for ChatBot, Agent, ChatFlow, and Completion applications. 64 | It provides session related APIs and supports streaming return of sessions. It mainly includes the following: 65 | - [```IAppBaseClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppBaseClient.java) 66 | - [```IAppChatClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppChatClient.java) 67 | - [```IAppFlowClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppFlowClient.java) 68 | - [```IAppCompletion```](https://github.com/yuanbaobaoo/dify-java-client/blob/master/src/main/java/io/github/yuanbaobaoo/dify/app/IAppCompletion.java) 69 | 70 | ### 1、IAppBaseClient 71 | Base client providing common Dify APIs: 72 | ```java 73 | IAppBaseClient client = DifyClientBuilder.app().base().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 74 | 75 | // Call preset API 76 | String metaInfo = client.getAppMetaInfo(); 77 | // Upload file 78 | DifyFileResult result = client.uploadFile(new File("pom.xml"), "abc-123"); 79 | ``` 80 | 81 | ### 2、IAppChatClient 82 | For ChatBot/Agent/ChatFlow apps (extends IAppBaseClient): 83 | ```java 84 | IAppChatClient client = DifyClientBuilder.app().chat().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 85 | 86 | // create message 87 | ParamMessage m = ParamMessage.builder().query("Who are you").user("abc-123").inputs(new HashMap<>() {{ 88 | put("test", "value"); 89 | put("file1", ParamFile.builder() 90 | .type(ParamFile.FileType.audio) 91 | .transferMethod(ParamFile.TransferMethod.remote_url) 92 | .build() 93 | ); 94 | }}).build(); 95 | 96 | // send block message 97 | DifyChatResult result = chatClient.sendMessages(m); 98 | 99 | // send streaming message 100 | CompletableFuture future = client.sendMessagesAsync(m, (r) -> { 101 | System.out.println("ok: " + r.getPayload().toJSONString()); 102 | }); 103 | ``` 104 | 105 | ### 3、IAppFlowClient 106 | For WorkFlow apps (extends IAppBaseClient): 107 | ```java 108 | IAppFlowClient flowClient = DifyClientBuilder.app().flow().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 109 | 110 | // create message 111 | ParamMessage m = ParamMessage.builder().user("abc-123").inputs(new HashMap<>() {{ 112 | put("name", "元宝宝"); 113 | put("text", "Java为什么叫Java?"); 114 | }}).build(); 115 | 116 | // run workflow for blocking 117 | DifyChatResult result = flowClient.runBlocking(m); 118 | 119 | // run workflow for streaming 120 | CompletableFuture future = client.runStreaming(m, (r) -> { 121 | System.out.println("ok: " + r.getPayload().toJSONString()); 122 | }); 123 | ``` 124 | 125 | ### 4、IAppCompletion 126 | scope = Completion, extends ```IDifyBaseClient```, provides completion APIs 127 | ```java 128 | IAppCompletion completion = DifyClientBuilder.completion().flow().apiKey("app-xxxx").baseUrl("https://api.dify.ai/v1").build(); 129 | 130 | // create message 131 | ParamMessage m = ParamMessage.builder().query("Java为什么叫Java").user("abc-123").build(); 132 | 133 | // run with blocking 134 | DifyChatResult result = completion.sendMessages(m); 135 | 136 | // run with streaming 137 | CompletableFuture future = completion.sendMessagesAsync(m, (r) -> { 138 | System.out.println("ok: " + r.getPayload().toJSONString()); 139 | }); 140 | ``` 141 | 142 | ## Dataset Clients 143 | The current project provides the definition of internal knowledge base client and external knowledge base related types, 144 | of which the external knowledge base has not been specifically implemented. 145 | 146 | ### Dify Dataset: IDifyDatasetClient 147 | For specific API definitions, please refer to [```io.github.yuanbaobaoo.dify.client.dataset.IDifyDatasetClient```](https://github.com/yuanbaobaoo/dify-java-client/blob/feature/knowledge-api/src/main/java/io/github/yuanbaobaoo/dify/dataset/IDatasetClient.java) 148 | 149 | #### Examples 150 | ```java 151 | IDatasetClient client = DifyClientBuilder.dataset().apiKey("dataset-xxxx").baseUrl("https://api.dify.ai/v1").build(); 152 | 153 | // create params 154 | ParamDataset dataset = ParamDataset.builder() 155 | .name("your knowledge name") 156 | .build(); 157 | 158 | // request create 159 | client.create(dataset); 160 | ``` 161 | 162 | #### Hero Classes 163 | In the project, for the tool class of the knowledge base, in addition to providing related methods based on ```IDatasetClient```, 164 | it also provides Hero class to support the operation of the knowledge base.Which way to use depends on your needs. 165 | 166 | - Case 1: add document 167 | ```java 168 | // dify config 169 | DifyConfig config = DifyConfig.builder().server("https://api.dify.ai/v1").apiKey("dataset-xxxx").build(); 170 | 171 | // create params 172 | ParamDocument document = ParamDocument.builder() 173 | .name("测试文档") 174 | .text("你好啊你好吧") 175 | .indexingTechnique(DatasetConsts.IndexingTechnique.high_quality) 176 | .processRule(ProcessRule.builder().mode(ProcessRule.Mode.automatic).build()) 177 | .build(); 178 | ``` 179 | Mode1、use IDatasetClient 180 | ```java 181 | IDatasetClient client = DifyClientBuilder.dataset().config(config).build(); 182 | client.insertDocByText("Dataset Id", document); 183 | ``` 184 | Mode2、use DifyClientBuilder to build the Hero object 185 | ```java 186 | DatasetHero dataset = DifyClientBuilder.dataset().config(config).of("Dataset Id"); 187 | dataset.insertTxt(document); 188 | ``` 189 | Mode3、use Hero Class 190 | ```java 191 | DatasetHero dataset = DatasetHero.of("Dataset Id", config); 192 | dataset.insertTxt(document); 193 | ``` 194 | 195 | - Case 2: update document 196 | ```java 197 | // dify config 198 | DifyConfig config = DifyConfig.builder().server("https://api.dify.ai/v1").apiKey("dataset-xxxx").build(); 199 | 200 | // create params 201 | ParamDocument document = ParamDocument.builder() 202 | .name("测试.txt2") 203 | .text("又疑瑶台近,飞上青云端") 204 | .build(); 205 | ``` 206 | Mode1、use IDatasetClient 207 | ```java 208 | IDatasetClient client = DifyClientBuilder.dataset().config(config).build(); 209 | client.updateDocByText("Dataset ID", "Document ID", dataset); 210 | ``` 211 | Mode2、use DifyClientBuilder to build the Hero object 212 | ```java 213 | DocumentHero documentHero = DifyClientBuilder.dataset().config(config).ofDocument("Dataset ID", "Document ID"); 214 | documentHero.updateByText(document); 215 | ``` 216 | Mod3、use Hero Class 217 | ```java 218 | DocumentHero documentHero = DocumentHero.of("Dataset ID", "Document ID", config); 219 | documentHero.updateByText(document); 220 | ``` 221 | 222 | ### External Dataset: IKnowledgeService 223 | The current project dose not implement the knowledge API, and only declare parameter objects and interfaces 224 | ```java 225 | public interface IKnowledgeService { 226 | /** 227 | * retrieval 228 | * @param apiKey API KEY 229 | * @param args Knowledge Args 230 | */ 231 | KnowledgeResult retrieval(String apiKey, KnowledgeArgs args); 232 | } 233 | ``` 234 | If you have a need, you can implement the interface based on the declared parameters and interfaces, as follows is a reference code: 235 | - 1、create an endpoint 236 | ```java 237 | /** 238 | * retrieval api 239 | * @param args KnowledgeArgs 240 | */ 241 | @PostMapping("/retrieval") 242 | public KnowledgeResult retrieval(@RequestBody(required = false) KnowledgeArgs args, HttpServletRequest request) { 243 | return knowledgeService.retrieval(request.getHeader("Authorization"), args); 244 | } 245 | ``` 246 | - 2、implement the interface```io.github.yuanbaobaoo.dify.dataset.IKnowledgeService``` 247 | ```java 248 | class KnowledgeService implements IKnowledgeService { 249 | @Override 250 | public KnowledgeResult retrieval(String apiKey, KnowledgeArgs args) { 251 | // TODO Your local knowledge retrieval logic 252 | } 253 | } 254 | ``` 255 | 256 | ## WebConsole Client 257 | - params 258 | ```java 259 | WebConfig config = WebConfig.builder() 260 | .server("https://api.dify.ai/") 261 | .userName("username") 262 | .password("password") 263 | .build(); 264 | ``` 265 | - login 266 | ```java 267 | IWebConsoleClient client = DifyClientBuilder.web(config).connect(); 268 | ``` 269 | - request 270 | ```java 271 | /** 272 | * get app list 273 | */ 274 | DifyPage res = client.queryApps(1, 30, null); 275 | 276 | /** 277 | * request custom api 278 | */ 279 | String res = client.httpClient().requestJson(); 280 | ``` 281 | 282 | ## Custom Requests 283 | Any Client object has an httpClient () method, 284 | This method will return a SimpleFHIR object that has been injected with API key and server URL or login token attributes. 285 | You can use this object to make custom interface requests. 286 | ```java 287 | SimpleHttpClient http = client.httpClient(); 288 | ``` 289 | 290 | ## Exception Type 291 | - **DifyException** 292 | >By default, when the normal request returns http status>=400, an exception object ```DiffyException``` will be thrown. 293 | This object receives the '```status```, ```code```, ```message```, ```params```. 294 | Of course, you can also get the original return content through the ```getOriginal()``` method. 295 | 296 | - **DifyClientException** 297 | >Except for ```DifyException```, all other types of exceptions will be wrapped as non inspected exceptions ```DifyClientException``` and thrown -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | io.github.yuanbaobaoo 6 | dify-java-client 7 | 1.4.4 8 | The Simple Dify Java Client 9 | https://github.com/yuanbaobaoo/dify-java-client 10 | 11 | 12 | 13 | The Apache Software License, Version 2.0 14 | http://www.apache.org/licenses/LICENSE-2.0.txt 15 | 16 | 17 | 18 | 19 | 20 | yuanbaobaoo 21 | hodge.yuan@hotmail.com 22 | +8 23 | 24 | 25 | 26 | 27 | https://github.com/yuanbaobaoo/dify-java-client 28 | 29 | 30 | 31 | central 32 | 17 33 | ${java.version} 34 | ${java.version} 35 | UTF-8 36 | 37 | 38 | 39 | 40 | org.projectlombok 41 | lombok 42 | 1.18.32 43 | 44 | 45 | 46 | org.slf4j 47 | slf4j-api 48 | 2.0.12 49 | 50 | 51 | 52 | org.apache.commons 53 | commons-text 54 | 1.13.0 55 | 56 | 57 | 58 | com.alibaba.fastjson2 59 | fastjson2 60 | 2.0.56 61 | 62 | 63 | 64 | com.alibaba.fastjson2 65 | fastjson2-extension 66 | 2.0.56 67 | 68 | 69 | 70 | jakarta.servlet 71 | jakarta.servlet-api 72 | 6.0.0 73 | 74 | 75 | 76 | org.junit.jupiter 77 | junit-jupiter-api 78 | 5.11.1 79 | test 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | src/main/resources 88 | 89 | **/*.* 90 | 91 | 92 | 93 | 94 | 95 | maven-source-plugin 96 | 3.3.1 97 | 98 | true 99 | 100 | 101 | 102 | compile 103 | 104 | jar 105 | 106 | 107 | 108 | 109 | 110 | org.apache.maven.plugins 111 | maven-compiler-plugin 112 | 3.13.0 113 | 114 | true 115 | 116 | 117 | 118 | org.apache.maven.plugins 119 | maven-javadoc-plugin 120 | 3.11.2 121 | 122 | none 123 | ${project.build.sourceEncoding} 124 | ${project.build.sourceEncoding} 125 | 126 | 127 | 128 | package 129 | 130 | jar 131 | 132 | 133 | 134 | 135 | 136 | org.apache.maven.plugins 137 | maven-gpg-plugin 138 | 3.2.7 139 | 140 | 141 | verify 142 | 143 | sign 144 | 145 | 146 | 147 | 148 | 149 | org.sonatype.central 150 | central-publishing-maven-plugin 151 | 0.7.0 152 | true 153 | 154 | ${serverId} 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | ${serverId} 163 | https://central.sonatype.com/ 164 | 165 | 166 | 167 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/DifyClientBuilder.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify; 2 | 3 | import io.github.yuanbaobaoo.dify.types.ApiConfig; 4 | import io.github.yuanbaobaoo.dify.types.WebConfig; 5 | import io.github.yuanbaobaoo.dify.utils.AppClientBuilder; 6 | import io.github.yuanbaobaoo.dify.utils.DatasetBuilder; 7 | import io.github.yuanbaobaoo.dify.utils.WebClientBuilder; 8 | 9 | /** 10 | * The Dify Api Client Builder. 11 | * @link https://github.com/yuanbaobaoo/dify-java-client 12 | */ 13 | public class DifyClientBuilder { 14 | /** 15 | * get a app client builder. 16 | * DifyAppClient主要用于调用 dify app 的 open api 接口 17 | */ 18 | public static AppClientBuilder app() { 19 | return AppClientBuilder.builder(); 20 | } 21 | 22 | /** 23 | * get a app client builder 24 | * @param config DifyApiConfig 25 | */ 26 | public static AppClientBuilder app(ApiConfig config) { 27 | return AppClientBuilder.builder(config.getServer(), config.getApiKey()); 28 | } 29 | 30 | /** 31 | * get a app client builder 32 | * @param server Dify 服务地址 33 | * @param apiKey App Api Key 34 | */ 35 | public static AppClientBuilder app(String server, String apiKey) { 36 | return AppClientBuilder.builder(server, apiKey); 37 | } 38 | 39 | /** 40 | * get a dataset client builder 41 | * DifyDatasetClient主要用于调用 dify 内部知识库 的 open api 接口 42 | * @return DifyDatasetBuilder 43 | */ 44 | public static DatasetBuilder dataset() { 45 | return DatasetBuilder.builder(); 46 | } 47 | 48 | /** 49 | * get a dataset client builder 50 | * DifyDatasetClient主要用于调用 dify 内部知识库 的 open api 接口 51 | * @param server Dify 服务地址 52 | * @param apiKey 知识库API 53 | */ 54 | public static DatasetBuilder dataset(String server, String apiKey) { 55 | return DatasetBuilder.builder(server, apiKey); 56 | } 57 | 58 | /** 59 | * get a dataset client builder 60 | * DifyDatasetClient主要用于调用 dify 内部知识库 的 open api 接口 61 | * @param apiConfig DifyApiConfig 62 | */ 63 | public static DatasetBuilder dataset(ApiConfig apiConfig) { 64 | return DatasetBuilder.builder(apiConfig.getServer(), apiConfig.getApiKey()); 65 | } 66 | 67 | /** 68 | * get a web client builder 69 | * DifyWebClient是一种以API形式管理 Dify 各种功能的尝试. 例如创建应用、编辑应用等等 70 | */ 71 | public static WebClientBuilder web() { 72 | return WebClientBuilder.builder(); 73 | } 74 | 75 | /** 76 | * get a web client builder 77 | * DifyWebClient是一种以API形式管理 Dify 各种功能的尝试. 例如创建应用、编辑应用等等 78 | * @param server Dify 服务地址 79 | * @param userName 用户名 80 | * @param password 密码 81 | */ 82 | public static WebClientBuilder web(String server, String userName, String password) { 83 | return WebClientBuilder.builder(server, userName, password); 84 | } 85 | 86 | /** 87 | * get a web client builder. 88 | * DifyWebClient是一种以API形式管理 Dify 各种功能的尝试. 例如创建应用、编辑应用等等 89 | * @param config DifyWebConfig 90 | */ 91 | public static WebClientBuilder web(WebConfig config) { 92 | return WebClientBuilder.builder(config.getServer(), config.getUserName(), config.getPassword()); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/SimpleHttpClient.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify; 2 | 3 | import com.alibaba.fastjson2.JSON; 4 | import io.github.yuanbaobaoo.dify.types.*; 5 | import io.github.yuanbaobaoo.dify.types.ApiConfig; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.net.URI; 10 | import java.net.http.HttpClient; 11 | import java.net.http.HttpRequest; 12 | import java.net.http.HttpResponse; 13 | import java.nio.file.Files; 14 | import java.nio.file.Path; 15 | import java.util.*; 16 | import java.util.concurrent.CompletableFuture; 17 | import java.util.concurrent.ConcurrentHashMap; 18 | import java.util.function.Consumer; 19 | 20 | public class SimpleHttpClient { 21 | private final static Map cache = new ConcurrentHashMap<>(); 22 | 23 | private final String server; 24 | private final String apiKey; 25 | private final HttpClient httpClient; 26 | 27 | /** 28 | * constructor 29 | * 30 | * @param server Dify Server Address 31 | * @param apiKey Api Key 32 | */ 33 | private SimpleHttpClient(String server, String apiKey) { 34 | this.apiKey = apiKey; 35 | this.server = server; 36 | this.httpClient = HttpClient.newHttpClient(); 37 | } 38 | 39 | /** 40 | * 从缓存池中获取一个client对象,如果没有则创建 41 | * 42 | * @param config DifyConfig 43 | */ 44 | public static SimpleHttpClient get(ApiConfig config) { 45 | return get(config.getServer(), config.getApiKey()); 46 | } 47 | 48 | /** 49 | * 从缓存池中获取一个client对象,如果没有则创建 50 | * 51 | * @param server Dify Server Address 52 | * @param apiKey Api Key 53 | */ 54 | public static SimpleHttpClient get(String server, String apiKey) { 55 | return cache.computeIfAbsent(String.format("%s-%s", server, apiKey), id -> new SimpleHttpClient(server, apiKey)); 56 | } 57 | 58 | /** 59 | * 实例化一个新对象 60 | * 61 | * @param server Dify Server Address 62 | */ 63 | public static SimpleHttpClient newHttpClient(String server) { 64 | return new SimpleHttpClient(server, null); 65 | } 66 | 67 | /** 68 | * 实例化一个新对象 69 | * 70 | * @param server Dify Server Address 71 | * @param apiKey Api Key 72 | */ 73 | public static SimpleHttpClient newHttpClient(String server, String apiKey) { 74 | return new SimpleHttpClient(server, apiKey); 75 | } 76 | 77 | /** 78 | * request by application/json content-type 79 | * 80 | * @param route DifyRoute 81 | * @return String 82 | */ 83 | public String requestJson(DifyRoute route) { 84 | return requestJson(route.getUrl(), route.getMethod(), null, null); 85 | } 86 | 87 | /** 88 | * request by application/json content-type 89 | * 90 | * @param route DifyRoute 91 | * @param query Query 查询参数 92 | * @return String 93 | */ 94 | public String requestJson(DifyRoute route, Map query) { 95 | return requestJson(route.getUrl(), route.getMethod(), query, null); 96 | } 97 | 98 | /** 99 | * request by application/json content-type 100 | * 101 | * @param route DifyRoute 102 | * @param query Query 查询参数 103 | * @param params Body 参数 104 | * @return String 105 | */ 106 | public String requestJson(DifyRoute route, Map query, Object params) { 107 | return requestJson(route.getUrl(), route.getMethod(), query, params); 108 | } 109 | 110 | /** 111 | * request by application/json content-type 112 | * 113 | * @param url API URL 114 | * @param method HTTP请求方法 115 | * @param query Query 查询参数 116 | * @param params Body 参数 117 | * @return String 118 | */ 119 | public String requestJson(String url, HttpMethod method, Map query, Object params) { 120 | try { 121 | HttpRequest.Builder builder = buildRequest(url, query); 122 | 123 | if (params == null) { 124 | params = new HashMap<>(); 125 | } 126 | 127 | if (method == HttpMethod.GET) { 128 | builder.method(method.name(), HttpRequest.BodyPublishers.noBody()); 129 | } else { 130 | builder.header("Content-Type", "application/json"); 131 | builder.method(method.name(), HttpRequest.BodyPublishers.ofString(JSON.toJSONString(params))); 132 | } 133 | 134 | HttpResponse response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString()); 135 | 136 | // 所有非200响应都被视为dify平台的错误响应,统一返回异常对象 137 | if (response.statusCode() >= 400) { 138 | throw new DifyException(response.body(), response.statusCode()); 139 | } 140 | 141 | return response.body(); 142 | } catch (DifyException e) { 143 | throw e; 144 | } catch (Exception e) { 145 | throw new DifyClientException(e); 146 | } 147 | } 148 | 149 | /** 150 | * request by application/json content-type. return File bytes 151 | * 152 | * @param route DifyRoute 153 | * @param query query params 154 | * @param params body params 155 | */ 156 | public AudioFile requestFile(DifyRoute route, Map query, Object params) { 157 | return requestFile(route.getUrl(), route.getMethod(), query, params); 158 | } 159 | 160 | /** 161 | * request by application/json content-type. return File bytes 162 | * 163 | * @param url API URL 164 | * @param method HTTP METHOD 165 | * @param query query map 166 | * @param params body map 167 | */ 168 | public AudioFile requestFile(String url, HttpMethod method, Map query, Object params) { 169 | try { 170 | HttpRequest.Builder builder = buildRequest(url, query); 171 | 172 | if (params == null) { 173 | params = new HashMap<>(); 174 | } 175 | 176 | if (method == HttpMethod.GET) { 177 | builder.method(method.name(), HttpRequest.BodyPublishers.noBody()); 178 | } else { 179 | builder.header("Content-Type", "application/json"); 180 | builder.method(method.name(), HttpRequest.BodyPublishers.ofString(JSON.toJSONString(params))); 181 | } 182 | 183 | HttpResponse response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray()); 184 | 185 | // 所有非200响应都被视为dify平台的错误响应,统一返回异常对象 186 | if (response.statusCode() >= 400) { 187 | throw new DifyException(new String(response.body()), response.statusCode()); 188 | } 189 | 190 | String suffix = null; 191 | String contentType = null; 192 | Optional contentTypeOpt = response.headers().firstValue("Content-Type"); 193 | 194 | if (contentTypeOpt.isPresent()) { 195 | contentType = contentTypeOpt.get(); 196 | suffix = contentType.replaceAll(".*/", ""); 197 | } 198 | 199 | return AudioFile.builder().type(contentType).suffix(suffix).data(response.body()).build(); 200 | } catch (DifyException e) { 201 | throw e; 202 | } catch (Exception e) { 203 | throw new DifyClientException(e); 204 | } 205 | } 206 | 207 | /** 208 | * async request by application/json content-type 209 | * 210 | * @param route DifyRoute 211 | * @param query Query params 212 | * @param params Body params 213 | * @param consumer Consumer consumer 214 | */ 215 | public CompletableFuture requestJsonAsync( 216 | DifyRoute route, 217 | Map query, 218 | Map params, 219 | Consumer consumer 220 | ) { 221 | HttpRequest.Builder builder = buildRequest(route.getUrl(), query); 222 | 223 | if (route.getMethod() == HttpMethod.GET) { 224 | builder.method(route.getMethod().name(), HttpRequest.BodyPublishers.noBody()); 225 | } else { 226 | builder.header("Content-Type", "application/json"); 227 | builder.method(route.getMethod().name(), HttpRequest.BodyPublishers.ofString(JSON.toJSONString(params))); 228 | } 229 | 230 | // 异步发送请求并处理响应 231 | return httpClient.sendAsync(builder.build(), HttpResponse.BodyHandlers.ofLines()).thenAccept(response -> { 232 | response.body().forEach(line -> { 233 | if (response.statusCode() >= 400) { 234 | throw new DifyException(line, response.statusCode()); 235 | } 236 | 237 | consumer.accept(line); 238 | }); 239 | }); 240 | } 241 | 242 | /** 243 | * request by multipart/form-data content-type 244 | * 245 | * @param route DifyRoute 246 | * @param query Query 查询参数 247 | * @param params Body 参数,文件流需自行在params中传入 248 | * @return String 249 | */ 250 | public String requestMultipart(DifyRoute route, Map query, Map params) { 251 | return requestMultipart(route.getUrl(), route.getMethod(), query, params, null); 252 | } 253 | 254 | /** 255 | * request by multipart/form-data content-type 256 | * 257 | * @param route DifyRoute 258 | * @param query Query 查询参数 259 | * @param params Body 参数,文件流需自行在params中传入 260 | * @param fileType 如果该参数不为空,那么params中所有File或者Path类型的对象的ContentType将设置为该值 261 | * @return String 262 | */ 263 | public String requestMultipart(DifyRoute route, Map query, Map params, String fileType) { 264 | return requestMultipart(route.getUrl(), route.getMethod(), query, params, fileType); 265 | } 266 | 267 | /** 268 | * request by multipart/form-data content-type 269 | * 270 | * @param url API URL 271 | * @param method HTTP请求方法 272 | * @param query Query 查询参数 273 | * @param params Body 参数,文件流需自行在params中传入 274 | * @param fileType 如果该参数不为空,那么params中所有File或者Path类型的对象的ContentType将设置为该值 275 | * @return String 276 | */ 277 | public String requestMultipart(String url, HttpMethod method, Map query, Map params, String fileType) { 278 | try { 279 | HttpRequest.Builder builder = buildRequest(url, query); 280 | 281 | if (params == null) { 282 | params = new HashMap<>(); 283 | } 284 | 285 | String boundary = "-----------" + UUID.randomUUID().toString().replaceAll("-", ""); 286 | builder.header("Content-Type", "multipart/form-data; boundary=" + boundary); 287 | builder.method(method.name(), convertMapToMultipart(boundary, params, fileType)); 288 | HttpResponse response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString()); 289 | 290 | // 所有非200响应都被视为dify平台的错误响应,统一返回异常对象 291 | if (response.statusCode() >= 400) { 292 | throw new DifyException(response.body(), response.statusCode()); 293 | } 294 | 295 | return response.body(); 296 | } catch (DifyException e) { 297 | throw e; 298 | } catch (Exception e) { 299 | throw new DifyClientException(e); 300 | } 301 | } 302 | 303 | /** 304 | * build request 305 | * 306 | * @param url api url 307 | * @param query Query params 308 | */ 309 | public HttpRequest.Builder buildRequest(String url, Map query) { 310 | HttpRequest.Builder builder = HttpRequest.newBuilder(); 311 | StringBuilder sb = new StringBuilder(); 312 | 313 | if (this.server.endsWith("/") && url.startsWith("/")) { 314 | sb.append(this.server, 0, this.server.length() - 1); 315 | } else if (!this.server.endsWith("/") && !url.startsWith("/")) { 316 | sb.append(this.server).append('/'); 317 | } else { 318 | sb.append(this.server); 319 | } 320 | 321 | sb.append(url); 322 | 323 | if (query != null && !query.isEmpty()) { 324 | sb.append("?"); 325 | 326 | query.forEach((key, value) -> { 327 | if (key != null && value != null) { 328 | sb.append(key).append("=").append(value).append("&"); 329 | } 330 | }); 331 | 332 | sb.setLength(sb.length() - 1); 333 | } 334 | 335 | builder.uri(URI.create(sb.toString())); 336 | 337 | if (this.apiKey != null) { 338 | builder.header("Authorization", "Bearer " + this.apiKey); 339 | } 340 | 341 | return builder; 342 | } 343 | 344 | /** 345 | * 将 Map 转换为 multipart/form-data 格式的 BodyPublisher 346 | * 支持类型:String(文本)、Path/File(文件) 347 | */ 348 | private HttpRequest.BodyPublisher convertMapToMultipart(String boundary, Map data, String fileType) throws IOException { 349 | var parts = new ArrayList(); 350 | 351 | for (Map.Entry entry : data.entrySet()) { 352 | String key = entry.getKey(); 353 | Object value = entry.getValue(); 354 | 355 | if (key == null || value == null) { 356 | continue; 357 | } 358 | 359 | if (value instanceof Path || value instanceof File) { 360 | // 文件字段(支持 Path 或 File 对象) 361 | Path filePath = (value instanceof Path) ? (Path) value : ((File) value).toPath(); 362 | String fileName = filePath.getFileName().toString(); 363 | byte[] fileBytes = Files.readAllBytes(filePath); 364 | String contentType = null; 365 | 366 | if (fileType != null) { 367 | contentType = fileType; 368 | } else { 369 | String mimeType = Files.probeContentType(filePath); 370 | 371 | int index = fileName.lastIndexOf('.'); 372 | String ext = (index == -1 || index == fileName.length() - 1) ? "" : fileName.substring(index + 1); 373 | 374 | String[] type = mimeType.split("/"); 375 | contentType = String.format("%s/%s", type[0], ext); 376 | } 377 | 378 | parts.add(HttpRequest.BodyPublishers.ofString( 379 | "--" + boundary + "\r\n" + 380 | "Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + fileName + "\"\r\n" + 381 | "Content-Type: " + contentType + "\r\n\r\n" 382 | )); 383 | 384 | parts.add(HttpRequest.BodyPublishers.ofByteArray(fileBytes)); 385 | parts.add(HttpRequest.BodyPublishers.ofString("\r\n")); 386 | } else if (value instanceof String) { 387 | // 字符串 388 | parts.add(HttpRequest.BodyPublishers.ofString( 389 | "--" + boundary + "\r\n" + 390 | "Content-Disposition: form-data; name=\"" + key + "\"\r\n" + 391 | "Content-Type: text/plain\r\n\r\n" + 392 | value + "\r\n" 393 | )); 394 | } else { 395 | // 其他类型都使用JSON转换为字符串处理 396 | parts.add(HttpRequest.BodyPublishers.ofString( 397 | "--" + boundary + "\r\n" + 398 | "Content-Disposition: form-data; name=\"" + key + "\"\r\n" + 399 | "Content-Type: text/plain\r\n\r\n" + 400 | JSON.toJSONString(value) + "\r\n" 401 | )); 402 | } 403 | } 404 | 405 | // 添加结束边界 406 | parts.add(HttpRequest.BodyPublishers.ofString("--" + boundary + "--\r\n")); 407 | // 合并所有部分 408 | return HttpRequest.BodyPublishers.concat(parts.toArray(new HttpRequest.BodyPublisher[0])); 409 | } 410 | 411 | } 412 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/IAppBaseClient.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app; 2 | 3 | import com.alibaba.fastjson2.JSONObject; 4 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 5 | import io.github.yuanbaobaoo.dify.app.types.DifyFileResult; 6 | import io.github.yuanbaobaoo.dify.types.AudioFile; 7 | import io.github.yuanbaobaoo.dify.types.DifyPage; 8 | import io.github.yuanbaobaoo.dify.types.DifyRoute; 9 | 10 | import java.io.File; 11 | import java.util.Map; 12 | import java.util.concurrent.CompletableFuture; 13 | import java.util.function.Consumer; 14 | 15 | /** 16 | * 基础Dify客户端 17 | */ 18 | public interface IAppBaseClient { 19 | /** 20 | * 获取一个Simple http client 对象 21 | */ 22 | SimpleHttpClient httpClient(); 23 | 24 | /** 25 | * 获取应用基础信息 26 | * 27 | * @return String 28 | */ 29 | String getAppInfo(); 30 | 31 | /** 32 | * 获取应用参数信息 33 | * 34 | * @return String 35 | */ 36 | String getAppParameters(); 37 | 38 | /** 39 | * 获取应用元数据 40 | * 41 | * @return String 42 | */ 43 | String getAppMetaInfo(); 44 | 45 | /** 46 | * 上传文件 47 | * 48 | * @param file 文件对象 49 | * @param user 用户标识 50 | * @return DifyFileResult 51 | */ 52 | DifyFileResult uploadFile(File file, String user); 53 | 54 | /** 55 | * 消息反馈 56 | * 57 | * @param messageId 消息ID 58 | * @param rating 点赞 like, 点踩 dislike, 撤销点赞 null 59 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 60 | * @param content 消息反馈的具体信息。 61 | */ 62 | Boolean feedbacks(String messageId, String rating, String user, String content); 63 | 64 | /** 65 | * 语音转文字 66 | * 67 | * @param file 语音文件。 支持格式:['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm'] 文件 68 | * 大小限制:15MB 69 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 70 | */ 71 | String audioToText(File file, String user); 72 | 73 | /** 74 | * 语音转文字 75 | * 76 | * @param file 语音文件。 支持格式:['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm'] 文件 77 | * 大小限制:15MB 78 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 79 | * @param fileType 如果该参数不为空,那么file对象的ContentType将设置为该值。 80 | */ 81 | String audioToText(File file, String user, String fileType); 82 | 83 | /** 84 | * 文字转语音 85 | * 86 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一 87 | * @param messageId Dify 生成的文本消息 message-id 88 | */ 89 | AudioFile textToAudioByMessage(String user, String messageId); 90 | 91 | /** 92 | * 文字转语音 93 | * 94 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 95 | * @param text 语音生成内容。 96 | */ 97 | AudioFile textToAudio(String user, String text); 98 | 99 | /** 100 | * 文字转语音 101 | * 102 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 103 | * @param text 语音生成内容。如果没有传 message-id的话,则会使用这个字段的内容 104 | * @param messageId Dify 生成的文本消息,那么直接传递生成的message-id 即可,后台会通过 message_id 查找相应的内容直接合成语音信息。 105 | * 如果同时传 message_id 和 text,优先使用 message_id。 106 | */ 107 | AudioFile textToAudio(String user, String text, String messageId); 108 | 109 | /** 110 | * 发送同步接口请求 111 | * 112 | * @param route DifyRoute 113 | * @param query Query params 114 | * @param params Body params 115 | * @return String 116 | */ 117 | String requestBlocking(DifyRoute route, Map query, Map params); 118 | 119 | /** 120 | * 发送流式接口请求 121 | * 122 | * @param route DifyRoute 123 | * @param query Query params 124 | * @param params Body params 125 | * @return CompletableFuture 126 | */ 127 | CompletableFuture requestStreaming( 128 | DifyRoute route, 129 | Map query, 130 | Map params, 131 | Consumer consumer 132 | ); 133 | 134 | /** 135 | * 获取标注列表 136 | * @param page 页码 137 | * @param limit 每页数量 138 | */ 139 | DifyPage queryAnnotations(Integer page, Integer limit); 140 | 141 | /** 142 | * 创建标注 143 | * @param question 问题 144 | * @param answer 答案内容 145 | */ 146 | JSONObject createAnnotation(String question, String answer); 147 | 148 | /** 149 | * 更新标注 150 | * @param annotationId 标注ID 151 | * @param question 问题 152 | * @param answer 答案内容 153 | */ 154 | JSONObject updateAnnotation(String annotationId, String question, String answer); 155 | 156 | /** 157 | * 删除标注 158 | * @param annotationId 标注ID 159 | */ 160 | Boolean deleteAnnotation(String annotationId); 161 | 162 | /** 163 | * 标注回复初始设置 164 | * @param enable 动作,true 代表 'enable',false 代表 'disable' 165 | * @param embeddingModelProvider 指定的嵌入模型提供商, 必须先在系统内设定好接入的模型,对应的是provider字段 166 | * @param embeddingModel 指定的嵌入模型,对应的是model字段 167 | * @param scoreThreshold 相似度阈值,当相似度大于该阈值时,系统会自动回复,否则不回复 168 | */ 169 | JSONObject setAnnotationReply(Boolean enable, String embeddingModelProvider, String embeddingModel, Double scoreThreshold); 170 | 171 | /** 172 | * 查询标注回复初始设置任务状态 173 | * @param enable 动作,true 代表 'enable',false 代表 'disable',必须和标注回复初始设置接口的动作一致 174 | * @param jobId 任务 ID,从标注回复初始设置接口返回的 job_id 175 | */ 176 | JSONObject getAnnotationJobStatus(Boolean enable, String jobId); 177 | } 178 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/IAppChatClient.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app; 2 | 3 | import com.alibaba.fastjson2.JSONObject; 4 | import io.github.yuanbaobaoo.dify.app.params.ParamMessage; 5 | import io.github.yuanbaobaoo.dify.app.types.DifyChatResult; 6 | 7 | import java.util.List; 8 | import java.util.concurrent.CompletableFuture; 9 | import java.util.function.Consumer; 10 | 11 | /** 12 | * 适用于对话应用的客户端 13 | * ChatBot、Agent、ChatFlow 14 | */ 15 | public interface IAppChatClient extends IAppBaseClient { 16 | /** 17 | * 发送对话消息(同步接收) 18 | * 19 | * @param message ParamMessage 20 | */ 21 | DifyChatResult sendMessages(ParamMessage message); 22 | 23 | /** 24 | * 发送对话消息(流式接收) 25 | * 26 | * @param message ParamMessage 27 | * @param consumer Consumer 28 | */ 29 | CompletableFuture sendMessagesAsync(ParamMessage message, Consumer consumer); 30 | 31 | /** 32 | * 停止响应(仅支持流式模式) 33 | * 34 | * @param taskId 任务 ID,可在流式返回 Chunk 中获取 35 | * @param user 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 36 | */ 37 | Boolean stopResponse(String taskId, String user); 38 | 39 | /** 40 | * 获取下一轮建议问题列表 41 | * 42 | * @param messageId 消息ID 43 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 44 | */ 45 | List suggestedList(String messageId, String user); 46 | 47 | /** 48 | * 获取会话历史消息 49 | * 50 | * @param conversationId 会话ID 51 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 52 | * @param limit 一次请求返回多少条聊天记录,默认 20 条。 53 | * @param firstId 当前页第一条聊天记录的 ID,默认为空,表示获取第一页数据 54 | */ 55 | JSONObject history(String conversationId, String user, Integer limit, String firstId); 56 | 57 | /** 58 | * 获取会话列表 59 | * 60 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 61 | * @param lastId (选填)当前页最后面一条记录的 ID,默认 null 62 | * @param sortBy (选填)排序字段,默认 -updated_at(按更新时间倒序排列) 63 | * 可选值:created_at, -created_at, updated_at, -updated_at 64 | * 字段前面的符号代表顺序或倒序,-代表倒序 65 | * @param limit (选填)一次请求返回多少条记录,默认 20 条,最大 100 条,最小 1 条。 66 | */ 67 | JSONObject conversations(String user, Integer limit, String sortBy, String lastId); 68 | 69 | /** 70 | * 删除会话 71 | * 72 | * @param conversationId 会话 ID 73 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 74 | */ 75 | Boolean deleteConversation(String conversationId, String user); 76 | 77 | /** 78 | * 会话重命名 79 | * 80 | * @param conversationId 会话ID 81 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 82 | * @param name 会话名称 83 | */ 84 | JSONObject renameConversation(String conversationId, String user, String name); 85 | 86 | /** 87 | * 会话重命名 88 | * 89 | * @param conversationId 会话ID 90 | * @param user 用户标识,由开发者定义规则,需保证用户标识在应用内唯一。 91 | * @param name 会话名称 92 | * @param autoGenerate 是否自动生成标题 93 | */ 94 | JSONObject renameConversation(String conversationId, String user, String name, boolean autoGenerate); 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/IAppCompletion.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app; 2 | 3 | import io.github.yuanbaobaoo.dify.app.params.ParamMessage; 4 | import io.github.yuanbaobaoo.dify.app.types.DifyChatResult; 5 | 6 | import java.util.concurrent.CompletableFuture; 7 | import java.util.function.Consumer; 8 | 9 | /** 10 | * 适用于文本生成应用的客户端 11 | * ChatBot、Agent、ChatFlow 12 | */ 13 | public interface IAppCompletion extends IAppBaseClient { 14 | /** 15 | * 发送消息 16 | * 17 | * @param message ParamMessage 18 | */ 19 | DifyChatResult sendMessages(ParamMessage message); 20 | 21 | /** 22 | * 发送消息(流式) 23 | * 24 | * @param message ParamMessage 25 | * @param consumer Consumer 26 | */ 27 | CompletableFuture sendMessagesAsync(ParamMessage message, Consumer consumer); 28 | 29 | /** 30 | * 停止响应(仅支持流式模式) 31 | * 32 | * @param taskId 任务 ID,可在流式返回 Chunk 中获取 33 | * @param user 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致。 34 | */ 35 | Boolean stopGenerate(String taskId, String user); 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/IAppFlowClient.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app; 2 | 3 | import com.alibaba.fastjson2.JSONObject; 4 | import io.github.yuanbaobaoo.dify.app.params.ParamMessage; 5 | import io.github.yuanbaobaoo.dify.app.types.DifyWorkFlowResult; 6 | import io.github.yuanbaobaoo.dify.app.types.WorkflowStatus; 7 | 8 | import java.util.concurrent.CompletableFuture; 9 | import java.util.function.Consumer; 10 | 11 | /** 12 | * 适用于工作流应用的客户端 13 | * workflow 14 | */ 15 | public interface IAppFlowClient extends IAppBaseClient { 16 | /** 17 | * 执行工作流(流式模式) 18 | * 19 | * @param message ParamMessage 20 | * @param consumer Consumer 21 | */ 22 | CompletableFuture runStreaming(ParamMessage message, Consumer consumer); 23 | 24 | /** 25 | * 执行工作流(阻塞模式) 26 | * 27 | * @param message ParamMessage 28 | */ 29 | JSONObject runBlocking(ParamMessage message); 30 | 31 | /** 32 | * 获取工作流执行情况 33 | * 34 | * @param workFlowId 工作流ID 35 | */ 36 | JSONObject getWorkFlowStatus(String workFlowId); 37 | 38 | /** 39 | * 停止工作流(仅限流式模式) 40 | * 41 | * @param taskId 任务ID(流式返回chunk中获取) 42 | * @param user 用户标识,用于定义终端用户的身份,必须和发送消息接口传入 user 保持一致 43 | */ 44 | Boolean stopWorkFlow(String taskId, String user); 45 | 46 | /** 47 | * 获取工作流日志 48 | * 49 | * @param keyword 关键字 50 | * @param status 执行状态(succeeded/failed/stopped) 51 | * @param page 页码 52 | * @param limit 每页数量 53 | */ 54 | JSONObject getWorkFlowLog(String keyword, WorkflowStatus status, Integer page, Integer limit); 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/impl/AppBaseClientImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.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.types.*; 7 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 8 | import io.github.yuanbaobaoo.dify.app.IAppBaseClient; 9 | import io.github.yuanbaobaoo.dify.app.types.DifyFileResult; 10 | import io.github.yuanbaobaoo.dify.routes.AppRoutes; 11 | import io.github.yuanbaobaoo.dify.app.types.ResponseMode; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | import java.io.File; 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | import java.util.concurrent.CompletableFuture; 18 | import java.util.function.Consumer; 19 | 20 | import static java.awt.SystemColor.text; 21 | 22 | @Slf4j 23 | public class AppBaseClientImpl implements IAppBaseClient { 24 | protected final ApiConfig config; 25 | 26 | /** 27 | * constructor 28 | * 29 | * @param server Dify Server URL 30 | * @param apiKey The App Api Key 31 | */ 32 | public AppBaseClientImpl(String server, String apiKey) { 33 | config = ApiConfig.builder().server(server).apiKey(apiKey).build(); 34 | } 35 | 36 | @Override 37 | public SimpleHttpClient httpClient() { 38 | return SimpleHttpClient.get(config); 39 | } 40 | 41 | @Override 42 | public String getAppInfo() { 43 | return SimpleHttpClient.get(config).requestJson(AppRoutes.INFO, null, null); 44 | } 45 | 46 | @Override 47 | public String getAppParameters() { 48 | return SimpleHttpClient.get(config).requestJson(AppRoutes.PARAMETERS, null, null); 49 | } 50 | 51 | @Override 52 | public String getAppMetaInfo() { 53 | return SimpleHttpClient.get(config).requestJson(AppRoutes.META_INFO, null, null); 54 | } 55 | 56 | @Override 57 | public DifyFileResult uploadFile(File file, String user) { 58 | Map data = new HashMap<>(); 59 | data.put("file", file); 60 | data.put("user", user); 61 | 62 | String result = SimpleHttpClient.get(config).requestMultipart(AppRoutes.FILE_UPLOAD, null, data); 63 | return JSON.parseObject(result, DifyFileResult.class); 64 | } 65 | 66 | @Override 67 | public Boolean feedbacks(String messageId, String rating, String user, String content) { 68 | String result = SimpleHttpClient.get(config).requestJson( 69 | String.format("%s/%s/feedbacks", AppRoutes.MESSAGES.getUrl(), messageId), 70 | HttpMethod.POST, 71 | null, 72 | new HashMap<>() {{ 73 | put("rating", rating); 74 | put("user", user); 75 | put("content", content); 76 | }} 77 | ); 78 | 79 | JSONObject json = JSON.parseObject(result); 80 | return "success".equals(json.getString("result")); 81 | } 82 | 83 | @Override 84 | public String audioToText(File file, String user) { 85 | return audioToText(file, user, null); 86 | } 87 | 88 | @Override 89 | public String audioToText(File file, String user, String fileType) { 90 | Map data = new HashMap<>(); 91 | data.put("file", file); 92 | data.put("user", user); 93 | 94 | JSONObject result = JSON.parseObject( 95 | SimpleHttpClient.get(config).requestMultipart(AppRoutes.AUDIO_TO_TEXT, null, data, fileType) 96 | ); 97 | 98 | return result.getString("text"); 99 | } 100 | 101 | @Override 102 | public AudioFile textToAudioByMessage(String user, String messageId) { 103 | return textToAudio(user, null, messageId); 104 | } 105 | 106 | @Override 107 | public AudioFile textToAudio(String user, String text) { 108 | return textToAudio(user, text, null); 109 | } 110 | 111 | @Override 112 | public AudioFile textToAudio(String user, String text, String messageId) { 113 | Map data = new HashMap<>(); 114 | data.put("message_id", messageId); 115 | data.put("text", text); 116 | data.put("user", user); 117 | 118 | return SimpleHttpClient.get(config).requestFile(AppRoutes.TEXT_TO_AUDIO, null, data); 119 | } 120 | 121 | @Override 122 | public String requestBlocking(DifyRoute route, Map query, Map params) { 123 | // body请求对象中,强制覆盖 response_mode 124 | params.put("response_mode", ResponseMode.blocking); 125 | return SimpleHttpClient.get(config).requestJson(route, query, params); 126 | } 127 | 128 | @Override 129 | public CompletableFuture requestStreaming( 130 | DifyRoute route, 131 | Map query, 132 | Map params, 133 | Consumer consumer 134 | ) { 135 | // body请求对象中,强制覆盖 response_mode 136 | params.put("response_mode", ResponseMode.streaming); 137 | // 异步请求 138 | return SimpleHttpClient.get(config).requestJsonAsync(route, query, params, line -> { 139 | final String FLAG = "data:"; 140 | 141 | if (line.startsWith(FLAG)) { 142 | consumer.accept(line.substring(FLAG.length()).trim()); 143 | } 144 | }); 145 | } 146 | 147 | @Override 148 | public DifyPage queryAnnotations(Integer page, Integer limit) { 149 | Map params = new HashMap<>(); 150 | params.put("page", page); 151 | params.put("limit", limit); 152 | 153 | String result = SimpleHttpClient.get(config).requestJson(AppRoutes.ANNOTATION_GET, params); 154 | return JSON.parseObject(result, new TypeReference>() {}); 155 | } 156 | 157 | @Override 158 | public JSONObject createAnnotation(String question, String answer) { 159 | Map data = new HashMap<>(); 160 | data.put("question", question); 161 | data.put("answer", answer); 162 | 163 | String result = SimpleHttpClient.get(config).requestJson(AppRoutes.ANNOTATION_ADD, null, data); 164 | return JSON.parseObject(result); 165 | } 166 | 167 | @Override 168 | public JSONObject updateAnnotation(String annotationId, String question, String answer) { 169 | Map data = new HashMap<>(); 170 | data.put("question", question); 171 | data.put("answer", answer); 172 | 173 | DifyRoute route = AppRoutes.ANNOTATION_SET.format(Map.of( 174 | "annotationId", annotationId 175 | )); 176 | 177 | String result = SimpleHttpClient.get(config).requestJson(route, null, data); 178 | return JSON.parseObject(result); 179 | } 180 | 181 | @Override 182 | public Boolean deleteAnnotation(String annotationId) { 183 | DifyRoute route = AppRoutes.ANNOTATION_DEL.format(Map.of( 184 | "annotationId", annotationId 185 | )); 186 | 187 | String result = SimpleHttpClient.get(config).requestJson(route); 188 | JSONObject json = JSON.parseObject(result); 189 | 190 | return "success".equals(json.getString("result")); 191 | } 192 | 193 | @Override 194 | public JSONObject setAnnotationReply(Boolean enable, String embeddingModelProvider, String embeddingModel, Double scoreThreshold) { 195 | Map data = new HashMap<>(); 196 | data.put("embedding_model_provider", embeddingModelProvider); 197 | data.put("embedding_model", embeddingModel); 198 | data.put("score_threshold", scoreThreshold); 199 | 200 | DifyRoute route = AppRoutes.ANNOTATION_REPLY_SET.format(Map.of( 201 | "action", enable ? "enable" : "disable" 202 | )); 203 | 204 | String result = SimpleHttpClient.get(config).requestJson(route, null, data); 205 | return JSON.parseObject(result); 206 | } 207 | 208 | @Override 209 | public JSONObject getAnnotationJobStatus(Boolean enable, String jobId) { 210 | DifyRoute route = AppRoutes.ANNOTATION_REPLY_SET.format(Map.of( 211 | "action", enable ? "enable" : "disable", 212 | "jobId", jobId 213 | )); 214 | 215 | String result = SimpleHttpClient.get(config).requestJson(route); 216 | return JSON.parseObject(result); 217 | } 218 | 219 | } 220 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/impl/AppChatClientImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.impl; 2 | 3 | import com.alibaba.fastjson2.JSON; 4 | import com.alibaba.fastjson2.JSONObject; 5 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 6 | import io.github.yuanbaobaoo.dify.app.IAppChatClient; 7 | import io.github.yuanbaobaoo.dify.app.params.ParamMessage; 8 | import io.github.yuanbaobaoo.dify.app.types.DifyChatEvent; 9 | import io.github.yuanbaobaoo.dify.app.types.DifyChatResult; 10 | import io.github.yuanbaobaoo.dify.routes.AppRoutes; 11 | import io.github.yuanbaobaoo.dify.types.HttpMethod; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | import java.util.ArrayList; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.concurrent.CompletableFuture; 18 | import java.util.function.Consumer; 19 | 20 | @Slf4j 21 | public class AppChatClientImpl extends AppBaseClientImpl implements IAppChatClient { 22 | /** 23 | * constructor 24 | * 25 | * @param server Dify Server URL 26 | * @param apiKey The App Api Key 27 | */ 28 | public AppChatClientImpl(String server, String apiKey) { 29 | super(server, apiKey); 30 | } 31 | 32 | @Override 33 | public DifyChatResult sendMessages(ParamMessage message) { 34 | String result = requestBlocking(AppRoutes.CHAT_MESSAGES, null, message.toMap()); 35 | return DifyChatResult.builder().event(DifyChatEvent.message).payload(JSON.parseObject(result)).build(); 36 | } 37 | 38 | @Override 39 | public CompletableFuture sendMessagesAsync(ParamMessage message, Consumer consumer) { 40 | return requestStreaming(AppRoutes.CHAT_MESSAGES, null, message.toMap(), (line) -> { 41 | JSONObject json = JSON.parseObject(line); 42 | consumer.accept(DifyChatResult.builder().event(json.getString("event")).payload(json).build()); 43 | }); 44 | } 45 | 46 | @Override 47 | public Boolean stopResponse(String taskId, String user) { 48 | String result = SimpleHttpClient.get(config).requestJson( 49 | String.format("%s/%s/stop", AppRoutes.CHAT_MESSAGES.getUrl(), taskId), 50 | HttpMethod.POST, 51 | null, 52 | new HashMap<>() {{ 53 | put("user", user); 54 | }} 55 | ); 56 | 57 | JSONObject json = JSON.parseObject(result); 58 | return "success".equals(json.getString("result")); 59 | } 60 | 61 | @Override 62 | public List suggestedList(String messageId, String user) { 63 | String result = SimpleHttpClient.get(config).requestJson( 64 | String.format("%s/%s/suggested", AppRoutes.MESSAGES.getUrl(), messageId), 65 | HttpMethod.GET, 66 | new HashMap<>() {{ 67 | put("user", user); 68 | }}, 69 | null 70 | 71 | ); 72 | 73 | JSONObject json = JSON.parseObject(result); 74 | 75 | if ("success".equals(json.getString("result"))) { 76 | return json.getJSONArray("data").toList(String.class); 77 | } 78 | 79 | return new ArrayList<>(); 80 | } 81 | 82 | @Override 83 | public JSONObject history(String conversationId, String user, Integer limit, String firstId) { 84 | String result = SimpleHttpClient.get(config).requestJson(AppRoutes.MESSAGES, new HashMap<>() {{ 85 | put("conversation_id", conversationId); 86 | put("user", user); 87 | put("limit", limit); 88 | put("first_id", firstId); 89 | }}, null); 90 | 91 | if (result == null) { 92 | return null; 93 | } 94 | 95 | return JSON.parseObject(result); 96 | } 97 | 98 | @Override 99 | public JSONObject conversations(String user, Integer limit, String sortBy, String lastId) { 100 | String result = SimpleHttpClient.get(config).requestJson(AppRoutes.CHAT_CONVERSATIONS, new HashMap<>() {{ 101 | put("user", user); 102 | put("last_id", lastId); 103 | put("sort_by", sortBy); 104 | put("limit", limit); 105 | }}, null); 106 | 107 | if (result == null) { 108 | return null; 109 | } 110 | 111 | return JSON.parseObject(result); 112 | } 113 | 114 | @Override 115 | public Boolean deleteConversation(String conversationId, String user) { 116 | String result = SimpleHttpClient.get(config).requestJson( 117 | AppRoutes.CHAT_CONVERSATIONS.getUrl() + "/" + conversationId, 118 | HttpMethod.DELETE, 119 | null, 120 | new HashMap<>() {{ 121 | put("user", user); 122 | }} 123 | ); 124 | 125 | JSONObject json = JSON.parseObject(result); 126 | return "success".equals(json.getString("result")); 127 | } 128 | 129 | @Override 130 | public JSONObject renameConversation(String conversationId, String user, String name) { 131 | return renameConversation(conversationId, user, name, false); 132 | } 133 | 134 | @Override 135 | public JSONObject renameConversation(String conversationId, String user, String name, boolean autoGenerate) { 136 | String result = SimpleHttpClient.get(config).requestJson( 137 | String.format("%s/%s/name", AppRoutes.CHAT_CONVERSATIONS.getUrl(), conversationId), 138 | HttpMethod.POST, 139 | null, 140 | new HashMap<>() {{ 141 | put("user", user); 142 | put("name", name); 143 | put("auto_generate", autoGenerate); 144 | }} 145 | ); 146 | 147 | return JSON.parseObject(result); 148 | } 149 | 150 | } 151 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/impl/AppCompletionImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.impl; 2 | 3 | import com.alibaba.fastjson2.JSON; 4 | import com.alibaba.fastjson2.JSONObject; 5 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 6 | import io.github.yuanbaobaoo.dify.app.IAppCompletion; 7 | import io.github.yuanbaobaoo.dify.app.params.ParamMessage; 8 | import io.github.yuanbaobaoo.dify.app.types.DifyChatEvent; 9 | import io.github.yuanbaobaoo.dify.app.types.DifyChatResult; 10 | import io.github.yuanbaobaoo.dify.routes.AppRoutes; 11 | import io.github.yuanbaobaoo.dify.types.HttpMethod; 12 | import io.github.yuanbaobaoo.dify.types.DifyException; 13 | import lombok.extern.slf4j.Slf4j; 14 | 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | import java.util.concurrent.CompletableFuture; 18 | import java.util.function.Consumer; 19 | 20 | @Slf4j 21 | public class AppCompletionImpl extends AppBaseClientImpl implements IAppCompletion { 22 | /** 23 | * constructor 24 | * 25 | * @param server Dify Server URL 26 | * @param apiKey The App Api Key 27 | */ 28 | public AppCompletionImpl(String server, String apiKey) { 29 | super(server, apiKey); 30 | } 31 | 32 | @Override 33 | public DifyChatResult sendMessages(ParamMessage message) { 34 | formatMessage(message); 35 | String result = requestBlocking(AppRoutes.COMPLETION_MESSAGES, null, message.toMap()); 36 | return DifyChatResult.builder().event(DifyChatEvent.message).payload(JSON.parseObject(result)).build(); 37 | } 38 | 39 | @Override 40 | public CompletableFuture sendMessagesAsync(ParamMessage message, Consumer consumer) { 41 | formatMessage(message); 42 | 43 | return requestStreaming(AppRoutes.COMPLETION_MESSAGES, null, message.toMap(), (line) -> { 44 | JSONObject json = JSON.parseObject(line); 45 | consumer.accept(DifyChatResult.builder().event(json.getString("event")).payload(json).build()); 46 | }); 47 | } 48 | 49 | @Override 50 | public Boolean stopGenerate(String taskId, String user) { 51 | String result = SimpleHttpClient.get(config).requestJson( 52 | String.format("%s/%s/stop", AppRoutes.COMPLETION_MESSAGES.getUrl(), taskId), 53 | HttpMethod.POST, 54 | null, 55 | new HashMap<>() {{ 56 | put("user", user); 57 | }} 58 | ); 59 | 60 | JSONObject json = JSON.parseObject(result); 61 | return "success".equals(json.getString("result")); 62 | } 63 | 64 | /** 65 | * reset message params 66 | * @param message ParamMessage 67 | */ 68 | private void formatMessage(ParamMessage message) { 69 | if (message.getQuery() != null) { 70 | Map inputs = message.getInputs(); 71 | 72 | if (inputs == null) { 73 | inputs = new HashMap<>(); 74 | } 75 | 76 | if (!inputs.containsKey("query") || inputs.get("query") == null) { 77 | inputs.put("query", message.getQuery()); 78 | } 79 | 80 | message.setQuery(null); 81 | message.setInputs(inputs); 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/impl/AppFlowClientImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.impl; 2 | 3 | import com.alibaba.fastjson2.JSON; 4 | import com.alibaba.fastjson2.JSONObject; 5 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 6 | import io.github.yuanbaobaoo.dify.app.IAppFlowClient; 7 | import io.github.yuanbaobaoo.dify.app.params.ParamMessage; 8 | import io.github.yuanbaobaoo.dify.app.types.DifyWorkFlowResult; 9 | import io.github.yuanbaobaoo.dify.app.types.WorkflowStatus; 10 | import io.github.yuanbaobaoo.dify.routes.AppRoutes; 11 | import io.github.yuanbaobaoo.dify.types.HttpMethod; 12 | import io.github.yuanbaobaoo.dify.types.DifyException; 13 | import lombok.extern.slf4j.Slf4j; 14 | 15 | import java.util.HashMap; 16 | import java.util.concurrent.CompletableFuture; 17 | import java.util.function.Consumer; 18 | 19 | @Slf4j 20 | public class AppFlowClientImpl extends AppBaseClientImpl implements IAppFlowClient { 21 | /** 22 | * constructor 23 | * 24 | * @param server Dify Server URL 25 | * @param apiKey The App Api Key 26 | */ 27 | public AppFlowClientImpl(String server, String apiKey) { 28 | super(server, apiKey); 29 | } 30 | 31 | @Override 32 | public CompletableFuture runStreaming(ParamMessage message, Consumer consumer) { 33 | return requestStreaming(AppRoutes.WORKFLOW_RUN, null, message.toMap(), (line) -> { 34 | JSONObject json = JSON.parseObject(line); 35 | consumer.accept(DifyWorkFlowResult.builder().event(json.getString("event")).payload(json).build()); 36 | }); 37 | } 38 | 39 | @Override 40 | public JSONObject runBlocking(ParamMessage message) { 41 | String result = requestBlocking(AppRoutes.WORKFLOW_RUN, null, message.toMap()); 42 | return JSON.parseObject(result); 43 | } 44 | 45 | @Override 46 | public JSONObject getWorkFlowStatus(String workFlowId) { 47 | String result = SimpleHttpClient.get(config).requestJson( 48 | AppRoutes.WORKFLOW_RUN.getUrl() + "/" + workFlowId, 49 | HttpMethod.GET, 50 | null, 51 | null 52 | ); 53 | 54 | return JSON.parseObject(result); 55 | } 56 | 57 | @Override 58 | public Boolean stopWorkFlow(String taskId, String user) { 59 | String result = SimpleHttpClient.get(config).requestJson( 60 | String.format("%s/%s/stop", AppRoutes.WORKFLOW_TASK.getUrl(), taskId), 61 | HttpMethod.POST, 62 | null, 63 | new HashMap<>() {{ 64 | put("user", user); 65 | }} 66 | ); 67 | 68 | JSONObject json = JSON.parseObject(result); 69 | return "success".equals(json.getString("result")); 70 | } 71 | 72 | @Override 73 | public JSONObject getWorkFlowLog(String keyword, WorkflowStatus status, Integer page, Integer limit) { 74 | String result = SimpleHttpClient.get(config).requestJson(AppRoutes.WORKFLOW_LOGS, new HashMap<>() {{ 75 | put("keyword", keyword); 76 | put("status", status.name()); 77 | put("page", page); 78 | put("limit", limit); 79 | }}, null); 80 | 81 | if (result == null) { 82 | return null; 83 | } 84 | 85 | return JSON.parseObject(result); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/params/ParamFile.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.params; 2 | 3 | import com.alibaba.fastjson2.annotation.JSONField; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | @Getter 9 | @Setter 10 | @Builder 11 | public class ParamFile { 12 | /** 13 | * 文件类型 14 | */ 15 | private FileType type; 16 | 17 | /** 18 | * 传递方式 19 | */ 20 | @JSONField(name = "transfer_method", alternateNames = {"transferMethod"}) 21 | private TransferMethod transferMethod; 22 | 23 | /** 24 | * 图片地址(仅当传递方式为 remote_url 时) 25 | */ 26 | private String url; 27 | 28 | /** 29 | * 上传文件ID(仅当传递方式为 local_file 时) 30 | */ 31 | @JSONField(name = "upload_file_id", alternateNames = {"uploadFileId"}) 32 | private String uploadFileId; 33 | 34 | /** 35 | * document 具体类型包含:'TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB' 36 | * image 具体类型包含:'JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG' 37 | * audio 具体类型包含:'MP3', 'M4A', 'WAV', 'WEBM', 'AMR' 38 | * video 具体类型包含:'MP4', 'MOV', 'MPEG', 'MPGA' 39 | * custom 具体类型包含:其他文件类型 40 | */ 41 | public enum FileType { 42 | document, 43 | image, 44 | audio, 45 | video, 46 | custom 47 | } 48 | 49 | /** 50 | * 传递方式 51 | */ 52 | public enum TransferMethod { 53 | /** 54 | * 图片地址 55 | */ 56 | remote_url, 57 | 58 | /** 59 | * 上传文件 60 | */ 61 | local_file, 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/params/ParamMessage.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.params; 2 | 3 | import com.alibaba.fastjson2.annotation.JSONField; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | @Getter 13 | @Setter 14 | @Builder 15 | public class ParamMessage { 16 | /** 17 | * 用户输入/提问内容。(仅对话类型应用) 18 | */ 19 | private String query; 20 | 21 | /** 22 | * 允许传入 App 定义的各变量值 23 | * 如果变量是文件类型,请指定一个包含以下 files 中所述键的对象 24 | */ 25 | private Map inputs; 26 | 27 | /** 28 | * 用户标识 29 | */ 30 | private String user; 31 | 32 | /** 33 | * 会话 ID 34 | */ 35 | @JSONField(name = "conversation_id", alternateNames = {"conversationId"}) 36 | private String conversationId; 37 | 38 | /** 39 | * 文件列表,适用于传入文件结合文本理解并回答问题,仅当模型支持 Vision 能力时可用 40 | * 具体请看官方文档 41 | */ 42 | private List files; 43 | 44 | /** 45 | * 自动生成标题,默认 true。 46 | * 若设置为 false,则可通过调用会话重命名接口并设置 auto_generate 为 true 实现异步生成标题。 47 | */ 48 | @JSONField(name = "auto_generate_name", alternateNames = {"autoGenerateName"}) 49 | private Boolean autoGenerateName; 50 | 51 | /** 52 | * ToMap 53 | * 54 | * @return Map 55 | */ 56 | public Map toMap() { 57 | return new HashMap<>() {{ 58 | put("query", query); 59 | put("inputs", inputs == null ? new HashMap<>() : inputs); 60 | put("user", user); 61 | put("conversation_id", conversationId); 62 | put("files", files); 63 | put("auto_generate_name", autoGenerateName == null || autoGenerateName); 64 | }}; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/types/DifyChatEvent.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.types; 2 | 3 | /** 4 | * dify chat-message 消息事件 5 | * 来源:https://docs.dify.ai/ 6 | */ 7 | public class DifyChatEvent { 8 | public static final String message = "message"; 9 | public static final String nodeRetry = "node_retry"; 10 | public static final String messageFile = "message_file"; 11 | public static final String messageEnd = "message_end"; 12 | public static final String ttsMessage = "tts_message"; 13 | public static final String ttsMessageEnd = "tts_message_end"; 14 | public static final String messageReplace = "message_replace"; 15 | public static final String workflowStarted = "workflow_started"; 16 | public static final String nodeStarted = "node_started"; 17 | public static final String nodeFinished = "node_finished"; 18 | public static final String workflowFinished = "workflow_finished"; 19 | public static final String error = "error"; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/types/DifyChatResult.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.types; 2 | 3 | import com.alibaba.fastjson2.JSONObject; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | @Getter 9 | @Setter 10 | @Builder 11 | public class DifyChatResult { 12 | /** 13 | * 事件类型 14 | */ 15 | private String event; 16 | 17 | /** 18 | * 返回的消息内容 19 | */ 20 | private JSONObject payload; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/types/DifyFileResult.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.types; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | @Getter 7 | @Setter 8 | public class DifyFileResult { 9 | /** 10 | * ID 11 | */ 12 | private String id; 13 | 14 | /** 15 | * 文件名 16 | */ 17 | private String name; 18 | 19 | /** 20 | * 文件大小(byte) 21 | */ 22 | private Long size; 23 | 24 | /** 25 | * 文件后缀 26 | */ 27 | private String extension; 28 | 29 | /** 30 | * 文件 mime-type 31 | */ 32 | private String mimeType; 33 | 34 | /** 35 | * 上传人 ID 36 | */ 37 | private String createdBy; 38 | 39 | /** 40 | * 上传时间 41 | */ 42 | private Long createdAt; 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/types/DifyWorkFlowResult.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.types; 2 | 3 | import com.alibaba.fastjson2.JSONObject; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | @Getter 9 | @Setter 10 | @Builder 11 | public class DifyWorkFlowResult { 12 | /** 13 | * 事件类型 14 | */ 15 | private String event; 16 | 17 | /** 18 | * 返回的消息内容 19 | */ 20 | private JSONObject payload; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/types/ResponseMode.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.types; 2 | 3 | public enum ResponseMode { 4 | /** 5 | * 阻塞模式 6 | */ 7 | blocking, 8 | 9 | /** 10 | * 流式模式 11 | */ 12 | streaming, 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/app/types/WorkflowStatus.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.app.types; 2 | 3 | public enum WorkflowStatus { 4 | succeeded, 5 | failed, 6 | stopped 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/IDatasetClient.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset; 2 | 3 | import com.alibaba.fastjson2.JSONObject; 4 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 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.params.ParamUpdateDataset; 11 | import io.github.yuanbaobaoo.dify.dataset.types.*; 12 | import io.github.yuanbaobaoo.dify.types.DifyPage; 13 | 14 | import java.io.File; 15 | import java.util.List; 16 | 17 | public interface IDatasetClient { 18 | /** 19 | * 获取一个SimpleHttpClient对象 20 | */ 21 | SimpleHttpClient httpClient(); 22 | 23 | /** 24 | * 快捷构建一个Dataset对象 25 | * @param datasetId 知识库ID 26 | */ 27 | DatasetHero ofDataset(String datasetId); 28 | 29 | /** 30 | * 快捷创建一个Document对象 31 | * @param documentId 文档ID 32 | */ 33 | DocumentHero ofDocument(String datasetId, String documentId); 34 | 35 | /** 36 | * 获取嵌入模型列表 37 | */ 38 | List selectTextEmbedding(); 39 | 40 | /** 41 | * 查询知识库列表 42 | * @param page 页码 43 | * @param limit 返回条数,默认 20,范围 1-100 44 | */ 45 | DifyPage list(int page, int limit); 46 | 47 | /** 48 | * Create an Empty Knowledge Base. 创建空知识库 49 | * @param data ParamDataset 50 | */ 51 | DatasetHero create(ParamDataset data); 52 | 53 | /** 54 | * 查看知识库详情 55 | * @param datasetId 知识库ID 56 | */ 57 | DatasetHero get(String datasetId); 58 | 59 | /** 60 | * 修改知识库详情 61 | * @param datasetId 知识库ID 62 | * @param data ParamUpdateDataset 63 | */ 64 | DatasetHero update(String datasetId, ParamUpdateDataset data); 65 | 66 | /** 67 | * 删除知识库 68 | * @param datasetId 知识库ID 69 | */ 70 | void delete(String datasetId); 71 | 72 | /** 73 | * 通过文本创建文档 74 | * @param datasetId 知识库ID 75 | * @param doc ParamDocument 76 | */ 77 | DocumentResult insertDocByText(String datasetId, ParamDocument doc) ; 78 | 79 | /** 80 | * 通过文本创建文档 81 | * @param datasetId 知识库ID 82 | * @param doc ParamDocument 83 | * @param retrievalModel RetrievalModel 84 | * @param embeddingModel Embedding 模型名称 85 | * @param embeddingModelProvider Embedding 模型供应商 86 | */ 87 | DocumentResult insertDocByText( 88 | String datasetId, 89 | ParamDocument doc, 90 | RetrievalModel retrievalModel, 91 | String embeddingModel, 92 | String embeddingModelProvider 93 | ); 94 | 95 | /** 96 | * 通过文件创建文档 97 | * @param datasetId 知识库ID 98 | * @param file File 99 | * @param data ParamDocument 100 | */ 101 | DocumentResult insertDocByFile(String datasetId, File file, ParamDocument data) ; 102 | 103 | /** 104 | * 通过文件创建文档 105 | * @param datasetId 知识库ID 106 | * @param file File 107 | * @param data ParamDocument 108 | * @param retrievalModel retrievalModel 109 | * @param embeddingModel Embedding 模型名称 110 | * @param embeddingModelProvider Embedding 模型供应商 111 | */ 112 | DocumentResult insertDocByFile( 113 | String datasetId, 114 | File file, 115 | ParamDocument data, 116 | RetrievalModel retrievalModel, 117 | String embeddingModel, 118 | String embeddingModelProvider 119 | ); 120 | 121 | /** 122 | * 获取文档嵌入状态(进度) 123 | * @param datasetId 知识库ID 124 | * @param batch 上传文档的批次号 125 | */ 126 | List queryBatchStatus(String datasetId, String batch); 127 | 128 | /** 129 | * 获取知识库文档列表 130 | * @param datasetId 知识库ID 131 | */ 132 | DifyPage documents(String datasetId) ; 133 | 134 | /** 135 | * 获取知识库文档列表 136 | * @param datasetId 知识库ID 137 | * @param page 页码 138 | * @param limit 返回条数 139 | * @param keyword 搜索关键词,可选,目前仅搜索文档名称 140 | */ 141 | DifyPage documents(String datasetId, Integer page, Integer limit, String keyword) ; 142 | 143 | /** 144 | * 检索知识库 145 | * @param datasetId 知识库ID 146 | * @param query 检索关键词 147 | * @param retrievalModel RetrievalModel 148 | */ 149 | RetrieveResult retrieve(String datasetId, String query, RetrievalModel retrievalModel) ; 150 | 151 | 152 | /** 153 | * 通过文本更新文档 154 | * @param datasetId 知识库ID 155 | * @param documentId 文档ID 156 | * @param data ParamDocument 157 | */ 158 | DocumentResult updateDocByText(String datasetId, String documentId, ParamDocument data); 159 | 160 | /** 161 | * 通过文件更新文档 162 | * @param datasetId 知识库ID 163 | * @param documentId 文档ID 164 | * @param file File 165 | * @param rule ProcessRule 166 | */ 167 | DocumentResult updateDocByFile(String datasetId, String documentId, File file, ProcessRule rule); 168 | 169 | /** 170 | * 通过文件更新文档 171 | * @param datasetId 知识库ID 172 | * @param documentId 文档ID 173 | * @param name 文档名称 174 | * @param file 需要上传的文件 175 | * @param rule 处理规则 176 | */ 177 | DocumentResult updateDocByFile(String datasetId, String documentId, String name, File file, ProcessRule rule); 178 | 179 | /** 180 | * 删除文档 181 | * @param datasetId 知识库ID 182 | * @param documentId 文档ID 183 | */ 184 | Boolean deleteDocument(String datasetId, String documentId); 185 | 186 | /** 187 | * 获取文档文件信息 188 | * @param datasetId 知识库ID 189 | * @param documentId 文档ID 190 | */ 191 | DocFileInfo queryFileInfo(String datasetId, String documentId); 192 | 193 | /** 194 | * 获取文档分段 195 | * @param datasetId 知识库ID 196 | * @param documentId 文档ID 197 | */ 198 | SegmentResult querySegments(String datasetId, String documentId); 199 | 200 | /** 201 | * 获取文档分段 202 | * @param datasetId 知识库ID 203 | * @param documentId 文档ID 204 | * @param keyword 关键词 205 | */ 206 | SegmentResult querySegments(String datasetId, String documentId, String keyword); 207 | 208 | /** 209 | * 获取文档分段 210 | * @param datasetId 知识库ID 211 | * @param documentId 文档ID 212 | * @param keyword 关键词 213 | * @param status 搜索状态 214 | */ 215 | SegmentResult querySegments(String datasetId, String documentId, String keyword, String status); 216 | 217 | /** 218 | * 插入文档分段 219 | * @param datasetId 知识库ID 220 | * @param documentId 文档ID 221 | * @param segments List 222 | * content 文本内容/问题内容 223 | * keywords 关键字,非必填 224 | * answer 答案内容,非必填,如果知识库的模式为 Q&A 模式则传值 225 | */ 226 | SegmentResult insertSegment(String datasetId, String documentId, List segments); 227 | 228 | /** 229 | * 删除文档分段 230 | * @param datasetId 知识库ID 231 | * @param documentId 文档ID 232 | * @param segmentId 分段ID 233 | */ 234 | Boolean deleteSegment(String datasetId, String documentId, String segmentId); 235 | 236 | /** 237 | * 更新文档分段 238 | * @param datasetId 知识库ID 239 | * @param documentId 文档ID 240 | * @param segmentId 分段ID 241 | * @param content 文本内容/问题内容 242 | * @param regenerate 是否重新生成向量 243 | */ 244 | SegmentResult updateSegment(String datasetId, String documentId, String segmentId, String content, boolean regenerate); 245 | 246 | /** 247 | * 更新文档分段 248 | * @param datasetId 知识库ID 249 | * @param documentId 文档ID 250 | * @param segment Segment 251 | * @param regenerate 是否重新生成子分段 252 | */ 253 | SegmentResult updateSegment(String datasetId, String documentId, Segment segment, boolean regenerate); 254 | 255 | /** 256 | * 新增文档子分段 257 | * @param datasetId 知识库 ID 258 | * @param documentId 文档 ID 259 | * @param segmentId 分段 ID 260 | * @param content 子分段内容 261 | */ 262 | SegmentChildChunk insertSegmentChildChunks(String datasetId, String documentId, String segmentId, String content); 263 | 264 | /** 265 | * 查询文档子分段 266 | * @param datasetId 知识库 ID 267 | * @param documentId 文档 ID 268 | * @param segmentId 分段 ID 269 | */ 270 | DifyPage querySegmentChildChunks( 271 | String datasetId, 272 | String documentId, 273 | String segmentId, 274 | Integer page, 275 | Integer limit 276 | ); 277 | 278 | /** 279 | * 查询文档子分段 280 | * @param datasetId 知识库 ID 281 | * @param documentId 文档 ID 282 | * @param segmentId 分段 ID 283 | * @param page 页码(选填,默认1) 284 | * @param limit 每页数量(选填,默认20,最大100) 285 | * @param keyword 搜索关键词(选填) 286 | */ 287 | DifyPage querySegmentChildChunks( 288 | String datasetId, 289 | String documentId, 290 | String segmentId, 291 | Integer page, 292 | Integer limit, 293 | String keyword 294 | ); 295 | 296 | /** 297 | * TODO 删除文档子分段 298 | * @param datasetId 知识库 ID 299 | * @param documentId 文档 ID 300 | * @param segmentId 分段 ID 301 | * @param childChunkId 子分段 ID 302 | */ 303 | Boolean deleteSegmentChildChunks(String datasetId, String documentId, String segmentId, String childChunkId); 304 | 305 | /** 306 | * TODO 更新文档子分段 307 | * @param datasetId 知识库 ID 308 | * @param documentId 文档 ID 309 | * @param segmentId 分段 ID 310 | * @param childChunkId 子分段 ID 311 | * @param content 子分段内容 312 | */ 313 | SegmentChildChunk updateSegmentChildChunks( 314 | String datasetId, 315 | String documentId, 316 | String segmentId, 317 | String childChunkId, 318 | String content 319 | ); 320 | 321 | } 322 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/IKnowledgeService.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset; 2 | 3 | import io.github.yuanbaobaoo.dify.dataset.types.external.KnowledgeArgs; 4 | import io.github.yuanbaobaoo.dify.dataset.types.external.KnowledgeResult; 5 | 6 | public interface IKnowledgeService { 7 | /** 8 | * 知识检索 9 | * @param apiKey Dify传递的API KEY 10 | * @param args KnowledgeArgs 11 | */ 12 | KnowledgeResult retrieval(String apiKey, KnowledgeArgs args); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/entity/Dataset.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.entity; 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.types.DatasetConsts; 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 Dataset { 16 | private String id; 17 | private String name; 18 | private String description; 19 | private String provider; 20 | private String permission; 21 | private String dataSourceType; 22 | private DatasetConsts.IndexingTechnique indexingTechnique; 23 | private Integer appCount; 24 | private Long documentCount; 25 | private Long wordCount; 26 | private String createdBy; 27 | private Long createdAt; 28 | private String updatedBy; 29 | private Long updatedAt; 30 | private String embeddingModel; 31 | private String embeddingModelProvider; 32 | private String embeddingAvailable; 33 | private List tags; 34 | private Object docForm; 35 | private JSONObject retrievalModelDict; 36 | private JSONObject externalKnowledgeInfo; 37 | private JSONObject externalRetrievalModel; 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/entity/DocFileInfo.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.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 DocFileInfo { 12 | private String id; 13 | private String name; 14 | private Long size; 15 | private String extension; 16 | private String url; 17 | private String downloadUrl; 18 | private String mimeType; 19 | private String createdBy; 20 | private Long createdAt; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/entity/Document.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.entity; 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.types.DatasetConsts; 7 | import lombok.Getter; 8 | import lombok.Setter; 9 | 10 | @Getter 11 | @Setter 12 | @JSONType(naming = PropertyNamingStrategy.SnakeCase) 13 | public class Document { 14 | private String id; 15 | private Integer position; 16 | private String dataSourceType; 17 | private JSONObject dataSourceInfo; 18 | private JSONObject dataSourceDetailDict; 19 | private String datasetProcessRuleId; 20 | private String name; 21 | private String createdFrom; 22 | private String createdBy; 23 | private Long createdAt; 24 | private String tokens; 25 | private String indexingStatus; 26 | private String error; 27 | private Boolean enabled; 28 | private Long disabledAt; 29 | private String disabledBy; 30 | private Boolean archived; 31 | private String displayStatus; 32 | private Long wordCount; 33 | private Long hitCount; 34 | private DatasetConsts.DocForm docForm; 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/entity/Segment.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.entity; 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 | import java.util.List; 10 | 11 | @Getter 12 | @Setter 13 | @Builder 14 | @JSONType(naming = PropertyNamingStrategy.SnakeCase) 15 | public class Segment { 16 | private String id; 17 | private Integer position; 18 | private String documentId; 19 | private String content; 20 | private String answer; 21 | private Long wordCount; 22 | private Long tokens; 23 | private List keywords; 24 | private String indexNodeId; 25 | private String indexNodeHash; 26 | private Long hitCount; 27 | private Boolean enabled; 28 | private Long disabledAt; 29 | private String disabledBy; 30 | private String status; 31 | private String createdBy; 32 | private Long createdAt; 33 | private Long indexingAt; 34 | private Long completedAt; 35 | private String error; 36 | private Long stopped_at; 37 | private Document document; 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/entity/SegmentChildChunk.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.entity; 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 | import java.util.List; 10 | 11 | @Getter 12 | @Setter 13 | @Builder 14 | @JSONType(naming = PropertyNamingStrategy.SnakeCase) 15 | public class SegmentChildChunk { 16 | private String id; 17 | private String segmentId; 18 | private String content; 19 | private Long wordCount; 20 | private Long tokens; 21 | private String indexNodeId; 22 | private String indexNodeHash; 23 | private String status; 24 | private String createdBy; 25 | private Long createdAt; 26 | private Long indexingAt; 27 | private Long completedAt; 28 | private String error; 29 | private Long stopped_at; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/heros/DatasetHero.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.heros; 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.dataset.params.ParamUpdateDataset; 7 | import io.github.yuanbaobaoo.dify.types.ApiConfig; 8 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 9 | import io.github.yuanbaobaoo.dify.routes.DatasetRoutes; 10 | import io.github.yuanbaobaoo.dify.dataset.entity.Dataset; 11 | import io.github.yuanbaobaoo.dify.dataset.entity.Document; 12 | import io.github.yuanbaobaoo.dify.dataset.types.RetrieveResult; 13 | import io.github.yuanbaobaoo.dify.dataset.params.ParamDocument; 14 | import io.github.yuanbaobaoo.dify.dataset.types.BatchStatus; 15 | import io.github.yuanbaobaoo.dify.dataset.types.DocumentResult; 16 | import io.github.yuanbaobaoo.dify.dataset.types.RetrievalModel; 17 | import io.github.yuanbaobaoo.dify.types.DifyPage; 18 | import io.github.yuanbaobaoo.dify.types.DifyRoute; 19 | 20 | import java.io.File; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | public class DatasetHero extends Dataset { 26 | private final ApiConfig config; 27 | 28 | /** 29 | * new DatasetHero 30 | * 31 | * @param id Dataset id 32 | * @param config DifyConfig 33 | */ 34 | public static DatasetHero of(String id, ApiConfig config) { 35 | return new DatasetHero(config.getServer(), config.getApiKey(), id); 36 | } 37 | 38 | /** 39 | * new DatasetHero 40 | * 41 | * @param dataset Dataset 42 | * @param config DifyConfig 43 | */ 44 | public static DatasetHero of(Dataset dataset, ApiConfig config) { 45 | return new DatasetHero(config.getServer(), config.getApiKey(), dataset); 46 | } 47 | 48 | /** 49 | * Constructor 50 | * 51 | * @param server Dify Server Address 52 | * @param apiKey Api Key 53 | * @param id Dataset id 54 | */ 55 | private DatasetHero(String server, String apiKey, String id) { 56 | this.config = ApiConfig.builder().server(server).apiKey(apiKey).build(); 57 | this.setId(id); 58 | } 59 | 60 | /** 61 | * Constructor 62 | * 63 | * @param server Dify Server Address 64 | * @param apiKey Api Key 65 | * @param dataset Dataset 66 | */ 67 | private DatasetHero(String server, String apiKey, Dataset dataset) { 68 | this.config = ApiConfig.builder().server(server).apiKey(apiKey).build(); 69 | this.resetDataset(dataset); 70 | } 71 | 72 | /** 73 | * 快捷创建一个Document对象 74 | * 75 | * @param documentId 文档ID 76 | */ 77 | public DocumentHero ofDocument(String documentId) { 78 | return DocumentHero.of(this.getId(), documentId, this.config); 79 | } 80 | 81 | /** 82 | * 更新知识库 83 | * @param data ParamUpdateDataset 84 | */ 85 | public DatasetHero update(ParamUpdateDataset data) { 86 | DifyRoute route = DatasetRoutes.DATASETS_UPDATE.format( 87 | Map.of("datasetId", getId()) 88 | ); 89 | 90 | String result = SimpleHttpClient.get(config).requestJson(route, null, data); 91 | Dataset dataset = JSON.parseObject(result, Dataset.class); 92 | 93 | this.resetDataset(dataset); 94 | return this; 95 | } 96 | 97 | /** 98 | * 删除知识库 99 | */ 100 | public void delete() { 101 | SimpleHttpClient.get(config).requestJson(DatasetRoutes.DATASETS_DELETE.format( 102 | Map.of("datasetId", getId()) 103 | )); 104 | } 105 | 106 | /** 107 | * 通过文本创建文档 108 | * 109 | * @param doc ParamDocument 110 | */ 111 | public DocumentResult insertText(ParamDocument doc) { 112 | return insertText(doc, null, null, null); 113 | } 114 | 115 | /** 116 | * 通过文本创建文档 117 | * 118 | * @param doc ParamDocument 119 | * @param retrievalModel RetrievalModel 120 | * @param embeddingModel Embedding 模型名称 121 | * @param embeddingModelProvider Embedding 模型供应商 122 | */ 123 | public DocumentResult insertText(ParamDocument doc, RetrievalModel retrievalModel, String embeddingModel, String embeddingModelProvider) { 124 | Map params = doc.toMap(); 125 | params.put("retrieval_model", retrievalModel); 126 | params.put("embedding_model", embeddingModel); 127 | params.put("embedding_model_provider", embeddingModelProvider); 128 | 129 | DifyRoute route = DatasetRoutes.DATASETS_CREATE_DOC_TEXT.format(new HashMap<>() {{ 130 | put("datasetId", getId()); 131 | }}); 132 | 133 | String result = SimpleHttpClient.get(config).requestJson(route, null, params); 134 | return DocumentResult.parse(this.getId(), result, config); 135 | } 136 | 137 | /** 138 | * 通过文件创建文档 139 | * 140 | * @param file File 141 | * @param data ParamDocument 142 | */ 143 | public DocumentResult insertFile(File file, ParamDocument data) { 144 | return insertFile(file, data, null, null, null); 145 | } 146 | 147 | /** 148 | * 通过文件创建文档 149 | * 150 | * @param file File 151 | * @param data ParamDocument 152 | * @param retrievalModel retrievalModel 153 | * @param embeddingModel Embedding 模型名称 154 | * @param embeddingModelProvider Embedding 模型供应商 155 | */ 156 | public DocumentResult insertFile(File file, ParamDocument data, RetrievalModel retrievalModel, String embeddingModel, String embeddingModelProvider) { 157 | Map params = new HashMap<>(); 158 | params.put("file", file); 159 | params.put("data", data.toMap()); 160 | params.put("retrieval_model", retrievalModel); 161 | params.put("embedding_model", embeddingModel); 162 | params.put("embedding_model_provider", embeddingModelProvider); 163 | 164 | DifyRoute route = DatasetRoutes.DATASETS_CREATE_DOC_FILE.format(new HashMap<>() {{ 165 | put("datasetId", getId()); 166 | }}); 167 | 168 | String result = SimpleHttpClient.get(config).requestMultipart(route, null, params); 169 | return DocumentResult.parse(this.getId(), result, config); 170 | } 171 | 172 | /** 173 | * 获取文档嵌入状态(进度) 174 | * 175 | * @param batch 上传文档的批次号 176 | */ 177 | public List queryBatchStatus(String batch) { 178 | DifyRoute route = DatasetRoutes.DATASETS_INDEXING_STATUS.format(new HashMap<>() {{ 179 | put("datasetId", getId()); 180 | put("batch", batch); 181 | }}); 182 | 183 | JSONObject result = JSON.parseObject( 184 | SimpleHttpClient.get(config).requestJson(route) 185 | ); 186 | 187 | return result.getJSONArray("data").toJavaList(BatchStatus.class); 188 | } 189 | 190 | /** 191 | * 获取知识库文档列表 192 | */ 193 | public DifyPage documents() { 194 | return documents(null, null, null); 195 | } 196 | 197 | /** 198 | * 获取知识库文档列表 199 | * 200 | * @param page 页码 201 | * @param limit 返回条数 202 | * @param keyword 搜索关键词,可选,目前仅搜索文档名称 203 | */ 204 | public DifyPage documents(Integer page, Integer limit, String keyword) { 205 | DifyRoute route = DatasetRoutes.DATASETS_DOCS.format(new HashMap<>() {{ 206 | put("datasetId", getId()); 207 | }}); 208 | 209 | Map query = new HashMap<>() {{ 210 | put("page", page); 211 | put("limit", limit); 212 | put("keyword", keyword); 213 | }}; 214 | 215 | String result = SimpleHttpClient.get(config).requestJson(route, query, null); 216 | return JSON.parseObject(result, new TypeReference>() { 217 | }); 218 | } 219 | 220 | /** 221 | * 检索知识库 222 | * 223 | * @param query 检索关键词 224 | */ 225 | public RetrieveResult retrieve(String query) { 226 | return retrieve(query, null); 227 | } 228 | 229 | /** 230 | * 检索知识库 231 | * 232 | * @param query 检索关键词 233 | * @param retrievalModel RetrievalModel 234 | */ 235 | public RetrieveResult retrieve(String query, RetrievalModel retrievalModel) { 236 | String result = SimpleHttpClient.get(config).requestJson(DatasetRoutes.DATASETS_RETRIEVE.format(new HashMap<>() {{ 237 | put("datasetId", getId()); 238 | }}), null, new HashMap<>() {{ 239 | put("query", query); 240 | put("retrieval_model", retrievalModel); 241 | }}); 242 | 243 | return JSON.parseObject(result, RetrieveResult.class); 244 | } 245 | 246 | /** 247 | * reset dataset field 248 | * @param dataset Dataset 249 | */ 250 | private void resetDataset(Dataset dataset) { 251 | this.setId(dataset.getId()); 252 | this.setName(dataset.getName()); 253 | this.setDescription(dataset.getDescription()); 254 | this.setProvider(dataset.getProvider()); 255 | this.setPermission(dataset.getPermission()); 256 | this.setDataSourceType(dataset.getDataSourceType()); 257 | this.setIndexingTechnique(dataset.getIndexingTechnique()); 258 | this.setAppCount(dataset.getAppCount()); 259 | this.setDocumentCount(dataset.getDocumentCount()); 260 | this.setWordCount(dataset.getWordCount()); 261 | this.setCreatedBy(dataset.getCreatedBy()); 262 | this.setCreatedAt(dataset.getCreatedAt()); 263 | this.setUpdatedBy(dataset.getUpdatedBy()); 264 | this.setUpdatedAt(dataset.getUpdatedAt()); 265 | this.setEmbeddingModel(dataset.getEmbeddingModel()); 266 | this.setEmbeddingModelProvider(dataset.getEmbeddingModelProvider()); 267 | this.setEmbeddingAvailable(dataset.getEmbeddingAvailable()); 268 | this.setTags(dataset.getTags()); 269 | this.setDocForm(dataset.getDocForm()); 270 | this.setRetrievalModelDict(dataset.getRetrievalModelDict()); 271 | this.setExternalKnowledgeInfo(dataset.getExternalKnowledgeInfo()); 272 | this.setExternalRetrievalModel(dataset.getExternalRetrievalModel()); 273 | } 274 | 275 | } 276 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/heros/DocumentHero.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.heros; 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.dataset.entity.SegmentChildChunk; 7 | import io.github.yuanbaobaoo.dify.types.ApiConfig; 8 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 9 | import io.github.yuanbaobaoo.dify.routes.DatasetRoutes; 10 | import io.github.yuanbaobaoo.dify.dataset.entity.DocFileInfo; 11 | import io.github.yuanbaobaoo.dify.dataset.entity.Document; 12 | import io.github.yuanbaobaoo.dify.dataset.entity.Segment; 13 | import io.github.yuanbaobaoo.dify.dataset.types.SegmentResult; 14 | import io.github.yuanbaobaoo.dify.dataset.params.ParamDocument; 15 | import io.github.yuanbaobaoo.dify.dataset.types.DocumentResult; 16 | import io.github.yuanbaobaoo.dify.dataset.types.ProcessRule; 17 | import io.github.yuanbaobaoo.dify.types.DifyPage; 18 | import io.github.yuanbaobaoo.dify.types.DifyRoute; 19 | 20 | import java.io.File; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | 24 | public class DocumentHero extends Document { 25 | private final String datasetId; 26 | private final ApiConfig config; 27 | 28 | /** 29 | * new DocumentHero 30 | * @param datasetId dataset id 31 | * @param id document id 32 | * @param config DifyConfig 33 | */ 34 | public static DocumentHero of(String datasetId, String id, ApiConfig config) { 35 | return new DocumentHero(datasetId, id, config); 36 | } 37 | 38 | /**new DocumentHero 39 | * 40 | * @param datasetId dataset id 41 | * @param doc Document 42 | * @param config DifyConfig 43 | */ 44 | public static DocumentHero of(String datasetId, Document doc, ApiConfig config) { 45 | return new DocumentHero(datasetId, doc, config); 46 | } 47 | 48 | /** 49 | * Constructor 50 | * @param datasetId Dataset Id 51 | * @param id Document id 52 | * @param config DifyConfig 53 | */ 54 | private DocumentHero(String datasetId, String id, ApiConfig config) { 55 | this.config = config; 56 | this.datasetId = datasetId; 57 | 58 | this.setId(id); 59 | } 60 | 61 | /** 62 | * Constructor 63 | * @param datasetId Dataset Id 64 | * @param doc Document 65 | * @param config DifyConfig 66 | */ 67 | private DocumentHero(String datasetId, Document doc, ApiConfig config) { 68 | this.config = config; 69 | this.datasetId = datasetId; 70 | 71 | this.setId(doc.getId()); 72 | this.setName(doc.getName()); 73 | this.setDocForm(doc.getDocForm()); 74 | this.setDatasetProcessRuleId(doc.getDatasetProcessRuleId()); 75 | this.setDataSourceType(doc.getDataSourceType()); 76 | this.setDataSourceInfo(doc.getDataSourceInfo()); 77 | this.setDataSourceDetailDict(doc.getDataSourceDetailDict()); 78 | this.setCreatedAt(doc.getCreatedAt()); 79 | this.setCreatedBy(doc.getCreatedBy()); 80 | this.setDisabledAt(doc.getDisabledAt()); 81 | this.setDisabledBy(doc.getDisabledBy()); 82 | this.setEnabled(doc.getEnabled()); 83 | this.setError(doc.getError()); 84 | this.setHitCount(doc.getHitCount()); 85 | this.setWordCount(doc.getWordCount()); 86 | this.setDisplayStatus(doc.getDisplayStatus()); 87 | this.setIndexingStatus(doc.getIndexingStatus()); 88 | this.setTokens(doc.getTokens()); 89 | this.setArchived(doc.getArchived()); 90 | this.setCreatedFrom(doc.getCreatedFrom()); 91 | this.setPosition(doc.getPosition()); 92 | } 93 | 94 | /** 95 | * 通过文本更新文档 96 | */ 97 | public DocumentResult updateByText(ParamDocument data) { 98 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_UPDATE_TEXT.format(new HashMap<>() {{ 99 | put("datasetId", datasetId); 100 | put("documentId", getId()); 101 | }}); 102 | 103 | String result = SimpleHttpClient.get(config).requestJson(route, null, data); 104 | return DocumentResult.parse(datasetId, result, config); 105 | } 106 | 107 | /** 108 | * 通过文件更新文档 109 | * @param file File 110 | * @param rule ProcessRule 111 | */ 112 | public DocumentResult updateByFile(File file, ProcessRule rule) { 113 | return updateByFile(null, file, rule); 114 | } 115 | 116 | /** 117 | * 通过文件更新文档 118 | * 119 | * @param name 文档名称 120 | * @param file 需要上传的文件 121 | * @param rule 处理规则 122 | */ 123 | public DocumentResult updateByFile(String name, File file, ProcessRule rule) { 124 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_UPDATE_FILE.format(new HashMap<>() {{ 125 | put("datasetId", datasetId); 126 | put("documentId", getId()); 127 | }}); 128 | 129 | String result = SimpleHttpClient.get(config).requestMultipart(route, null, new HashMap<>() {{ 130 | put("name", name); 131 | put("file", file); 132 | put("process_rule", rule); 133 | }}); 134 | 135 | return DocumentResult.parse(datasetId, result, config); 136 | } 137 | 138 | /** 139 | * 删除文档 140 | */ 141 | public Boolean delete() { 142 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_DELETE.format(new HashMap<>() {{ 143 | put("datasetId", datasetId); 144 | put("documentId", getId()); 145 | }}); 146 | 147 | String result = SimpleHttpClient.get(config).requestJson(route); 148 | JSONObject json = JSON.parseObject(result); 149 | 150 | return "success".equals(json.getString("result")); 151 | } 152 | 153 | /** 154 | * 获取上传文件 155 | */ 156 | public DocFileInfo queryFileInfo() { 157 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_FILE_INFO.format(new HashMap<>() {{ 158 | put("datasetId", datasetId); 159 | put("documentId", getId()); 160 | }}); 161 | 162 | String result = SimpleHttpClient.get(config).requestJson(route); 163 | return JSON.parseObject(result, DocFileInfo.class); 164 | } 165 | 166 | /** 167 | * 查询文档分段 168 | */ 169 | public SegmentResult querySegments() { 170 | return querySegments(null, null); 171 | } 172 | 173 | /** 174 | * 查询文档分段 175 | * @param keyword 搜索关键词 176 | */ 177 | public SegmentResult querySegments(String keyword) { 178 | return querySegments(keyword, null); 179 | } 180 | 181 | /** 182 | * 查询文档分段 183 | * @param keyword 搜索关键词 184 | * @param status 搜索状态 185 | */ 186 | public SegmentResult querySegments(String keyword, String status) { 187 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS.format(new HashMap<>() {{ 188 | put("datasetId", datasetId); 189 | put("documentId", getId()); 190 | }}); 191 | 192 | String result = SimpleHttpClient.get(config).requestJson(route, new HashMap<>(){{ 193 | put("keyword", keyword); 194 | put("status", status); 195 | }}, null); 196 | 197 | return JSON.parseObject(result, SegmentResult.class); 198 | } 199 | 200 | /** 201 | * 新增分段 202 | * 203 | * @param segments List 204 | * content 文本内容/问题内容 205 | * keywords 关键字,非必填 206 | * answer 答案内容,非必填,如果知识库的模式为 Q&A 模式则传值 207 | */ 208 | public SegmentResult insertSegment(List segments) { 209 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS_ADD.format(new HashMap<>() {{ 210 | put("datasetId", datasetId); 211 | put("documentId", getId()); 212 | }}); 213 | 214 | String result = SimpleHttpClient.get(config).requestJson(route, null, new HashMap<>(){{ 215 | put("segments", segments); 216 | }}); 217 | 218 | return JSON.parseObject(result, SegmentResult.class); 219 | } 220 | 221 | /** 222 | * 删除文档分段 223 | * @param segmentId 文档分段ID 224 | */ 225 | public Boolean deleteSegment(String segmentId) { 226 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS_DEL.format(new HashMap<>() {{ 227 | put("datasetId", datasetId); 228 | put("documentId", getId()); 229 | put("segmentId", segmentId); 230 | }}); 231 | 232 | String result = SimpleHttpClient.get(config).requestJson(route); 233 | JSONObject json = JSON.parseObject(result); 234 | 235 | return "success".equals(json.getString("result")); 236 | } 237 | 238 | /** 239 | * 更新文档分段 240 | * @param segmentId 文档分段ID 241 | * @param content 文本内容/问题内容 242 | * @param regenerate 是否重新生成子分段 243 | */ 244 | public SegmentResult updateSegment(String segmentId, String content, boolean regenerate) { 245 | return updateSegment(Segment.builder().id(segmentId).content(content).build(), regenerate); 246 | } 247 | 248 | /** 249 | * 更新文档分段 250 | * @param segment Segment 251 | * @param regenerate 是否重新生成子分段 252 | */ 253 | public SegmentResult updateSegment(Segment segment, boolean regenerate) { 254 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS_UPDATE.format(new HashMap<>() {{ 255 | put("datasetId", datasetId); 256 | put("documentId", getId()); 257 | put("segmentId", segment.getId()); 258 | }}); 259 | 260 | String result = SimpleHttpClient.get(config).requestJson(route, null, new HashMap<>(){{ 261 | put("segment", new HashMap<>() {{ 262 | put("content", segment.getContent()); 263 | put("answer", segment.getAnswer()); 264 | put("keywords", segment.getKeywords()); 265 | put("enabled", segment.getEnabled()); 266 | put("regenerate_child_chunks", regenerate); 267 | }}); 268 | }}); 269 | 270 | return JSON.parseObject(result, SegmentResult.class); 271 | } 272 | 273 | /** 274 | * 新增文档子分段 275 | * @param segmentId 分段ID 276 | * @param content 子分段内容 277 | */ 278 | public SegmentChildChunk insertSegmentChildChunks(String segmentId, String content) { 279 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_ADD.format(new HashMap<>() {{ 280 | put("datasetId", datasetId); 281 | put("documentId", getId()); 282 | put("segmentId", segmentId); 283 | }}); 284 | 285 | String result = SimpleHttpClient.get(config).requestJson(route, null, new HashMap<>(){{ 286 | put("content", content); 287 | }}); 288 | 289 | JSONObject json = JSON.parseObject(result); 290 | return json.getJSONObject("data").to(SegmentChildChunk.class); 291 | } 292 | 293 | /** 294 | * 查询文档子分段 295 | * @param segmentId 分段ID 296 | * @param page 页码 297 | * @param limit 每页数量 298 | */ 299 | public DifyPage querySegmentChildChunks(String segmentId, Integer page, Integer limit) { 300 | return querySegmentChildChunks(segmentId, page, limit, null); 301 | } 302 | 303 | /** 304 | * 查询文档子分段 305 | * @param segmentId 分段ID 306 | * @param page 页码 307 | * @param limit 每页数量 308 | * @param keyword 搜索关键词(选填) 309 | */ 310 | public DifyPage querySegmentChildChunks(String segmentId, Integer page, Integer limit, String keyword) { 311 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_GET.format(new HashMap<>() {{ 312 | put("datasetId", datasetId); 313 | put("documentId", getId()); 314 | put("segmentId", segmentId); 315 | }}); 316 | 317 | String result = SimpleHttpClient.get(config).requestJson(route, new HashMap<>() {{ 318 | put("page", page); 319 | put("limit", limit); 320 | put("keyword", keyword); 321 | }}); 322 | 323 | return JSON.parseObject(result, new TypeReference>() {}); 324 | } 325 | 326 | /** 327 | * 删除文档子分段 328 | * @param segmentId 分段ID 329 | * @param childChunkId 子分段ID 330 | */ 331 | public Boolean deleteSegmentChildChunks(String segmentId, String childChunkId) { 332 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_DEL.format(new HashMap<>() {{ 333 | put("datasetId", datasetId); 334 | put("documentId", getId()); 335 | put("segmentId", segmentId); 336 | put("childChunkId", childChunkId); 337 | }}); 338 | 339 | String result = SimpleHttpClient.get(config).requestJson(route); 340 | JSONObject json = JSON.parseObject(result); 341 | 342 | return "success".equals(json.getString("result")); 343 | } 344 | 345 | /** 346 | * 更新文档子分段 347 | * @param segmentId 分段ID 348 | * @param childChunkId 子分段ID 349 | * @param content 子分段内容 350 | */ 351 | public SegmentChildChunk updateSegmentChildChunks(String segmentId, String childChunkId, String content) { 352 | DifyRoute route = DatasetRoutes.DATASETS_DOCS_SEGMENTS_CHILD_CHUNKS_SET.format(new HashMap<>() {{ 353 | put("datasetId", datasetId); 354 | put("documentId", getId()); 355 | put("segmentId", segmentId); 356 | put("childChunkId", childChunkId); 357 | }}); 358 | 359 | String result = SimpleHttpClient.get(config).requestJson(route, null, new HashMap<>(){{ 360 | put("content", content); 361 | }}); 362 | 363 | JSONObject json = JSON.parseObject(result); 364 | return json.getJSONObject("data").to(SegmentChildChunk.class); 365 | } 366 | 367 | } 368 | -------------------------------------------------------------------------------- /src/main/java/io/github/yuanbaobaoo/dify/dataset/impl/DatasetClientImpl.java: -------------------------------------------------------------------------------- 1 | package io.github.yuanbaobaoo.dify.dataset.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.dataset.params.ParamUpdateDataset; 7 | import io.github.yuanbaobaoo.dify.types.ApiConfig; 8 | import io.github.yuanbaobaoo.dify.dataset.IDatasetClient; 9 | import io.github.yuanbaobaoo.dify.dataset.entity.*; 10 | import io.github.yuanbaobaoo.dify.dataset.params.ParamDocument; 11 | import io.github.yuanbaobaoo.dify.dataset.types.*; 12 | import io.github.yuanbaobaoo.dify.types.DifyPage; 13 | import io.github.yuanbaobaoo.dify.dataset.params.ParamDataset; 14 | import io.github.yuanbaobaoo.dify.SimpleHttpClient; 15 | import io.github.yuanbaobaoo.dify.routes.DatasetRoutes; 16 | import io.github.yuanbaobaoo.dify.dataset.heros.DatasetHero; 17 | import io.github.yuanbaobaoo.dify.dataset.heros.DocumentHero; 18 | import io.github.yuanbaobaoo.dify.types.DifyRoute; 19 | import io.github.yuanbaobaoo.dify.types.HttpMethod; 20 | 21 | import java.io.File; 22 | import java.util.HashMap; 23 | import java.util.List; 24 | import java.util.Map; 25 | import java.util.concurrent.ConcurrentHashMap; 26 | 27 | public class DatasetClientImpl implements IDatasetClient { 28 | private final ApiConfig server; 29 | 30 | private final Map datasetCache = new ConcurrentHashMap<>(); 31 | private final Map documentCache = new ConcurrentHashMap<>(); 32 | 33 | /** 34 | * build 35 | * @param server Dify Server Address 36 | * @param apiKey API KEY 37 | */ 38 | public static DatasetClientImpl build(String server, String apiKey) { 39 | return new DatasetClientImpl(server, apiKey); 40 | } 41 | 42 | /** 43 | * constructor 44 | * @param server String 45 | * @param apiKey String 46 | */ 47 | private DatasetClientImpl(String server, String apiKey) { 48 | this.server = ApiConfig.builder().server(server).apiKey(apiKey).build(); 49 | } 50 | 51 | /** 52 | * ofDataset 53 | * @param formCache boolean 54 | * @param datasetId String 55 | */ 56 | private DatasetHero ofDataset(boolean formCache, String datasetId) { 57 | if (!formCache) { 58 | return DatasetHero.of(datasetId, server); 59 | } 60 | 61 | return datasetCache.computeIfAbsent(datasetId, k -> DatasetHero.of(datasetId, server)); 62 | } 63 | 64 | /** 65 | * ofDocument 66 | * @param formCache boolean 67 | * @param datasetId String 68 | * @param documentId String 69 | */ 70 | private DocumentHero ofDocument(boolean formCache, String datasetId, String documentId) { 71 | if (!formCache) { 72 | return DocumentHero.of(datasetId, documentId, server); 73 | } 74 | 75 | return documentCache.computeIfAbsent( 76 | String.format("%s-%s", datasetId, documentId), 77 | k -> DocumentHero.of(datasetId, documentId, server) 78 | ); 79 | } 80 | 81 | @Override 82 | public SimpleHttpClient httpClient() { 83 | return SimpleHttpClient.get(server); 84 | } 85 | 86 | @Override 87 | public DatasetHero ofDataset(String datasetId) { 88 | return ofDataset(false, datasetId); 89 | } 90 | 91 | @Override 92 | public DocumentHero ofDocument(String datasetId, String documentId) { 93 | return ofDocument(false, datasetId, documentId); 94 | } 95 | 96 | @Override 97 | public List selectTextEmbedding() { 98 | String result = SimpleHttpClient.get(server).requestJson(DatasetRoutes.MODELS_TEXT_EMBEDDING); 99 | return JSON.parseObject(result).getJSONArray("data").toJavaList(JSONObject.class); 100 | } 101 | 102 | @Override 103 | public DifyPage list(int page, int limit) { 104 | String result = SimpleHttpClient.get(server).requestJson(DatasetRoutes.DATASETS.getUrl(), HttpMethod.GET, new HashMap<>() {{ 105 | put("page", page); 106 | put("limit", limit); 107 | }}, null); 108 | 109 | return JSON.parseObject(result, new TypeReference>() {}); 110 | } 111 | 112 | @Override 113 | public DatasetHero create(ParamDataset data) { 114 | String result = SimpleHttpClient.get(server).requestJson(DatasetRoutes.DATASETS, null, data); 115 | 116 | Dataset dataset = JSON.parseObject(result, Dataset.class); 117 | return DatasetHero.of(dataset, server); 118 | } 119 | 120 | @Override 121 | public DatasetHero get(String datasetId) { 122 | DifyRoute r = DatasetRoutes.DATASETS_INFO.format(Map.of("datasetId", datasetId)); 123 | String result = SimpleHttpClient.get(server).requestJson(r); 124 | 125 | Dataset dataset = JSON.parseObject(result, Dataset.class); 126 | return DatasetHero.of(dataset, server); 127 | } 128 | 129 | @Override 130 | public DatasetHero update(String datasetId, ParamUpdateDataset data) { 131 | return ofDataset(true, datasetId).update(data); 132 | } 133 | 134 | @Override 135 | public void delete(String datasetId) { 136 | ofDataset(true, datasetId).delete(); 137 | } 138 | 139 | @Override 140 | public DocumentResult insertDocByText(String datasetId, ParamDocument doc) { 141 | return ofDataset(true, datasetId).insertText(doc); 142 | } 143 | 144 | @Override 145 | public DocumentResult insertDocByText(String datasetId, ParamDocument doc, RetrievalModel retrievalModel, String embeddingModel, String embeddingModelProvider) { 146 | return ofDataset(true, datasetId).insertText(doc, retrievalModel, embeddingModel, embeddingModelProvider); 147 | } 148 | 149 | @Override 150 | public DocumentResult insertDocByFile(String datasetId, File file, ParamDocument data) { 151 | return ofDataset(true, datasetId).insertFile(file, data); 152 | } 153 | 154 | @Override 155 | public DocumentResult insertDocByFile(String datasetId, File file, ParamDocument data, RetrievalModel retrievalModel, String embeddingModel, String embeddingModelProvider) { 156 | return ofDataset(true, datasetId).insertFile(file, data, retrievalModel, embeddingModel, embeddingModelProvider); 157 | } 158 | 159 | @Override 160 | public List queryBatchStatus(String datasetId, String batch) { 161 | return ofDataset(true, datasetId).queryBatchStatus(batch); 162 | } 163 | 164 | @Override 165 | public DifyPage documents(String datasetId) { 166 | return ofDataset(true, datasetId).documents(); 167 | } 168 | 169 | @Override 170 | public DifyPage documents(String datasetId, Integer page, Integer limit, String keyword) { 171 | return ofDataset(true, datasetId).documents(page, limit, keyword); 172 | } 173 | 174 | @Override 175 | public RetrieveResult retrieve(String datasetId, String query, RetrievalModel retrievalModel) { 176 | return ofDataset(true, datasetId).retrieve(query, retrievalModel); 177 | } 178 | 179 | @Override 180 | public DocumentResult updateDocByText(String datasetId, String documentId, ParamDocument data) { 181 | return ofDocument(true, datasetId, documentId).updateByText(data); 182 | } 183 | 184 | @Override 185 | public DocumentResult updateDocByFile(String datasetId, String documentId, File file, ProcessRule rule) { 186 | return ofDocument(true, datasetId, documentId).updateByFile(file, rule); 187 | } 188 | 189 | @Override 190 | public DocumentResult updateDocByFile(String datasetId, String documentId, String name, File file, ProcessRule rule) { 191 | return ofDocument(true, datasetId, documentId).updateByFile(name, file, rule); 192 | } 193 | 194 | @Override 195 | public Boolean deleteDocument(String datasetId, String documentId) { 196 | return ofDocument(true, datasetId, documentId).delete(); 197 | } 198 | 199 | @Override 200 | public DocFileInfo queryFileInfo(String datasetId, String documentId) { 201 | return ofDocument(true, datasetId, documentId).queryFileInfo(); 202 | } 203 | 204 | @Override 205 | public SegmentResult querySegments(String datasetId, String documentId) { 206 | return ofDocument(true, datasetId, documentId).querySegments(); 207 | } 208 | 209 | @Override 210 | public SegmentResult querySegments(String datasetId, String documentId, String keyword) { 211 | return ofDocument(true, datasetId, documentId).querySegments(keyword); 212 | } 213 | 214 | @Override 215 | public SegmentResult querySegments(String datasetId, String documentId, String keyword, String status) { 216 | return ofDocument(true, datasetId, documentId).querySegments(keyword, status); 217 | } 218 | 219 | @Override 220 | public SegmentResult insertSegment(String datasetId, String documentId, List segments) { 221 | return ofDocument(true, datasetId, documentId).insertSegment(segments); 222 | } 223 | 224 | @Override 225 | public Boolean deleteSegment(String datasetId, String documentId, String segmentId) { 226 | return ofDocument(true, datasetId, documentId).deleteSegment(segmentId); 227 | } 228 | 229 | @Override 230 | public SegmentResult updateSegment(String datasetId, String documentId, String segmentId, String content, boolean regenerate) { 231 | return ofDocument(true, datasetId, documentId).updateSegment(segmentId, content, regenerate); 232 | } 233 | 234 | @Override 235 | public SegmentResult updateSegment(String datasetId, String documentId, Segment segment, boolean regenerate) { 236 | return ofDocument(true, datasetId, documentId).updateSegment(segment, regenerate); 237 | } 238 | 239 | @Override 240 | public SegmentChildChunk insertSegmentChildChunks(String datasetId, String documentId, String segmentId, String content) { 241 | return ofDocument(true, datasetId, documentId).insertSegmentChildChunks(segmentId, content); 242 | } 243 | 244 | @Override 245 | public DifyPage querySegmentChildChunks(String datasetId, String documentId, String segmentId, Integer page, Integer limit) { 246 | return querySegmentChildChunks(datasetId, documentId, segmentId, page, limit, null); 247 | } 248 | 249 | @Override 250 | public DifyPage 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 | --------------------------------------------------------------------------------