Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash in Streamed submit tools output #420

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.serialization.json.*

internal class RunsApi(val requester: HttpRequester) : Runs {
override suspend fun createRun(threadId: ThreadId, request: RunRequest, requestOptions: RequestOptions?): Run {
Expand Down Expand Up @@ -123,7 +122,11 @@ internal class RunsApi(val requester: HttpRequester) : Runs {
return requester
.performSse {
url(path = "${ApiPath.Threads}/${threadId.id}/runs/${runId.id}/submit_tool_outputs")
setBody(mapOf("tool_outputs" to output, "stream" to true))
val bodyObject = buildJsonObject {
put("tool_outputs", output.toJsonArray())
put("stream", JsonPrimitive(true))
}
setBody(bodyObject)
contentType(ContentType.Application.Json)
accept(ContentType.Text.EventStream)
beta("assistants", 2)
Expand All @@ -132,6 +135,18 @@ internal class RunsApi(val requester: HttpRequester) : Runs {
}
}

// Need to manual convert to JsonObject as Kotlinx serialization fails when multiple data types are present in the same collection
// java.lang.IllegalStateException: Serializing collections of different element types is not yet supported. Selected serializers: [kotlin.collections.ArrayList, kotlin.Boolean]
// https://youtrack.jetbrains.com/issue/KTOR-3063/Support-serializing-collections-of-different-element-types
private fun List<ToolOutput>.toJsonArray(): JsonArray = buildJsonArray {
forEach { add(it.toJsonObject()) }
}

private fun ToolOutput.toJsonObject(): JsonObject = buildJsonObject {
toolCallId?.id?.let { put("tool_call_id", JsonPrimitive(it)) }
output?.let { put("output", JsonPrimitive(it)) }
}

override suspend fun cancel(threadId: ThreadId, runId: RunId, requestOptions: RequestOptions?): Run {
return requester.perform {
it.post {
Expand Down