From fd69db83ab8bd090a9f45345abb89ac686ac46ef Mon Sep 17 00:00:00 2001 From: ETdoFresh Date: Sat, 2 Mar 2024 22:09:38 -0600 Subject: [PATCH] fix(settings): Add fallback in case models httpRequest returns a JsonArray instead of JsonObject --- .../commits/intellij/plugin/OpenAIService.kt | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/src/main/kotlin/com/github/blarc/ai/commits/intellij/plugin/OpenAIService.kt b/src/main/kotlin/com/github/blarc/ai/commits/intellij/plugin/OpenAIService.kt index 7e688a2..0f042c4 100644 --- a/src/main/kotlin/com/github/blarc/ai/commits/intellij/plugin/OpenAIService.kt +++ b/src/main/kotlin/com/github/blarc/ai/commits/intellij/plugin/OpenAIService.kt @@ -11,6 +11,16 @@ import com.github.blarc.ai.commits.intellij.plugin.settings.AppSettings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import kotlin.time.Duration.Companion.seconds +import com.aallam.openai.api.model.Model +import io.ktor.client.HttpClient +import io.ktor.client.request.get +import io.ktor.client.request.url +import io.ktor.client.statement.HttpResponse +import io.ktor.client.call.body +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.long @Service(Service.Level.APP) @@ -46,7 +56,7 @@ class OpenAIService { suspend fun refreshOpenAIModelIds() { val openAI = OpenAI(AppSettings.instance.getOpenAIConfig()) - AppSettings.instance.openAIModelIds=openAI.models().map { it.id.id } + AppSettings.instance.openAIModelIds=getOpenAIModels(openAI).map { it.id.id } } @Throws(Exception::class) @@ -59,6 +69,35 @@ class OpenAIService { timeout = Timeout(socket = socketTimeout.toInt().seconds) ) val openAI = OpenAI(config) - openAI.models() + getOpenAIModels(openAI) + } + + @Throws(Exception::class) + suspend fun getOpenAIModels(openAI: OpenAI): List { + try + { + return openAI.models() + } + catch (_: Exception) { + // Fallback to list of models + } + try { + val requester = openAI.javaClass.getDeclaredField("requester").apply { isAccessible = true }.get(openAI) + val httpClient = requester.javaClass.getDeclaredField("httpClient").apply { isAccessible = true }.get(requester) as HttpClient; + val response: HttpResponse = httpClient.get{url(path = "models") } + val jsonArray = response.body() + val models = mutableListOf() + jsonArray.forEach { + models.add(Model( + created = it.jsonObject["created"]?.jsonPrimitive?.long ?: 0, + id = ModelId(it.jsonObject["id"]?.jsonPrimitive?.content ?: ""), + ownedBy = "system" + )) + } + return models + } + catch (_: Exception) { + throw Exception("Failed to retrieve models from OpenAI API.") + } } }