Skip to content

Commit

Permalink
fix(chat): function mode serializer (#203)
Browse files Browse the repository at this point in the history
  • Loading branch information
emeasure-github-private authored Jun 24, 2023
1 parent c37ce61 commit ab24fbc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonEncoder
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonPrimitive
import kotlin.jvm.JvmInline

/**
Expand Down Expand Up @@ -62,7 +63,7 @@ internal object FunctionModeSerializer : KSerializer<FunctionMode> {
require(decoder is JsonDecoder) { "This decoder is not a JsonDecoder. Cannot deserialize `FunctionCall`" }
return when (val json = decoder.decodeJsonElement()) {
is JsonPrimitive -> Default(json.content)
is JsonObject -> Named.serializer().deserialize(decoder)
is JsonObject -> json["name"]?.jsonPrimitive?.content?.let(FunctionMode::Named) ?: error("Missing 'name'")
else -> throw UnsupportedOperationException("Cannot deserialize FunctionMode. Unsupported JSON element.")
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.aallam.openai.api.chat

import com.aallam.openai.api.BetaOpenAI
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals

@OptIn(BetaOpenAI::class)
class TestFunctionMode {

@Test
fun serialize() {
listOf(
FunctionMode.Auto,
FunctionMode.None,
FunctionMode.Named("someFunctionName")
).forEach { functionMode ->
val jsonString = Json.encodeToString(FunctionMode.serializer(), functionMode)
val decoded = Json.decodeFromString(FunctionMode.serializer(), jsonString)
assertEquals(functionMode, decoded)
}
}
}

0 comments on commit ab24fbc

Please sign in to comment.