interfAIce icon indicating copy to clipboard operation
interfAIce copied to clipboard

Provide a way to close OkHttpClient when using `DefaultOkHttpOpenAiClient`

Open mscheong01 opened this issue 2 years ago • 2 comments

When executing a Test where an error occurs in InvocationHandler, it takes a while for the system to exit after the exception is thrown. It looks like the probable cause is that the background thread that calls the openai api is not cleaned up and runs regardless of the error. This did not happen when I used OpenAiApiClientdefined in the spring boot starter that uses a spring webclient. suspicious code: https://github.com/mscheong01/interfAIce/blob/main/core/src/main/kotlin/io/github/mscheong01/interfaice/openai/DefaultOkHttpOpenAiClient.kt

Mono.create { sink ->
    client.newCall(httpRequest).enqueue(object : com.squareup.okhttp.Callback {
        override fun onFailure(request: Request, e: java.io.IOException) {
            sink.error(e)
        }

        override fun onResponse(response: com.squareup.okhttp.Response) {
            try {
                if (!response.isSuccessful) {
                    throw IOException("Error: ${response.code()} ${response.message()}")
                } else {
                    sink.success(mapper.readValue(response.body().string()))
                }
            } catch (e: Exception) {
                sink.error(e)
            }
        }
    })
}

mscheong01 avatar Jun 11 '23 09:06 mscheong01

The cause turned out to be that the OkHttpClient used in DefaultOkHttpOpenAiClient is not closed, leaving connection threads that keep the application from exiting. We could make the OpenAiProxyFactory and OpenAiApiAdapter implement Closable. However, this would mean that closing an OpenAiProxyFactory would stop all proxies created from it from working. I'm not sure if this is an acceptable pattern 🤔

mscheong01 avatar Jun 11 '23 10:06 mscheong01

I've implemented the above comment here, but I'll leave it open until I'm sure that it's a good implementation

mscheong01 avatar Jun 11 '23 10:06 mscheong01