forked from imfangs/dify-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDifyWorkflowClientTest.java
More file actions
364 lines (303 loc) · 12.6 KB
/
DifyWorkflowClientTest.java
File metadata and controls
364 lines (303 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package io.github.imfangs.dify.client;
import io.github.imfangs.dify.client.callback.WorkflowStreamCallback;
import io.github.imfangs.dify.client.config.DifyTestConfig;
import io.github.imfangs.dify.client.enums.FileTransferMethod;
import io.github.imfangs.dify.client.enums.FileType;
import io.github.imfangs.dify.client.enums.ResponseMode;
import io.github.imfangs.dify.client.event.*;
import io.github.imfangs.dify.client.model.file.FileInfo;
import io.github.imfangs.dify.client.model.file.FileUploadResponse;
import io.github.imfangs.dify.client.model.workflow.*;
import io.github.imfangs.dify.client.util.JsonUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/**
* Dify Workflow应用客户端测试类
* 注意:运行测试前,请确保已经正确配置了 dify-test-config.properties 文件
*/
public class DifyWorkflowClientTest {
private static final String BASE_URL = DifyTestConfig.getBaseUrl();
private static final String API_KEY = DifyTestConfig.getWorkflowApiKey();
private static final String USER_ID = "test-user-" + System.currentTimeMillis();
private DifyWorkflowClient workflowClient;
@BeforeEach
public void setUp() {
workflowClient = DifyClientFactory.createWorkflowClient(BASE_URL, API_KEY);
}
@AfterEach
public void tearDown() {
workflowClient.close();
}
/**
* 测试执行工作流(阻塞模式)
*/
@Test
public void testRunWorkflow() throws Exception {
// 创建工作流请求
Map<String, Object> inputs = new HashMap<>();
inputs.put("query", "请介绍一下人工智能的应用场景");
WorkflowRunRequest request = WorkflowRunRequest.builder()
.inputs(inputs)
.responseMode(ResponseMode.BLOCKING)
.user(USER_ID)
.build();
// 执行工作流并获取响应
WorkflowRunResponse response = workflowClient.runWorkflow(request);
// 验证响应
System.out.println(JsonUtils.toJson(response));
assertNotNull(response);
assertNotNull(response.getTaskId());
System.out.println("工作流执行ID: " + response.getTaskId());
// 输出结果
if (response.getData() != null) {
for (Map.Entry<String, Object> entry : response.getData().getOutputs().entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
/**
* 测试执行工作流(流式模式)
*/
@Test
public void testRunWorkflowStream() throws Exception {
// 创建工作流请求
Map<String, Object> inputs = new HashMap<>();
inputs.put("query", "请详细介绍一下机器学习的基本原理");
WorkflowRunRequest request = WorkflowRunRequest.builder()
.inputs(inputs)
.responseMode(ResponseMode.STREAMING)
.user(USER_ID)
.build();
// 用于等待异步回调完成
CountDownLatch latch = new CountDownLatch(1);
StringBuilder outputBuilder = new StringBuilder();
// 执行工作流流式请求
workflowClient.runWorkflowStream(request, new WorkflowStreamCallback() {
@Override
public void onWorkflowStarted(WorkflowStartedEvent event) {
System.out.println("工作流开始: " + event);
}
@Override
public void onNodeStarted(NodeStartedEvent event) {
System.out.println("节点开始: " + event);
}
@Override
public void onNodeFinished(NodeFinishedEvent event) {
System.out.println("节点完成: " + event);
// 直接打印事件,不尝试访问可能不存在的方法
if (event.toString().contains("output")) {
outputBuilder.append(event.toString()).append("\n");
}
}
@Override
public void onWorkflowFinished(WorkflowFinishedEvent event) {
System.out.println("工作流完成: " + event);
latch.countDown();
}
@Override
public void onWorkflowTextChunk(WorkflowTextChunkEvent event) {
System.out.println("工作流DDL执行过程: " + event);
}
@Override
public void onTtsMessage(TtsMessageEvent event) {
System.out.println("收到TTS消息: " + event);
}
@Override
public void onTtsMessageEnd(TtsMessageEndEvent event) {
System.out.println("TTS消息结束: " + event);
}
@Override
public void onError(ErrorEvent event) {
System.out.println("错误事件: " + event);
}
@Override
public void onPing(PingEvent event) {
System.out.println("心跳: " + event);
}
@Override
public void onException(Throwable throwable) {
System.out.println("异常: " + throwable.getMessage());
latch.countDown();
}
});
// 等待流式响应完成
boolean completed = latch.await(60, TimeUnit.SECONDS);
assertTrue(completed, "流式响应超时");
// 验证响应
assertFalse(outputBuilder.toString().isEmpty(), "输出不应为空");
System.out.println("完整输出: " + outputBuilder.toString());
}
/**
* 测试停止工作流
*/
@Test
public void testStopWorkflow() throws Exception {
// 创建工作流请求
Map<String, Object> inputs = new HashMap<>();
inputs.put("query", "请写一篇长文章,描述人工智能的未来发展");
WorkflowRunRequest request = WorkflowRunRequest.builder()
.inputs(inputs)
.responseMode(ResponseMode.STREAMING)
.user(USER_ID)
.build();
// 用于等待异步回调完成
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> taskId = new AtomicReference<>();
// 执行工作流流式请求
workflowClient.runWorkflowStream(request, new WorkflowStreamCallback() {
@Override
public void onWorkflowStarted(WorkflowStartedEvent event) {
if (taskId.get() == null && event.getTaskId() != null) {
taskId.set(event.getTaskId());
latch.countDown();
}
}
@Override
public void onNodeStarted(NodeStartedEvent event) {
// 不处理
}
@Override
public void onNodeFinished(NodeFinishedEvent event) {
// 不处理
}
@Override
public void onWorkflowFinished(WorkflowFinishedEvent event) {
// 不应该到达这里,因为我们会提前停止
}
@Override
public void onTtsMessage(TtsMessageEvent event) {
// 不处理
}
@Override
public void onTtsMessageEnd(TtsMessageEndEvent event) {
// 不处理
}
@Override
public void onError(ErrorEvent event) {
System.err.println("错误事件: " + event);
latch.countDown();
}
@Override
public void onPing(PingEvent event) {
// 不处理
}
@Override
public void onException(Throwable throwable) {
System.err.println("异常: " + throwable.getMessage());
latch.countDown();
}
});
// 等待获取任务ID
boolean gotTaskId = latch.await(10, TimeUnit.SECONDS);
assertTrue(gotTaskId, "未能获取任务ID");
assertNotNull(taskId.get(), "任务ID不应为空");
// 停止工作流
WorkflowStopResponse stopResponse = workflowClient.stopWorkflow(taskId.get(), USER_ID);
// 验证响应
assertNotNull(stopResponse);
assertEquals("success", stopResponse.getResult(), "停止应成功");
System.out.println("停止工作流结果: " + stopResponse.getResult());
}
/**
* 测试获取工作流执行情况
*/
@Test
public void testGetWorkflowRun() throws Exception {
// 创建工作流请求
Map<String, Object> inputs = new HashMap<>();
inputs.put("query", "请简要介绍一下深度学习");
WorkflowRunRequest request = WorkflowRunRequest.builder()
.inputs(inputs)
.responseMode(ResponseMode.BLOCKING)
.user(USER_ID)
.build();
// 执行工作流
WorkflowRunResponse runResponse = workflowClient.runWorkflow(request);
assertNotNull(runResponse);
System.out.println(runResponse);
assertNotNull(runResponse.getWorkflowRunId(), "工作流执行ID不应为空");
// 获取工作流执行情况
WorkflowRunStatusResponse statusResponse = workflowClient.getWorkflowRun(runResponse.getWorkflowRunId());
// 验证响应
assertNotNull(statusResponse);
assertEquals(runResponse.getWorkflowRunId(), statusResponse.getId(), "工作流执行ID应匹配");
System.out.println("工作流执行状态: " + statusResponse.getStatus());
System.out.println("工作流执行详情: " + statusResponse);
}
/**
* 测试获取工作流日志
*/
@Test
public void testGetWorkflowLogs() throws Exception {
// 获取工作流日志
WorkflowLogsResponse logsResponse = workflowClient.getWorkflowLogs(null, null, 1, 10);
// 验证响应
assertNotNull(logsResponse);
System.out.println("工作流日志: " + logsResponse);
// 如果有日志记录,打印第一条
if (logsResponse != null && logsResponse.toString().contains("items") &&
logsResponse.toString().contains("id")) {
System.out.println("工作流日志详情: " + logsResponse);
}
}
/**
* 测试获取应用信息
*/
@Test
public void testGetAppInfo() throws Exception {
Object appInfo = workflowClient.getAppInfo();
// 验证响应
assertNotNull(appInfo);
System.out.println("应用信息: " + appInfo);
}
@Test
public void testRunWorkflowWithFile() throws Exception {
// 上传文件
File file = new File("path/to/your/file.txt");
if (!file.exists()) {
System.out.println("文件不存在,跳过测试");
return;
}
FileUploadResponse uploadResponse = workflowClient.uploadFile(file, USER_ID);
assertNotNull(uploadResponse);
assertNotNull(uploadResponse.getId(), "上传文件ID不应为空");
System.out.println(uploadResponse);
// 创建文件信息
FileInfo fileInfo = FileInfo.builder()
.type(FileType.DOCUMENT)
.transferMethod(FileTransferMethod.LOCAL_FILE)
.uploadFileId(uploadResponse.getId())
.build();
// 创建工作流请求,需要在开始节点增加两个参数,例: query: 文本, file: 类型选择文件列表
Map<String, Object> inputs = new HashMap<>();
inputs.put("query", "你好,请分析这个文件的内容");
inputs.put("file", Collections.singletonList(fileInfo));
WorkflowRunRequest request = WorkflowRunRequest.builder()
.inputs(inputs)
.responseMode(ResponseMode.BLOCKING)
.user(USER_ID)
.build();
// 执行工作流并获取响应
WorkflowRunResponse response = workflowClient.runWorkflow(request);
// 验证响应
System.out.println(JsonUtils.toJson(response));
assertNotNull(response);
assertNotNull(response.getTaskId());
System.out.println("工作流执行ID: " + response.getTaskId());
// 输出结果
if (response.getData() != null) {
for (Map.Entry<String, Object> entry : response.getData().getOutputs().entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
}