Lambdua / openai4j

Java client library for OpenAI API.Full support for all OpenAI API models including Completions, Chat, Edits, Embeddings, Audio, Files, Assistants-v2, Images, Moderations, Batch, and Fine-tuning.
MIT License
331 stars 31 forks source link

Unable to connect azure with api version #66

Closed anoopnarang closed 2 months ago

anoopnarang commented 2 months ago

Azure openai urls are of type https://some-host.openai.azure.com/openai/deployments/my-gpt-35-turbo/chat/completions?api-version=2023-03-15-preview

We can supply the new url in constructor, but there is no way to provide api-version.

Presently I am bypassing this issue by forking the repo and adding my own interceptor. Whats the recommended way here ?

public class AzureAuthenticationInterceptor implements Interceptor {

    private final String apiKey;

    private final String apiVersion;

    public AzureAuthenticationInterceptor(String apiKey, String apiVersion) {
        Objects.requireNonNull(apiKey);
        Objects.requireNonNull(apiVersion);
        this.apiKey = apiKey;
        this.apiVersion = apiVersion;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {

        // Add api-version query parameter to all requests
        HttpUrl url = chain.request().url().newBuilder().addQueryParameter("api-version", apiVersion).build();

        // Add api-key header to all requests
        Request request = chain.request()
            .newBuilder()
            .url(url)
            .header("api-key",  apiKey)
            .build();

        return chain.proceed(request);
    }
}

I am happy to create a PR for this its not supported already.

Lambdua commented 2 months ago

https://github.com/Lambdua/openai4j/blob/7b7be9ae084d750b14bb6f3fb450c5fa2d734c78/example/src/main/java/example/ServiceCreateExample.java#L23-L53

You can refer to this main method to customize your openAiService

anoopnarang commented 2 months ago

Thanks @Lambdua , this should do for the time being.