-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorkflowDemo.kt
245 lines (235 loc) · 9.62 KB
/
WorkflowDemo.kt
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
package com.coze.demo
import com.coze.api.model.ChatFlowData
import com.coze.api.model.EnterMessage
import com.coze.api.model.StreamChatData
import com.coze.api.model.WorkflowEventInterrupt
import com.coze.api.model.WorkflowStreamData
import com.coze.api.model.workflow.*
import com.coze.api.workflow.WorkflowService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
/**
* Workflow Demo | 工作流演示
* Demonstrates workflow functionality | 演示工作流功能
*/
class WorkflowDemo {
private val workflowService = WorkflowService()
private val defaultBotId = "7373880376026103809"
private val defaultAppId = "7439688724318961672"
/**
* Test workflow stream | 测试工作流流式处理
* @param workflowId Workflow ID | 工作流ID
* @return Flow<String> Event messages | 事件消息流
*/
fun streamTest(workflowId: String): Flow<String> = flow {
val streamFlow = workflowService.stream(
RunWorkflowReq(
workflowId = workflowId,
botId = defaultBotId,
parameters = mapOf(
"name" to JsonPrimitive("Jason!")
)
)
)
try {
streamFlow.collect { event ->
when (event) {
is WorkflowStreamData.MessageEvent -> {
val message = event.data
if (message.nodeTitle.isNotEmpty()) {
emit("[${message.nodeTitle}] ${message.content}")
} else {
emit(message.content)
}
}
is WorkflowStreamData.InterruptEvent -> {
emit("[Interrupt] ${event.data.nodeTitle}")
}
is WorkflowStreamData.DoneEvent -> {
emit("[Done] Debug URL: ${event.data.debugUrl}")
}
else -> {} // Errors are handled in WorkflowService | 错误已在WorkflowService中处理
}
}
} catch (e: Exception) {
emit("[Error] ${e.message}")
}
}
/**
* Run workflow | 运行工作流
* @param workflowId Workflow ID | 工作流ID
* @param onMessage Message callback | 消息回调
* @param onError Error callback | 错误回调
* @param onComplete Completion callback | 完成回调
* @param onInterrupt Interrupt callback | 中断回调
* @param useStream Use streaming mode | 使用流式模式
*/
suspend fun runWorkflow(
workflowId: String,
onMessage: (String) -> Unit = {},
onError: (String) -> Unit = {},
onComplete: () -> Unit = {},
onInterrupt: (WorkflowEventInterrupt) -> Unit = {},
useStream: Boolean = true
) {
try {
val req = RunWorkflowReq(
workflowId = workflowId,
botId = defaultBotId,
parameters = mapOf(
"name" to JsonPrimitive("Jason!")
)
)
if (!useStream) {
val result = workflowService.create(req)
onMessage("[Non-Stream] Workflow execution result:")
onMessage("- Data: ${result.data}")
onMessage("- Cost: ${result.cost}")
onMessage("- Token: ${result.token}")
onMessage("- Debug URL: ${result.debugUrl}")
onComplete()
return
}
workflowService.stream(req)
.catch { e ->
if (e !is CancellationException) {
onError(e.message ?: "Unknown error")
}
}
.onCompletion { cause ->
if (cause == null) {
onComplete()
}
}
.collect { event ->
when (event) {
is WorkflowStreamData.MessageEvent -> {
val message = event.data
if (message.nodeTitle.isNotEmpty()) {
onMessage("[${message.nodeTitle}] ${message.content}")
} else {
onMessage(message.content)
}
}
is WorkflowStreamData.InterruptEvent -> {
onInterrupt(event.data)
}
is WorkflowStreamData.DoneEvent -> {
onMessage("[Done] Debug URL: ${event.data.debugUrl}")
}
else -> {} // Errors are handled in WorkflowService | 错误已在WorkflowService中处理
}
}
} catch (e: Exception) {
if (e !is CancellationException) {
onError("Failed to run workflow: ${e.message}")
}
}
}
/**
* Resume workflow | 恢复工作流
* @param workflowId Workflow ID | 工作流ID
* @param eventId Event ID | 事件ID
* @param resumeData Resume data | 恢复数据
* @param interruptType Interrupt type | 中断类型
*/
suspend fun resumeWorkflow(
workflowId: String,
eventId: String,
resumeData: String,
interruptType: Int
) {
val req = ResumeWorkflowReq(
workflowId = workflowId,
eventId = eventId,
resumeData = resumeData,
interruptType = interruptType
)
workflowService.resume(req)
}
/**
* Run chat flow | 运行聊天流
* @param workflowId Workflow ID | 工作流ID
* @param parameters Additional parameters | 额外参数
* @param additionalMessages Additional messages | 额外消息
* @param onMessage Message callback | 消息回调
* @param onError Error callback | 错误回调
* @param onComplete Completion callback | 完成回调
* @param onInterrupt Interrupt callback | 中断回调
*/
suspend fun runChatFlow(
workflowId: String,
parameters: Map<String, JsonElement>? = null,
additionalMessages: List<EnterMessage>,
onMessage: (String) -> Unit = {},
onError: (String) -> Unit = {},
onComplete: () -> Unit = {},
onInterrupt: (WorkflowEventInterrupt) -> Unit = {}
) {
try {
val req = ChatWorkflowReq(
workflowId = workflowId,
appId = defaultAppId,
parameters = parameters,
additionalMessages = additionalMessages
)
workflowService.chat(req)
.catch { e ->
if (e !is CancellationException) {
onError(e.message ?: "Unknown error")
}
}
.onCompletion { cause ->
if (cause == null) {
onComplete()
}
}
.collect { event ->
when (event) {
is ChatFlowData.WorkflowEvent -> {
when (val workflowData = event.data) {
is WorkflowStreamData.MessageEvent -> {
val message = workflowData.data
if (message.nodeTitle.isNotEmpty()) {
onMessage("[${message.nodeTitle}] ${message.content}")
} else {
onMessage(message.content)
}
}
is WorkflowStreamData.InterruptEvent -> {
onInterrupt(workflowData.data)
}
is WorkflowStreamData.DoneEvent -> {
onMessage("[Done] Debug URL: ${workflowData.data.debugUrl}")
}
else -> {} // Errors are handled in WorkflowService | 错误已在WorkflowService中处理
}
}
is ChatFlowData.ChatEvent -> {
when (val chatData = event.data) {
is StreamChatData.ChatMessageEvent -> {
onMessage("[${chatData.event.value}] ${chatData.data.content ?: ""}")
}
is StreamChatData.CreateChatEvent -> {
onMessage("[${chatData.event.value}] Chat created with ID: ${chatData.data.id}")
}
is StreamChatData.DoneEvent -> {
onMessage("[${chatData.event.value}] ${chatData.data}")
}
else -> {} // Errors are handled in WorkflowService | 错误已在WorkflowService中处理
}
}
}
}
} catch (e: Exception) {
if (e !is CancellationException) {
onError("Failed to run workflow chat: ${e.message}")
}
}
}
}