-
Notifications
You must be signed in to change notification settings - Fork 16
/
AssistantThread.kt
308 lines (273 loc) · 10 KB
/
AssistantThread.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
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
package com.xebia.functional.xef.llm.assistants
import arrow.fx.coroutines.parMap
import com.xebia.functional.openai.apis.AssistantsApi
import com.xebia.functional.openai.infrastructure.ApiClient
import com.xebia.functional.openai.models.*
import com.xebia.functional.openai.models.ext.assistant.RunStepDetailsMessageCreationObject
import com.xebia.functional.openai.models.ext.assistant.RunStepDetailsToolCallsObject
import com.xebia.functional.openai.models.ext.assistant.RunStepObjectStepDetails
import com.xebia.functional.xef.llm.addMetrics
import com.xebia.functional.xef.llm.fromEnvironment
import com.xebia.functional.xef.metrics.Metric
import kotlin.jvm.JvmName
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.flow
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
class AssistantThread(
val threadId: String,
val metric: Metric = Metric.EMPTY,
private val api: AssistantsApi = fromEnvironment(::AssistantsApi)
) {
suspend fun delete(): Boolean = api.deleteThread(threadId).body().deleted
suspend fun modify(request: ModifyThreadRequest): AssistantThread =
AssistantThread(api.modifyThread(threadId, request).body().id)
suspend fun createMessage(message: MessageWithFiles): MessageObject =
createMessage(
CreateMessageRequest(
role = CreateMessageRequest.Role.user,
content = message.content,
fileIds = message.fileIds
)
)
suspend fun createMessage(content: String): MessageObject =
createMessage(CreateMessageRequest(role = CreateMessageRequest.Role.user, content = content))
suspend fun createMessage(request: CreateMessageRequest): MessageObject =
api.createMessage(threadId, request).body()
suspend fun getMessage(messageId: String): MessageObject =
api.getMessage(threadId, messageId).body()
suspend fun listMessages(): List<MessageObject> = api.listMessages(threadId).body().data
suspend fun createRun(request: CreateRunRequest): RunObject =
api.createRun(threadId, request).body().addMetrics(metric)
suspend fun getRun(runId: String): RunObject = api.getRun(threadId, runId).body()
suspend fun createRun(assistant: Assistant): RunObject =
createRun(CreateRunRequest(assistantId = assistant.assistantId))
suspend fun run(assistant: Assistant): Flow<RunDelta> {
val run = createRun(assistant)
return awaitRun(assistant, run.id)
}
suspend fun cancelRun(runId: String): RunObject = api.cancelRun(threadId, runId).body()
suspend fun runSteps(runId: String): List<RunStepObject> =
api.listRunSteps(threadId, runId).body().data
sealed class RunDelta {
data class ReceivedMessage(val message: MessageObject) : RunDelta()
data class Run(val message: RunObject) : RunDelta()
data class Step(val runStep: RunStepObject) : RunDelta()
}
fun awaitRun(assistant: Assistant, runId: String): Flow<RunDelta> = flow {
val stepCache = mutableSetOf<RunStepObject>() // CacheTool
val messagesCache = mutableSetOf<MessageObject>()
val runCache = mutableSetOf<RunObject>()
try {
var run = checkRun(runId = runId, cache = runCache)
while (run.status != RunObject.Status.completed) {
checkSteps(assistant = assistant, runId = runId, cache = stepCache)
delay(500) // To avoid excessive calls to OpenAI
checkMessages(runId, cache = messagesCache)
delay(500) // To avoid excessive calls to OpenAI
run = checkRun(runId = runId, cache = runCache)
}
} catch (e: Exception) {
emit(
RunDelta.Run(
RunObject(
id = runId,
`object` = RunObject.Object.thread_run,
createdAt = 0,
threadId = threadId,
assistantId = assistant.assistantId,
status = RunObject.Status.failed,
lastError =
RunObjectLastError(
code = RunObjectLastError.Code.server_error,
message = e.message ?: "Unknown error"
),
startedAt = null,
cancelledAt = null,
failedAt = null,
completedAt = null,
model = "",
instructions = "",
tools = emptyList(),
fileIds = emptyList(),
metadata = null,
usage = null
)
)
)
} finally {
checkMessages(runId, cache = messagesCache)
}
}
private suspend fun FlowCollector<RunDelta>.checkRun(
runId: String,
cache: MutableSet<RunObject>
): RunObject {
val run = metric.assistantCreateRun(runId) { getRun(runId) }
if (run !in cache) {
cache.add(run)
emit(RunDelta.Run(run))
}
return run
}
private suspend fun FlowCollector<RunDelta>.checkMessages(
runId: String,
cache: MutableSet<MessageObject>
) {
metric.assistantCreatedMessage(runId) {
val messages = mutableListOf<MessageObject>()
val updatedAndNewMessages = listMessages().filterNot { it in cache }
updatedAndNewMessages.forEach { message ->
val content = message.content.filterNot { it.text?.value?.isBlank() ?: true }
if (content.isNotEmpty() && message !in cache) {
cache.add(message)
messages.add(message)
emit(RunDelta.ReceivedMessage(message))
}
}
messages
}
}
private fun RunStepObjectStepDetails.toolCalls():
List<RunStepDetailsToolCallsObjectToolCallsInner> =
when (this) {
is RunStepDetailsMessageCreationObject -> listOf()
is RunStepDetailsToolCallsObject -> toolCalls
}
private suspend fun FlowCollector<RunDelta>.checkSteps(
assistant: Assistant,
runId: String,
cache: MutableSet<RunStepObject>
) {
val steps = runSteps(runId).map { metric.assistantCreateRunStep(runId) { it } }
steps.forEach { step ->
val calls = step.stepDetails.toolCalls()
// .filter {
// it.function != null && it.function!!.arguments.isNotBlank()
// }
// We have detected that tool call in in_progress state sometimes don't have any arguments
// and this is not valid. We need to skip this step in this case.
val canEmitToolCalls =
if (
step.type == RunStepObject.Type.tool_calls &&
step.status == RunStepObject.Status.in_progress
)
calls.isNotEmpty()
else true
val emitEvent = canEmitToolCalls && step !in cache
if (emitEvent) {
cache.add(step)
emit(RunDelta.Step(step))
}
val run = getRun(runId)
if (
run.status == RunObject.Status.requires_action &&
run.requiredAction?.type == RunObjectRequiredAction.Type.submit_tool_outputs
) {
val results: Map<String, JsonElement> =
calls
.filter { it.function != null }
.parMap { toolCall ->
val function = toolCall.function!!
val result: JsonElement =
assistant.getToolRegistered(function.name, function.arguments)
toolCall.id to result
}
.toMap()
metric.assistantToolOutputsRun(runId) {
api
.submitToolOuputsToRun(
threadId = threadId,
runId = runId,
submitToolOutputsRunRequest =
SubmitToolOutputsRunRequest(
toolOutputs =
results.map { (toolCallId, result) ->
SubmitToolOutputsRunRequestToolOutputsInner(
toolCallId = toolCallId,
output = ApiClient.JSON_DEFAULT.encodeToString(result)
)
}
)
)
.body()
}
}
}
}
companion object {
@JvmName("createWithMessagesAndFiles")
suspend operator fun invoke(
messages: List<MessageWithFiles>,
metadata: JsonObject? = null,
metric: Metric = Metric.EMPTY,
api: AssistantsApi = fromEnvironment(::AssistantsApi)
): AssistantThread =
AssistantThread(
api
.createThread(
CreateThreadRequest(
messages.map {
CreateMessageRequest(
role = CreateMessageRequest.Role.user,
content = it.content,
fileIds = it.fileIds
)
},
metadata
)
)
.body()
.id,
metric,
api
)
@JvmName("createWithMessages")
suspend operator fun invoke(
messages: List<String>,
metadata: JsonObject? = null,
metric: Metric = Metric.EMPTY,
api: AssistantsApi = fromEnvironment(::AssistantsApi)
): AssistantThread =
AssistantThread(
api
.createThread(
CreateThreadRequest(
messages.map {
CreateMessageRequest(role = CreateMessageRequest.Role.user, content = it)
},
metadata
)
)
.body()
.id,
metric,
api
)
@JvmName("createWithRequests")
suspend operator fun invoke(
messages: List<CreateMessageRequest> = emptyList(),
metadata: JsonObject? = null,
metric: Metric = Metric.EMPTY,
api: AssistantsApi = fromEnvironment(::AssistantsApi)
): AssistantThread =
AssistantThread(
api.createThread(CreateThreadRequest(messages, metadata)).body().id,
metric,
api
)
suspend operator fun invoke(
request: CreateThreadRequest,
metric: Metric = Metric.EMPTY,
api: AssistantsApi = fromEnvironment(::AssistantsApi)
): AssistantThread = AssistantThread(api.createThread(request).body().id, metric, api)
suspend operator fun invoke(
request: CreateThreadAndRunRequest,
metric: Metric = Metric.EMPTY,
api: AssistantsApi = fromEnvironment(::AssistantsApi)
): AssistantThread = AssistantThread(api.createThreadAndRun(request).body().id, metric, api)
}
}