Skip to content

Add support for ApiKey for Anthropic and use it dynamically for every request #3365

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
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 @@ -34,8 +34,10 @@
import reactor.core.publisher.Mono;

import org.springframework.ai.anthropic.api.StreamHelper.ChatCompletionResponseBuilder;
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.observation.conventions.AiProvider;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.http.HttpHeaders;
Expand Down Expand Up @@ -96,6 +98,8 @@ public static Builder builder() {

private final WebClient webClient;

private final ApiKey apiKey;

/**
* Create a new client api.
* @param baseUrl api base URL.
Expand All @@ -107,18 +111,18 @@ public static Builder builder() {
* @param responseErrorHandler Response error handler.
* @param anthropicBetaFeatures Anthropic beta features.
*/
private AnthropicApi(String baseUrl, String completionsPath, String anthropicApiKey, String anthropicVersion,
private AnthropicApi(String baseUrl, String completionsPath, ApiKey anthropicApiKey, String anthropicVersion,
RestClient.Builder restClientBuilder, WebClient.Builder webClientBuilder,
ResponseErrorHandler responseErrorHandler, String anthropicBetaFeatures) {

Consumer<HttpHeaders> jsonContentHeaders = headers -> {
headers.add(HEADER_X_API_KEY, anthropicApiKey);
headers.add(HEADER_ANTHROPIC_VERSION, anthropicVersion);
headers.add(HEADER_ANTHROPIC_BETA, anthropicBetaFeatures);
headers.setContentType(MediaType.APPLICATION_JSON);
};

this.completionsPath = completionsPath;
this.apiKey = anthropicApiKey;

this.restClient = restClientBuilder.clone()
.baseUrl(baseUrl)
Expand Down Expand Up @@ -160,12 +164,17 @@ public ResponseEntity<ChatCompletionResponse> chatCompletionEntity(ChatCompletio
Assert.isTrue(!chatRequest.stream(), "Request must set the stream property to false.");
Assert.notNull(additionalHttpHeader, "The additional HTTP headers can not be null.");

// @formatter:off
return this.restClient.post()
.uri(this.completionsPath)
.headers(headers -> headers.addAll(additionalHttpHeader))
.headers(headers -> {
headers.addAll(additionalHttpHeader);
addDefaultHeadersIfMissing(headers);
})
.body(chatRequest)
.retrieve()
.toEntity(ChatCompletionResponse.class);
// @formatter:on
}

/**
Expand Down Expand Up @@ -196,9 +205,13 @@ public Flux<ChatCompletionResponse> chatCompletionStream(ChatCompletionRequest c

AtomicReference<ChatCompletionResponseBuilder> chatCompletionReference = new AtomicReference<>();

// @formatter:off
return this.webClient.post()
.uri(this.completionsPath)
.headers(headers -> headers.addAll(additionalHttpHeader))
.headers(headers -> {
headers.addAll(additionalHttpHeader);
addDefaultHeadersIfMissing(headers);
}) // @formatter:off
.body(Mono.just(chatRequest), ChatCompletionRequest.class)
.retrieve()
.bodyToFlux(String.class)
Expand Down Expand Up @@ -232,6 +245,15 @@ public Flux<ChatCompletionResponse> chatCompletionStream(ChatCompletionRequest c
.filter(chatCompletionResponse -> chatCompletionResponse.type() != null);
}

private void addDefaultHeadersIfMissing(HttpHeaders headers) {
if (!headers.containsKey(HEADER_X_API_KEY)) {
String apiKeyValue = this.apiKey.getValue();
if (StringUtils.hasText(apiKeyValue)) {
headers.add(HEADER_X_API_KEY, apiKeyValue);
}
}
}

/**
* Check the <a href="https://docs.anthropic.com/claude/docs/models-overview">Models
* overview</a> and <a href=
Expand Down Expand Up @@ -1339,7 +1361,7 @@ public static class Builder {

private String completionsPath = DEFAULT_MESSAGE_COMPLETIONS_PATH;

private String apiKey;
private ApiKey apiKey;

private String anthropicVersion = DEFAULT_ANTHROPIC_VERSION;

Expand All @@ -1363,12 +1385,18 @@ public Builder completionsPath(String completionsPath) {
return this;
}

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

public Builder apiKey(String simpleApiKey) {
Assert.notNull(simpleApiKey, "simpleApiKey cannot be null");
this.apiKey = new SimpleApiKey(simpleApiKey);
return this;
}

public Builder anthropicVersion(String anthropicVersion) {
Assert.notNull(anthropicVersion, "anthropicVersion cannot be null");
this.anthropicVersion = anthropicVersion;
Expand Down
Loading