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(settings): Add fallback in case models httpRequest returns a JsonArray instead of JsonObject #146

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 @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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<Model> {
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<JsonArray>()
val models = mutableListOf<Model>()
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.")
}
}
}