Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -31,8 +31,10 @@
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.springframework.ai.model.ApiKey;
import org.springframework.ai.model.ChatModelDescription;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.ai.model.SimpleApiKey;
import org.springframework.ai.openai.api.common.OpenAiApiConstants;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.core.ParameterizedTypeReference;
Expand Down Expand Up @@ -61,6 +63,10 @@
*/
public class OpenAiApi {

public static Builder builder() {
return new Builder();
}

public static final OpenAiApi.ChatModel DEFAULT_CHAT_MODEL = ChatModel.GPT_4_O;

public static final String DEFAULT_EMBEDDING_MODEL = EmbeddingModel.TEXT_EMBEDDING_ADA_002.getValue();
Expand All @@ -80,7 +86,9 @@ public class OpenAiApi {
/**
* Create a new chat completion api with base URL set to https://api.openai.com
* @param apiKey OpenAI apiKey.
* @deprecated since 1.0.0.M6 - use {@link #builder()} instead
*/
@Deprecated(since = "1.0.0.M6")
public OpenAiApi(String apiKey) {
this(OpenAiApiConstants.DEFAULT_BASE_URL, apiKey);
}
Expand All @@ -89,7 +97,9 @@ public OpenAiApi(String apiKey) {
* Create a new chat completion api.
* @param baseUrl api base URL.
* @param apiKey OpenAI apiKey.
* @deprecated since 1.0.0.M6 - use {@link #builder()} instead
*/
@Deprecated(since = "1.0.0.M6")
public OpenAiApi(String baseUrl, String apiKey) {
this(baseUrl, apiKey, RestClient.builder(), WebClient.builder());
}
Expand All @@ -100,7 +110,9 @@ public OpenAiApi(String baseUrl, String apiKey) {
* @param apiKey OpenAI apiKey.
* @param restClientBuilder RestClient builder.
* @param webClientBuilder WebClient builder.
* @deprecated since 1.0.0.M6 - use {@link #builder()} instead
*/
@Deprecated(since = "1.0.0.M6")
public OpenAiApi(String baseUrl, String apiKey, RestClient.Builder restClientBuilder,
WebClient.Builder webClientBuilder) {
this(baseUrl, apiKey, restClientBuilder, webClientBuilder, RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
Expand All @@ -113,7 +125,9 @@ public OpenAiApi(String baseUrl, String apiKey, RestClient.Builder restClientBui
* @param restClientBuilder RestClient builder.
* @param webClientBuilder WebClient builder.
* @param responseErrorHandler Response error handler.
* @deprecated since 1.0.0.M6 - use {@link #builder()} instead
*/
@Deprecated(since = "1.0.0.M6")
public OpenAiApi(String baseUrl, String apiKey, RestClient.Builder restClientBuilder,
WebClient.Builder webClientBuilder, ResponseErrorHandler responseErrorHandler) {
this(baseUrl, apiKey, "/v1/chat/completions", "/v1/embeddings", restClientBuilder, webClientBuilder,
Expand All @@ -129,7 +143,9 @@ public OpenAiApi(String baseUrl, String apiKey, RestClient.Builder restClientBui
* @param restClientBuilder RestClient builder.
* @param webClientBuilder WebClient builder.
* @param responseErrorHandler Response error handler.
* @deprecated since 1.0.0.M6 - use {@link #builder()} instead
*/
@Deprecated(since = "1.0.0.M6")
public OpenAiApi(String baseUrl, String apiKey, String completionsPath, String embeddingsPath,
RestClient.Builder restClientBuilder, WebClient.Builder webClientBuilder,
ResponseErrorHandler responseErrorHandler) {
Expand All @@ -148,10 +164,32 @@ public OpenAiApi(String baseUrl, String apiKey, String completionsPath, String e
* @param restClientBuilder RestClient builder.
* @param webClientBuilder WebClient builder.
* @param responseErrorHandler Response error handler.
* @deprecated since 1.0.0.M6 - use {@link #builder()} instead
*/
@Deprecated(since = "1.0.0.M6")
public OpenAiApi(String baseUrl, String apiKey, MultiValueMap<String, String> headers, String completionsPath,
String embeddingsPath, RestClient.Builder restClientBuilder, WebClient.Builder webClientBuilder,
ResponseErrorHandler responseErrorHandler) {
this(baseUrl, new SimpleApiKey(apiKey), headers, completionsPath, embeddingsPath, restClientBuilder,
webClientBuilder, responseErrorHandler);
}

/**
* Create a new chat completion api.
* @param baseUrl api base URL.
* @param apiKey OpenAI apiKey.
* @param headers the http headers to use.
* @param completionsPath the path to the chat completions endpoint.
* @param embeddingsPath the path to the embeddings endpoint.
* @param restClientBuilder RestClient builder.
* @param webClientBuilder WebClient builder.
* @param responseErrorHandler Response error handler.
* @deprecated since 1.0.0.M6 - use {@link #builder()} instead
*/
@Deprecated(since = "1.0.0.M6")
public OpenAiApi(String baseUrl, ApiKey apiKey, MultiValueMap<String, String> headers, String completionsPath,
String embeddingsPath, RestClient.Builder restClientBuilder, WebClient.Builder webClientBuilder,
ResponseErrorHandler responseErrorHandler) {

Assert.hasText(completionsPath, "Completions Path must not be null");
Assert.hasText(embeddingsPath, "Embeddings Path must not be null");
Expand All @@ -161,7 +199,7 @@ public OpenAiApi(String baseUrl, String apiKey, MultiValueMap<String, String> he
this.embeddingsPath = embeddingsPath;
// @formatter:off
Consumer<HttpHeaders> finalHeaders = h -> {
h.setBearerAuth(apiKey);
h.setBearerAuth(apiKey.getValue());
h.setContentType(MediaType.APPLICATION_JSON);
h.addAll(headers);
};
Expand Down Expand Up @@ -1507,4 +1545,78 @@ public record EmbeddingList<T>(// @formatter:off
@JsonProperty("usage") Usage usage) { // @formatter:on
}

public static class Builder {

private String baseUrl = OpenAiApiConstants.DEFAULT_BASE_URL;

private ApiKey apiKey;

private MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();

private String completionsPath = "/v1/chat/completions";

private String embeddingsPath = "/v1/embeddings";

private RestClient.Builder restClientBuilder = RestClient.builder();

private WebClient.Builder webClientBuilder = WebClient.builder();

private ResponseErrorHandler responseErrorHandler = RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER;

public Builder baseUrl(String baseUrl) {
Assert.hasText(baseUrl, "baseUrl cannot be null or empty");
this.baseUrl = baseUrl;
return this;
}

public Builder apiKey(ApiKey apiKey) {
Assert.notNull(apiKey, "apiKey cannot be null");
this.apiKey = apiKey;
return this;
}

public Builder headers(MultiValueMap<String, String> headers) {
Assert.notNull(headers, "headers cannot be null");
this.headers = headers;
return this;
}

public Builder completionsPath(String completionsPath) {
Assert.hasText(completionsPath, "completionsPath cannot be null or empty");
this.completionsPath = completionsPath;
return this;
}

public Builder embeddingsPath(String embeddingsPath) {
Assert.hasText(embeddingsPath, "embeddingsPath cannot be null or empty");
this.embeddingsPath = embeddingsPath;
return this;
}

public Builder restClientBuilder(RestClient.Builder restClientBuilder) {
Assert.notNull(restClientBuilder, "restClientBuilder cannot be null");
this.restClientBuilder = restClientBuilder;
return this;
}

public Builder webClientBuilder(WebClient.Builder webClientBuilder) {
Assert.notNull(webClientBuilder, "webClientBuilder cannot be null");
this.webClientBuilder = webClientBuilder;
return this;
}

public Builder responseErrorHandler(ResponseErrorHandler responseErrorHandler) {
Assert.notNull(responseErrorHandler, "responseErrorHandler cannot be null");
this.responseErrorHandler = responseErrorHandler;
return this;
}

public OpenAiApi build() {
Assert.notNull(this.apiKey, "apiKey must be set");
return new OpenAiApi(this.baseUrl, this.apiKey, this.headers, this.completionsPath, this.embeddingsPath,
this.restClientBuilder, this.webClientBuilder, this.responseErrorHandler);
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2023-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.openai.api;

import org.springframework.beans.factory.annotation.Qualifier;

import java.lang.annotation.*;

/**
* Qualifier annotation for OpenAI API key beans. Used to distinguish OpenAI API keys from
* other provider API keys.
*
* @author Mark Pollack
*/
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Qualifier
public @interface OpenAiApiKey {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change to OpenAiChatApiKey so it is specific to chat models, there will be OpenAiEmbeddingApiKey different models can have different endpoints.


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Copyright 2023-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai.api;

import org.junit.jupiter.api.Test;

import org.springframework.ai.model.ApiKey;
import org.springframework.ai.model.SimpleApiKey;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;

public class OpenAiApiBuilderTests {

private static final ApiKey TEST_API_KEY = new SimpleApiKey("test-api-key");

private static final String TEST_BASE_URL = "https://test.openai.com";

private static final String TEST_COMPLETIONS_PATH = "/test/completions";

private static final String TEST_EMBEDDINGS_PATH = "/test/embeddings";

@Test
void testMinimalBuilder() {
OpenAiApi api = OpenAiApi.builder().apiKey(TEST_API_KEY).build();

assertThat(api).isNotNull();
}

@Test
void testFullBuilder() {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Custom-Header", "test-value");
RestClient.Builder restClientBuilder = RestClient.builder();
WebClient.Builder webClientBuilder = WebClient.builder();
ResponseErrorHandler errorHandler = mock(ResponseErrorHandler.class);

OpenAiApi api = OpenAiApi.builder()
.apiKey(TEST_API_KEY)
.baseUrl(TEST_BASE_URL)
.headers(headers)
.completionsPath(TEST_COMPLETIONS_PATH)
.embeddingsPath(TEST_EMBEDDINGS_PATH)
.restClientBuilder(restClientBuilder)
.webClientBuilder(webClientBuilder)
.responseErrorHandler(errorHandler)
.build();

assertThat(api).isNotNull();
}

@Test
void testDefaultValues() {
OpenAiApi api = OpenAiApi.builder().apiKey(TEST_API_KEY).build();

assertThat(api).isNotNull();
// We can't directly test the default values as they're private fields,
// but we know the builder succeeded with defaults
}

@Test
void testMissingApiKey() {
assertThatThrownBy(() -> {
OpenAiApi.builder().build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("apiKey must be set");
}

@Test
void testInvalidBaseUrl() {
assertThatThrownBy(() -> {
OpenAiApi.builder().baseUrl("").build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("baseUrl cannot be null or empty");

assertThatThrownBy(() -> {
OpenAiApi.builder().baseUrl(null).build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("baseUrl cannot be null or empty");
}

@Test
void testInvalidHeaders() {
assertThatThrownBy(() -> {
OpenAiApi.builder().headers(null).build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("headers cannot be null");
}

@Test
void testInvalidCompletionsPath() {
assertThatThrownBy(() -> {
OpenAiApi.builder().completionsPath("").build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("completionsPath cannot be null or empty");

assertThatThrownBy(() -> {
OpenAiApi.builder().completionsPath(null).build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("completionsPath cannot be null or empty");
}

@Test
void testInvalidEmbeddingsPath() {
assertThatThrownBy(() -> {
OpenAiApi.builder().embeddingsPath("").build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("embeddingsPath cannot be null or empty");

assertThatThrownBy(() -> {
OpenAiApi.builder().embeddingsPath(null).build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("embeddingsPath cannot be null or empty");
}

@Test
void testInvalidRestClientBuilder() {
assertThatThrownBy(() -> {
OpenAiApi.builder().restClientBuilder(null).build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("restClientBuilder cannot be null");
}

@Test
void testInvalidWebClientBuilder() {
assertThatThrownBy(() -> {
OpenAiApi.builder().webClientBuilder(null).build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("webClientBuilder cannot be null");
}

@Test
void testInvalidResponseErrorHandler() {
assertThatThrownBy(() -> {
OpenAiApi.builder().responseErrorHandler(null).build();
}).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("responseErrorHandler cannot be null");
}

}
Loading