Bedrock Anthropic Options Support
This commit is contained in:
@@ -1,12 +1,91 @@
|
||||
# 1. Bedrock Anthropic
|
||||
# Bedrock Anthropic
|
||||
|
||||
Provides Bedrock Anthropic Chat API and Spring-AI chat clients.
|
||||
|
||||
## 1.1 AnthropicChatBedrockApi
|
||||
## BedrockAnthropicChatClient
|
||||
|
||||
The [BedrockAnthropicChatClient](./src/main/java/org/springframework/ai/bedrock/anthropic/BedrockAnthropicChatClient.java) implements the `ChatClient` and `StreamingChatClient` and uses the `AnthropicChatBedrockApi` library to connect to the Bedrock Anthropic service.
|
||||
|
||||
Add the `spring-ai-` dependency to your project's Maven `pom.xml` file:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bedrock</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
or to your Gradle `build.gradle` build file.
|
||||
|
||||
```gradle
|
||||
dependencies {
|
||||
implementation 'org.springframework.ai:spring-ai-bedrock:0.8.0-SNAPSHOT'
|
||||
}
|
||||
```
|
||||
|
||||
Next, create an `BedrockAnthropicChatClient` instance and use it to text generations requests:
|
||||
|
||||
```java
|
||||
AnthropicChatBedrockApi anthropicApi = new AnthropicChatBedrockApi(
|
||||
AnthropicChatBedrockApi.AnthropicModel.CLAUDE_V2.id(),
|
||||
EnvironmentVariableCredentialsProvider.create(),
|
||||
Region.EU_CENTRAL_1.id(),
|
||||
new ObjectMapper());
|
||||
|
||||
BedrockAnthropicChatClient chatClient = new BedrockAnthropicChatClient(anthropicApi,
|
||||
AnthropicChatOptions.builder()
|
||||
.withTemperature(0.6f)
|
||||
.withTopK(10)
|
||||
.withTopP(0.8f)
|
||||
.withMaxTokensToSample(100)
|
||||
.withAnthropicVersion(AnthropicChatBedrockApi.DEFAULT_ANTHROPIC_VERSION)
|
||||
.build());
|
||||
|
||||
ChatResponse response = chatClient.call(
|
||||
new Prompt("Generate the names of 5 famous pirates."));
|
||||
|
||||
// Or with streaming responses
|
||||
Flux<ChatResponse> response = chatClient.stream(
|
||||
new Prompt("Generate the names of 5 famous pirates."));
|
||||
```
|
||||
|
||||
or you can leverage the `spring-ai-bedrock-ai-spring-boot-starter` Spring Boot starter:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bedrock-ai-spring-boot-starter</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
And set `spring.ai.bedrock.anthropic.chat.enabled=true`.
|
||||
By default the client is disabled.
|
||||
|
||||
Use the `BedrockAnthropicChatProperties` to configure the Bedrock Anthropic Chat client:
|
||||
|
||||
| Property | Description | Default |
|
||||
| ------------- | ------------- | ------------- |
|
||||
| spring.ai.bedrock.aws.region | AWS region to use. | us-east-1 |
|
||||
| spring.ai.bedrock.aws.accessKey | AWS credentials access key. | |
|
||||
| spring.ai.bedrock.aws.secretKey | AWS credentials secret key. | |
|
||||
| spring.ai.bedrock.anthropic.chat.enable | Enable Bedrock Anthropic chat client. Disabled by default | false |
|
||||
| spring.ai.bedrock.anthropic.chat.model | The model id to use. See the `AnthropicChatModel` for the supported models. | anthropic.claude-v2 |
|
||||
| spring.ai.bedrock.anthropic.chat.options.temperature | Controls the randomness of the output. Values can range over [0.0,1.0] | 0.8 |
|
||||
| spring.ai.bedrock.anthropic.chat.options.topP | The maximum cumulative probability of tokens to consider when sampling. | AWS Bedrock default |
|
||||
| spring.ai.bedrock.anthropic.chat.options.topK | Specify the number of token choices the generative uses to generate the next token. | AWS Bedrock default |
|
||||
| spring.ai.bedrock.anthropic.chat.options.stopSequences | Configure up to four sequences that the generative recognizes. After a stop sequence, the generative stops generating further tokens. The returned text doesn't contain the stop sequence. | 10 |
|
||||
| spring.ai.bedrock.anthropic.chat.options.anthropicVersion | The version of the generative to use. | bedrock-2023-05-31 |
|
||||
| spring.ai.bedrock.anthropic.chat.options.maxTokensToSample | Specify the maximum number of tokens to use in the generated response. Note that the models may stop before reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate. We recommend a limit of 4,000 tokens for optimal performance. | 500 |
|
||||
|
||||
## Appendices
|
||||
|
||||
## Using low-level AnthropicChatBedrockApi Library
|
||||
|
||||
[AnthropicChatBedrockApi](./src/main/java/org/springframework/ai/bedrock/anthropic/api/AnthropicChatBedrockApi.java) provides is lightweight Java client on top of AWS Bedrock [Anthropic Claude models](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html).
|
||||
|
||||
Following class diagram illustrates the Llama2ChatBedrockApi interface and building blocks:
|
||||
Following class diagram illustrates the AnthropicChatBedrockApi interface and building blocks:
|
||||
|
||||

|
||||
|
||||
@@ -42,51 +121,3 @@ System.out.println(responses);
|
||||
```
|
||||
|
||||
Follow the [AnthropicChatBedrockApi.java](./src/main/java/org/springframework/ai/bedrock/anthropic/api/AnthropicChatBedrockApi.java)'s JavaDoc for further information.
|
||||
|
||||
## 1.2 BedrockAnthropicChatClient
|
||||
|
||||
[BedrockAnthropicChatClient](./src/main/java/org/springframework/ai/bedrock/anthropic/BedrockAnthropicChatClient.java) implements the Spring-Ai `ChatClient` and `StreamingChatClient` on top of the `AnthropicChatBedrockApi`.
|
||||
|
||||
You can use like this:
|
||||
|
||||
```java
|
||||
@Bean
|
||||
public AnthropicChatBedrockApi anthropicApi() {
|
||||
return new AnthropicChatBedrockApi(
|
||||
AnthropicChatBedrockApi.AnthropicModel.CLAUDE_V2.id(),
|
||||
EnvironmentVariableCredentialsProvider.create(),
|
||||
Region.EU_CENTRAL_1.id(),
|
||||
new ObjectMapper());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BedrockAnthropicChatClient anthropicChatClient(AnthropicChatBedrockApi anthropicApi) {
|
||||
return new BedrockAnthropicChatClient(anthropicApi);
|
||||
}
|
||||
```
|
||||
|
||||
or you can leverage the `spring-ai-bedrock-ai-spring-boot-starter` Spring Boot starter:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<artifactId>spring-ai-bedrock-ai-spring-boot-starter</artifactId>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
And set `spring.ai.bedrock.anthropic.chat.enabled=true`.
|
||||
By default the client is disabled.
|
||||
|
||||
Use the `BedrockAnthropicChatProperties` to configure the Bedrock Llama2 Chat client:
|
||||
|
||||
| Property | Description | Default |
|
||||
| ------------- | ------------- | ------------- |
|
||||
| spring.ai.bedrock.aws.region | AWS region to use. | us-east-1 |
|
||||
| spring.ai.bedrock.aws.accessKey | AWS credentials access key. | |
|
||||
| spring.ai.bedrock.aws.secretKey | AWS credentials secret key. | |
|
||||
| spring.ai.bedrock.anthropic.chat.enable | Enable Bedrock Llama2 chat client. Disabled by default | false |
|
||||
| spring.ai.bedrock.anthropic.chat.temperature | Controls the randomness of the output. Values can range over [0.0,1.0] | 0.8 |
|
||||
| spring.ai.bedrock.anthropic.chat.topP | The maximum cumulative probability of tokens to consider when sampling. | AWS Bedrock default |
|
||||
| spring.ai.bedrock.anthropic.chat.maxGenLen | Specify the maximum number of tokens to use in the generated response. | 300 |
|
||||
| spring.ai.bedrock.anthropic.chat.model | The model id to use. See the `Llama2ChatModel` for the supported models. | meta.llama2-70b-chat-v1 |
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
* Copyright 2024-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.bedrock.anthropic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
|
||||
import org.springframework.ai.chat.ChatOptions;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
*/
|
||||
@JsonInclude(Include.NON_NULL)
|
||||
public class AnthropicChatOptions implements ChatOptions {
|
||||
|
||||
// @formatter:off
|
||||
/**
|
||||
* Controls the randomness of the output. Values can range over [0.0,1.0], inclusive. A value closer to 1.0 will
|
||||
* produce responses that are more varied, while a value closer to 0.0 will typically result in less surprising
|
||||
* responses from the generative. This value specifies default to be used by the backend while making the call to
|
||||
* the generative.
|
||||
*/
|
||||
private @JsonProperty("temperature") Float temperature;
|
||||
|
||||
/**
|
||||
* Specify the maximum number of tokens to use in the generated response. Note that the models may stop before
|
||||
* reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate. We
|
||||
* recommend a limit of 4,000 tokens for optimal performance.
|
||||
*/
|
||||
private @JsonProperty("max_tokens_to_sample") Integer maxTokensToSample;
|
||||
|
||||
/**
|
||||
* Specify the number of token choices the generative uses to generate the next token.
|
||||
*/
|
||||
private @JsonProperty("top_k") Integer topK;
|
||||
|
||||
/**
|
||||
* The maximum cumulative probability of tokens to consider when sampling. The generative uses combined Top-k and
|
||||
* nucleus sampling. Nucleus sampling considers the smallest set of tokens whose probability sum is at least topP.
|
||||
*/
|
||||
private @JsonProperty("top_p") Float topP;
|
||||
|
||||
/**
|
||||
* Configure up to four sequences that the generative recognizes. After a stop sequence, the generative stops
|
||||
* generating further tokens. The returned text doesn't contain the stop sequence.
|
||||
*/
|
||||
private @JsonProperty("stop_sequences") List<String> stopSequences;
|
||||
|
||||
/**
|
||||
* The version of the generative to use. The default value is bedrock-2023-05-31.
|
||||
*/
|
||||
private @JsonProperty("anthropic_version") String anthropicVersion;
|
||||
// @formatter:on
|
||||
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
|
||||
private final AnthropicChatOptions options = new AnthropicChatOptions();
|
||||
|
||||
public Builder withTemperature(Float temperature) {
|
||||
this.options.setTemperature(temperature);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withMaxTokensToSample(Integer maxTokensToSample) {
|
||||
this.options.setMaxTokensToSample(maxTokensToSample);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withTopK(Integer topK) {
|
||||
this.options.setTopK(topK);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withTopP(Float topP) {
|
||||
this.options.setTopP(topP);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withStopSequences(List<String> stopSequences) {
|
||||
this.options.setStopSequences(stopSequences);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withAnthropicVersion(String anthropicVersion) {
|
||||
this.options.setAnthropicVersion(anthropicVersion);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AnthropicChatOptions build() {
|
||||
return this.options;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Float getTemperature() {
|
||||
return this.temperature;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTemperature(Float temperature) {
|
||||
this.temperature = temperature;
|
||||
}
|
||||
|
||||
public Integer getMaxTokensToSample() {
|
||||
return this.maxTokensToSample;
|
||||
}
|
||||
|
||||
public void setMaxTokensToSample(Integer maxTokensToSample) {
|
||||
this.maxTokensToSample = maxTokensToSample;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getTopK() {
|
||||
return this.topK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTopK(Integer topK) {
|
||||
this.topK = topK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Float getTopP() {
|
||||
return this.topP;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTopP(Float topP) {
|
||||
this.topP = topP;
|
||||
}
|
||||
|
||||
public List<String> getStopSequences() {
|
||||
return this.stopSequences;
|
||||
}
|
||||
|
||||
public void setStopSequences(List<String> stopSequences) {
|
||||
this.stopSequences = stopSequences;
|
||||
}
|
||||
|
||||
public String getAnthropicVersion() {
|
||||
return this.anthropicVersion;
|
||||
}
|
||||
|
||||
public void setAnthropicVersion(String anthropicVersion) {
|
||||
this.anthropicVersion = anthropicVersion;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -19,6 +19,7 @@ package org.springframework.ai.bedrock.anthropic;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ai.chat.ChatClient;
|
||||
import org.springframework.ai.chat.ChatOptions;
|
||||
import org.springframework.ai.chat.ChatResponse;
|
||||
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -30,6 +31,7 @@ import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.Anth
|
||||
import org.springframework.ai.chat.StreamingChatClient;
|
||||
import org.springframework.ai.chat.Generation;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.model.ModelOptionsUtils;
|
||||
|
||||
/**
|
||||
* Java {@link ChatClient} and {@link StreamingChatClient} for the Bedrock Anthropic chat
|
||||
@@ -42,64 +44,27 @@ public class BedrockAnthropicChatClient implements ChatClient, StreamingChatClie
|
||||
|
||||
private final AnthropicChatBedrockApi anthropicChatApi;
|
||||
|
||||
private Float temperature = 0.8f;
|
||||
|
||||
private Float topP;
|
||||
|
||||
private Integer maxTokensToSample = 500;
|
||||
|
||||
private Integer topK = 10;
|
||||
|
||||
private List<String> stopSequences;
|
||||
|
||||
private String anthropicVersion = AnthropicChatBedrockApi.DEFAULT_ANTHROPIC_VERSION;
|
||||
private final AnthropicChatOptions defaultOptions;
|
||||
|
||||
public BedrockAnthropicChatClient(AnthropicChatBedrockApi chatApi) {
|
||||
this(chatApi,
|
||||
AnthropicChatOptions.builder()
|
||||
.withTemperature(0.8f)
|
||||
.withMaxTokensToSample(500)
|
||||
.withTopK(10)
|
||||
.withAnthropicVersion(AnthropicChatBedrockApi.DEFAULT_ANTHROPIC_VERSION)
|
||||
.build());
|
||||
}
|
||||
|
||||
public BedrockAnthropicChatClient(AnthropicChatBedrockApi chatApi, AnthropicChatOptions options) {
|
||||
this.anthropicChatApi = chatApi;
|
||||
}
|
||||
|
||||
public BedrockAnthropicChatClient withTemperature(Float temperature) {
|
||||
this.temperature = temperature;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BedrockAnthropicChatClient withMaxTokensToSample(Integer maxTokensToSample) {
|
||||
this.maxTokensToSample = maxTokensToSample;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BedrockAnthropicChatClient withTopK(Integer topK) {
|
||||
this.topK = topK;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BedrockAnthropicChatClient withTopP(Float tpoP) {
|
||||
this.topP = tpoP;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BedrockAnthropicChatClient withStopSequences(List<String> stopSequences) {
|
||||
this.stopSequences = stopSequences;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BedrockAnthropicChatClient withAnthropicVersion(String anthropicVersion) {
|
||||
this.anthropicVersion = anthropicVersion;
|
||||
return this;
|
||||
this.defaultOptions = options;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatResponse call(Prompt prompt) {
|
||||
final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions());
|
||||
|
||||
AnthropicChatRequest request = AnthropicChatRequest.builder(promptValue)
|
||||
.withTemperature(this.temperature)
|
||||
.withMaxTokensToSample(this.maxTokensToSample)
|
||||
.withTopK(this.topK)
|
||||
.withTopP(this.topP)
|
||||
.withStopSequences(this.stopSequences)
|
||||
.withAnthropicVersion(this.anthropicVersion)
|
||||
.build();
|
||||
AnthropicChatRequest request = createRequest(prompt);
|
||||
|
||||
AnthropicChatResponse response = this.anthropicChatApi.chatCompletion(request);
|
||||
|
||||
@@ -109,16 +74,7 @@ public class BedrockAnthropicChatClient implements ChatClient, StreamingChatClie
|
||||
@Override
|
||||
public Flux<ChatResponse> stream(Prompt prompt) {
|
||||
|
||||
final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions());
|
||||
|
||||
AnthropicChatRequest request = AnthropicChatRequest.builder(promptValue)
|
||||
.withTemperature(this.temperature)
|
||||
.withMaxTokensToSample(this.maxTokensToSample)
|
||||
.withTopK(this.topK)
|
||||
.withTopP(this.topP)
|
||||
.withStopSequences(this.stopSequences)
|
||||
.withAnthropicVersion(this.anthropicVersion)
|
||||
.build();
|
||||
AnthropicChatRequest request = createRequest(prompt);
|
||||
|
||||
Flux<AnthropicChatResponse> fluxResponse = this.anthropicChatApi.chatCompletionStream(request);
|
||||
|
||||
@@ -133,4 +89,32 @@ public class BedrockAnthropicChatClient implements ChatClient, StreamingChatClie
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessible for testing.
|
||||
*/
|
||||
AnthropicChatRequest createRequest(Prompt prompt) {
|
||||
|
||||
final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions());
|
||||
|
||||
AnthropicChatRequest request = AnthropicChatRequest.builder(promptValue).build();
|
||||
|
||||
if (this.defaultOptions != null) {
|
||||
request = ModelOptionsUtils.merge(request, this.defaultOptions, AnthropicChatRequest.class);
|
||||
}
|
||||
|
||||
if (prompt.getOptions() != null) {
|
||||
if (prompt.getOptions() instanceof ChatOptions runtimeOptions) {
|
||||
AnthropicChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions,
|
||||
ChatOptions.class, AnthropicChatOptions.class);
|
||||
request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, AnthropicChatRequest.class);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Prompt options are not of type ChatOptions: "
|
||||
+ prompt.getOptions().getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2023-2023 the original author or authors.
|
||||
* 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.
|
||||
@@ -32,6 +32,7 @@ import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
* @since 0.8.0
|
||||
*/
|
||||
// @formatter:off
|
||||
public class AnthropicChatBedrockApi extends
|
||||
@@ -110,12 +111,13 @@ public class AnthropicChatBedrockApi extends
|
||||
|
||||
public static class Builder {
|
||||
private final String prompt;
|
||||
private Float temperature = 0.7f;
|
||||
private Integer maxTokensToSample = 500;
|
||||
private Integer topK = 10;
|
||||
private Float temperature;// = 0.7f;
|
||||
private Integer maxTokensToSample;// = 500;
|
||||
private Integer topK;// = 10;
|
||||
private Float topP;
|
||||
private List<String> stopSequences;
|
||||
private String anthropicVersion = DEFAULT_ANTHROPIC_VERSION;
|
||||
// private String anthropicVersion = DEFAULT_ANTHROPIC_VERSION;
|
||||
private String anthropicVersion;
|
||||
|
||||
private Builder(String prompt) {
|
||||
this.prompt = prompt;
|
||||
|
||||
@@ -8,6 +8,9 @@ import java.util.stream.Collectors;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import org.springframework.ai.chat.ChatResponse;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
|
||||
@@ -38,6 +41,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
|
||||
class BedrockAnthropicChatClientIT {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BedrockAnthropicChatClientIT.class);
|
||||
|
||||
@Autowired
|
||||
private BedrockAnthropicChatClient client;
|
||||
|
||||
@@ -145,7 +150,7 @@ class BedrockAnthropicChatClientIT {
|
||||
.collect(Collectors.joining());
|
||||
|
||||
ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream);
|
||||
System.out.println(actorsFilms);
|
||||
logger.info("" + actorsFilms);
|
||||
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
|
||||
assertThat(actorsFilms.movies()).hasSize(5);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Copyright 2024-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.bedrock.anthropic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
|
||||
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi;
|
||||
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
*/
|
||||
public class BedrockAnthropicCreateRequestTests {
|
||||
|
||||
private AnthropicChatBedrockApi anthropicChatApi = new AnthropicChatBedrockApi(AnthropicChatModel.CLAUDE_V2.id(),
|
||||
Region.EU_CENTRAL_1.id());
|
||||
|
||||
@Test
|
||||
public void createRequestWithChatOptions() {
|
||||
|
||||
var client = new BedrockAnthropicChatClient(anthropicChatApi,
|
||||
AnthropicChatOptions.builder()
|
||||
.withTemperature(66.6f)
|
||||
.withTopK(66)
|
||||
.withTopP(0.66f)
|
||||
.withMaxTokensToSample(666)
|
||||
.withAnthropicVersion("X.Y.Z")
|
||||
.withStopSequences(List.of("stop1", "stop2"))
|
||||
.build());
|
||||
|
||||
var request = client.createRequest(new Prompt("Test message content"));
|
||||
|
||||
assertThat(request.prompt()).isNotEmpty();
|
||||
assertThat(request.temperature()).isEqualTo(66.6f);
|
||||
assertThat(request.topK()).isEqualTo(66);
|
||||
assertThat(request.topP()).isEqualTo(0.66f);
|
||||
assertThat(request.maxTokensToSample()).isEqualTo(666);
|
||||
assertThat(request.anthropicVersion()).isEqualTo("X.Y.Z");
|
||||
assertThat(request.stopSequences()).containsExactly("stop1", "stop2");
|
||||
|
||||
request = client.createRequest(new Prompt("Test message content",
|
||||
AnthropicChatOptions.builder()
|
||||
.withTemperature(99.9f)
|
||||
.withTopP(0.99f)
|
||||
.withMaxTokensToSample(999)
|
||||
.withAnthropicVersion("zzz")
|
||||
.withStopSequences(List.of("stop3", "stop4"))
|
||||
.build()
|
||||
|
||||
));
|
||||
|
||||
assertThat(request.prompt()).isNotEmpty();
|
||||
assertThat(request.temperature()).isEqualTo(99.9f);
|
||||
assertThat(request.topK()).as("unchanged from the default options").isEqualTo(66);
|
||||
assertThat(request.topP()).isEqualTo(0.99f);
|
||||
assertThat(request.maxTokensToSample()).isEqualTo(999);
|
||||
assertThat(request.anthropicVersion()).isEqualTo("zzz");
|
||||
assertThat(request.stopSequences()).containsExactly("stop3", "stop4");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,6 +21,8 @@ import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.Flux;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
|
||||
@@ -37,6 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat;;
|
||||
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
|
||||
public class AnthropicChatBedrockApiIT {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(AnthropicChatBedrockApiIT.class);
|
||||
|
||||
private AnthropicChatBedrockApi anthropicChatApi = new AnthropicChatBedrockApi(AnthropicChatModel.CLAUDE_V2.id(),
|
||||
Region.EU_CENTRAL_1.id());
|
||||
|
||||
@@ -60,7 +64,7 @@ public class AnthropicChatBedrockApiIT {
|
||||
assertThat(response.stop()).isEqualTo("\n\nHuman:");
|
||||
assertThat(response.amazonBedrockInvocationMetrics()).isNull();
|
||||
|
||||
System.out.println(response);
|
||||
logger.info("" + response);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -7,6 +7,8 @@ import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import org.springframework.ai.chat.ChatResponse;
|
||||
import org.springframework.ai.chat.Generation;
|
||||
@@ -32,6 +34,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+")
|
||||
class OpenAiChatClientIT extends AbstractIT {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OpenAiChatClientIT.class);
|
||||
|
||||
@Value("classpath:/prompts/system-message.st")
|
||||
private Resource systemResource;
|
||||
|
||||
@@ -122,7 +126,7 @@ class OpenAiChatClientIT extends AbstractIT {
|
||||
Generation generation = openAiChatClient.call(prompt).getResult();
|
||||
|
||||
ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent());
|
||||
System.out.println(actorsFilms);
|
||||
logger.info("" + actorsFilms);
|
||||
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
|
||||
assertThat(actorsFilms.movies()).hasSize(5);
|
||||
}
|
||||
@@ -151,7 +155,7 @@ class OpenAiChatClientIT extends AbstractIT {
|
||||
.collect(Collectors.joining());
|
||||
|
||||
ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream);
|
||||
System.out.println(actorsFilms);
|
||||
logger.info("" + actorsFilms);
|
||||
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
|
||||
assertThat(actorsFilms.movies()).hasSize(5);
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 170 KiB |
@@ -6,6 +6,7 @@
|
||||
*** xref:api/clients/openai-chat.adoc[]
|
||||
*** xref:api/clients/azure-openai-chat.adoc[]
|
||||
*** xref:api/clients/bedrock.adoc[]
|
||||
**** xref:api/clients/bedrock/bedrock-anthropic.adoc[]
|
||||
*** xref:api/clients/huggingface.adoc[]
|
||||
*** xref:api/clients/ollama-chat.adoc[]
|
||||
** xref:api/prompt.adoc[]
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
= Amazon Bedrock Anthropic
|
||||
|
||||
https://www.anthropic.com/product[Anthropic's Claude] is an AI assistant based on Anthropic’s research into training helpful, honest, and harmless AI systems.
|
||||
|
||||
The Claude model has the following high level features
|
||||
|
||||
* 200k Token Context Window: Claude boasts a generous token capacity of 200,000, making it ideal for handling extensive information in applications like technical documentation, codebases, and literary works.
|
||||
* Supported Tasks: Claude's versatility spans tasks such as summarization, Q&A, trend forecasting, and document comparisons, enabling a wide range of applications from dialogues to content generation.
|
||||
* AI Safety Features: Built on Anthropic's safety research, Claude prioritizes helpfulness, honesty, and harmlessness in its interactions, reducing brand risk and ensuring responsible AI behavior.
|
||||
|
||||
The https://aws.amazon.com/bedrock/claude[AWS Bedrock Anthropic Model Page] and https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html[Amazon Bedrock User Guide] contains detailed information on how to use the AWS hosted model.
|
||||
|
||||
== Getting Started
|
||||
|
||||
Refer to the xref:api/clients/bedrock.adoc[Spring AI documentation on Amazon Bedrock] for setting up API access.
|
||||
|
||||
== Project Dependencies
|
||||
|
||||
Refer to the xref:getting-started.adoc#_dependency_management[Dependency Management] section to add Milestone and/or Snapshot Repositories to your build file.
|
||||
|
||||
Then add the Spring Boot Starter dependency to your project's Maven `pom.xml` build file:
|
||||
|
||||
[source, xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bedrock-ai-spring-boot-starter</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
or to your Gradle `build.gradle` build file.
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
dependencies {
|
||||
implementation 'org.springframework.ai:spring-ai-bedrock-ai-spring-boot-starter:0.8.0-SNAPSHOT'
|
||||
}
|
||||
----
|
||||
|
||||
== Enable Anthropic Support
|
||||
|
||||
Spring AI defines a configuration property named `spring.ai.bedrock.llama2.chat.enabled` that you should set to `true` to enable support for Llama2.
|
||||
|
||||
Exporting environment variables in one way to set this configuration property.
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
export SPRING_AI_BEDROCK_LLAMA2_CHAT_ENABLED=true
|
||||
----
|
||||
|
||||
== Sample Code
|
||||
|
||||
This will create a `ChatClient` implementation that you can inject into your class.
|
||||
Here is an example of a simple `@Controller` class that uses the `ChatClient` implementation.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@RestController
|
||||
public class ChatController {
|
||||
|
||||
private final ChatClient chatClient;
|
||||
|
||||
@Autowired
|
||||
public ChatController(ChatClient chatClient) {
|
||||
this.chatClient = chatClient;
|
||||
}
|
||||
|
||||
@GetMapping("/ai/generate")
|
||||
public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
|
||||
return Map.of("generation", chatClient.generate(message));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
== Bedrock Properties
|
||||
|
||||
The prefix `spring.ai.bedrock.aws` is the property prefix to configure the connection to AWS Bedrock.
|
||||
|
||||
|
||||
[cols="3,3,3"]
|
||||
|====
|
||||
| Property | Description | Default
|
||||
|
||||
| spring.ai.bedrock.aws.region | AWS region to use. | us-east-1
|
||||
| spring.ai.bedrock.aws.access-key | AWS access key. | -
|
||||
| spring.ai.bedrock.aws.secret-key | AWS secret key. | -
|
||||
|====
|
||||
|
||||
|
||||
The prefix `spring.ai.bedrock.anthropic.chat` is the property prefix that configures the `ChatClient` implementation for Claude.
|
||||
|
||||
[cols="8,4,3"]
|
||||
|====
|
||||
| Property | Description | Default
|
||||
|
||||
| spring.ai.bedrock.anthropic.chat.enabled | Enable or disable support for Anthropic | false
|
||||
| spring.ai.bedrock.anthropic.chat.model | The model id to use (See Below) | anthropic.claude-v2
|
||||
| spring.ai.bedrock.anthropic.chat.anthropic-version | The version of the model to use | bedrock-2023-05-31
|
||||
| spring.ai.bedrock.anthropic.chat.temperature | Controls the randomness of the output. Values can range over [0.0,1.0], inclusive. A value closer to 1.0 will produce responses that are more varied, while a value closer to 0.0 will typically result in less surprising responses from the model. This value specifies default to be used by the backend while making the call to the model.| 0.7
|
||||
| spring.ai.bedrock.anthropic.chat.top-p | The maximum cumulative probability of tokens to consider when sampling. The model uses combined Top-k and nucleus sampling. Nucleus sampling considers the smallest set of tokens whose probability sum is at least topP.| AWS Bedrock default
|
||||
| spring.ai.bedrock.anthropic.chat.max-tokens-to-sample | Specify the maximum number of tokens to use in the generated response. Note that the models may stop before reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate. We recommend a limit of 4,000 tokens for optimal performance. | 300
|
||||
| spring.ai.bedrock.anthropic.chat.top-k | Specify the number of token choices the model uses to generate the next token. | 10
|
||||
| spring.ai.bedrock.anthropic.chat.stop-sequences | Configure up to four sequences that the model recognizes. After a stop sequence, the model stops generating further tokens. The returned text doesn't contain the stop sequence. | "\n\Human:"
|
||||
|====
|
||||
|
||||
Look at the Spring AI enumeration `AnthropicChatModel` for other model IDs. The other value supported is `anthropic.claude-instant-v1`.
|
||||
|
||||
Model ID values can also be found in the https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids-arns.html[AWS Bedrock documentation for base model IDs].
|
||||
@@ -84,7 +84,7 @@ Next, you can use the `spring.ai.bedrock.<model>.<chat|embedding>.*` properties
|
||||
|
||||
For more information, refer to the documentation below for each supported model.
|
||||
|
||||
* xref:api/clients/bedrock-anthropic.adoc[Spring AI Bedrock Anthropic Chat]: `spring.ai.bedrock.anthropic.chat.enabled=true`
|
||||
* xref:api/clients/bedrock/bedrock-anthropic.adoc[Spring AI Bedrock Anthropic Chat]: `spring.ai.bedrock.anthropic.chat.enabled=true`
|
||||
* xref:api/clients/bedrock-llama2.adoc[Spring AI Bedrock Llama2 Chat]: `spring.ai.bedrock.llama2.chat.enabled=true`
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
= Bedrock Anthropic Chat Client
|
||||
|
||||
https://www.anthropic.com/product[Anthropic's Claude] is an AI assistant based on Anthropic’s research into training helpful, honest, and harmless AI systems.
|
||||
|
||||
The Claude model has the following high level features
|
||||
|
||||
* 200k Token Context Window: Claude boasts a generous token capacity of 200,000, making it ideal for handling extensive information in applications like technical documentation, codebases, and literary works.
|
||||
* Supported Tasks: Claude's versatility spans tasks such as summarization, Q&A, trend forecasting, and document comparisons, enabling a wide range of applications from dialogues to content generation.
|
||||
* AI Safety Features: Built on Anthropic's safety research, Claude prioritizes helpfulness, honesty, and harmlessness in its interactions, reducing brand risk and ensuring responsible AI behavior.
|
||||
|
||||
The https://aws.amazon.com/bedrock/claude[AWS Bedrock Anthropic Model Page] and https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html[Amazon Bedrock User Guide] contains detailed information on how to use the AWS hosted model.
|
||||
|
||||
== Getting Started
|
||||
|
||||
Refer to the xref:api/clients/bedrock.adoc[Spring AI documentation on Amazon Bedrock] for setting up API access.
|
||||
|
||||
The link:./src/main/java/org/springframework/ai/bedrock/anthropic/BedrockAnthropicChatClient.java[BedrockAnthropicChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the `AnthropicChatBedrockApi` library to connect to the Bedrock Anthropic service.
|
||||
|
||||
Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bedrock</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
or to your Gradle `build.gradle` build file.
|
||||
|
||||
[source,gradle]
|
||||
----
|
||||
dependencies {
|
||||
implementation 'org.springframework.ai:spring-ai-bedrock:0.8.0-SNAPSHOT'
|
||||
}
|
||||
----
|
||||
|
||||
NOTE: Refer to the xref:getting-started.adoc#_dependency_management[Dependency Management] section to add Milestone and/or Snapshot Repositories to your build file.
|
||||
|
||||
Next, create an `BedrockAnthropicChatClient` instance and use it to text generations requests:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
AnthropicChatBedrockApi anthropicApi = new AnthropicChatBedrockApi(
|
||||
AnthropicChatBedrockApi.AnthropicModel.CLAUDE_V2.id(),
|
||||
EnvironmentVariableCredentialsProvider.create(),
|
||||
Region.EU_CENTRAL_1.id(),
|
||||
new ObjectMapper());
|
||||
|
||||
BedrockAnthropicChatClient chatClient = new BedrockAnthropicChatClient(anthropicApi,
|
||||
AnthropicChatOptions.builder()
|
||||
.withTemperature(0.6f)
|
||||
.withTopK(10)
|
||||
.withTopP(0.8f)
|
||||
.withMaxTokensToSample(100)
|
||||
.withAnthropicVersion(AnthropicChatBedrockApi.DEFAULT_ANTHROPIC_VERSION)
|
||||
.build());
|
||||
|
||||
ChatResponse response = chatClient.call(
|
||||
new Prompt("Generate the names of 5 famous pirates."));
|
||||
|
||||
// Or with streaming responses
|
||||
Flux<ChatResponse> response = chatClient.stream(
|
||||
new Prompt("Generate the names of 5 famous pirates."));
|
||||
----
|
||||
|
||||
=== AnthropicChatClient Auto-configuration
|
||||
|
||||
or you can leverage the `spring-ai-bedrock-ai-spring-boot-starter` Spring Boot starter:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.ai</groupId>
|
||||
<artifactId>spring-ai-bedrock-ai-spring-boot-starter</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
==== Enable Anthropic Support
|
||||
|
||||
Spring AI defines a configuration property named `spring.ai.bedrock.anthropic.chat.enabled` that you should set to `true` to enable support for Anthropic.
|
||||
|
||||
Exporting environment variables in one way to set this configuration property.
|
||||
|
||||
[source,shell]
|
||||
----
|
||||
export SPRING_AI_BEDROCK_ANTHROPIC_CHAT_ENABLED=true
|
||||
----
|
||||
|
||||
==== Sample Code
|
||||
|
||||
This will create a `ChatClient` implementation that you can inject into your class.
|
||||
|
||||
Create an `application.properties` file in the `src/main/resources` directory and add the following properties to configure the Anthropic Chat client.
|
||||
|
||||
[source]
|
||||
----
|
||||
spring.ai.bedrock.anthropic.chat.enabled=true
|
||||
spring.ai.bedrock.anthropic.chat.options.temperature=0.8
|
||||
----
|
||||
|
||||
Here is an example of a simple `@Controller` class that uses the `ChatClient` implementation.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@RestController
|
||||
public class ChatController {
|
||||
|
||||
private final ChatClient chatClient;
|
||||
|
||||
@Autowired
|
||||
public ChatController(ChatClient chatClient) {
|
||||
this.chatClient = chatClient;
|
||||
}
|
||||
|
||||
@GetMapping("/ai/generate")
|
||||
public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
|
||||
return Map.of("generation", chatClient.generate(message));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
==== Bedrock Properties
|
||||
|
||||
The prefix `spring.ai.bedrock.aws` is the property prefix to configure the connection to AWS Bedrock.
|
||||
|
||||
[cols="3,3,1"]
|
||||
|====
|
||||
| Property | Description | Default
|
||||
|
||||
| spring.ai.bedrock.aws.region | AWS region to use. | us-east-1
|
||||
| spring.ai.bedrock.aws.access-key | AWS access key. | -
|
||||
| spring.ai.bedrock.aws.secret-key | AWS secret key. | -
|
||||
|====
|
||||
|
||||
The prefix `spring.ai.bedrock.anthropic.chat` is the property prefix that configures the `ChatClient` implementation for Claude.
|
||||
|
||||
[cols="2,5,1"]
|
||||
|====
|
||||
| Property | Description | Default
|
||||
|
||||
| spring.ai.bedrock.anthropic.chat.enable | Enable Bedrock Anthropic chat client. Disabled by default | false
|
||||
| spring.ai.bedrock.anthropic.chat.model | The model id to use. See the `AnthropicChatModel` for the supported models. | anthropic.claude-v2
|
||||
| spring.ai.bedrock.anthropic.chat.options.temperature | Controls the randomness of the output. Values can range over [0.0,1.0] | 0.8
|
||||
| spring.ai.bedrock.anthropic.chat.options.topP | The maximum cumulative probability of tokens to consider when sampling. | AWS Bedrock default
|
||||
| spring.ai.bedrock.anthropic.chat.options.topK | Specify the number of token choices the generative uses to generate the next token. | AWS Bedrock default
|
||||
| spring.ai.bedrock.anthropic.chat.options.stopSequences | Configure up to four sequences that the generative recognizes. After a stop sequence, the generative stops generating further tokens. The returned text doesn't contain the stop sequence. | 10
|
||||
| spring.ai.bedrock.anthropic.chat.options.anthropicVersion | The version of the generative to use. | bedrock-2023-05-31
|
||||
| spring.ai.bedrock.anthropic.chat.options.maxTokensToSample | Specify the maximum number of tokens to use in the generated response. Note that the models may stop before reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate. We recommend a limit of 4,000 tokens for optimal performance. | 500
|
||||
|====
|
||||
|
||||
Look at the Spring AI enumeration `AnthropicChatModel` for other model IDs. The other value supported is `anthropic.claude-instant-v1`.
|
||||
|
||||
Model ID values can also be found in the https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids-arns.html[AWS Bedrock documentation for base model IDs].
|
||||
|
||||
== Appendices
|
||||
|
||||
=== Using low-level AnthropicChatBedrockApi Library
|
||||
|
||||
The link:./src/main/java/org/springframework/ai/bedrock/anthropic/api/AnthropicChatBedrockApi.java[AnthropicChatBedrockApi] provides is lightweight Java client on top of AWS Bedrock link:https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html[Anthropic Claude models].
|
||||
|
||||
Following class diagram illustrates the AnthropicChatBedrockApi interface and building blocks:
|
||||
|
||||
image::bedrock/bedrock-anthropic-chat-api.png[AnthropicChatBedrockApi Class Diagram]
|
||||
|
||||
The AnthropicChatBedrockApi supports the `anthropic.claude-instant-v1` and `anthropic.claude-v2` models.
|
||||
|
||||
Also the AnthropicChatBedrockApi supports both synchronous (e.g. `chatCompletion()`) and streaming (e.g. `chatCompletionStream()`) responses.
|
||||
|
||||
Here is a simple snippet how to use the api programmatically:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
AnthropicChatBedrockApi anthropicChatApi = new AnthropicChatBedrockApi(
|
||||
AnthropicModel.CLAUDE_V2.id(),
|
||||
Region.EU_CENTRAL_1.id());
|
||||
|
||||
AnthropicChatRequest request = AnthropicChatRequest
|
||||
.builder(String.format(AnthropicChatBedrockApi.PROMPT_TEMPLATE, "Name 3 famous pirates"))
|
||||
.withTemperature(0.8f)
|
||||
.withMaxTokensToSample(300)
|
||||
.withTopK(10)
|
||||
// .withStopSequences(List.of("\n\nHuman:"))
|
||||
.build();
|
||||
|
||||
AnthropicChatResponse response = anthropicChatApi.chatCompletion(request);
|
||||
|
||||
System.out.println(response.completion());
|
||||
|
||||
// Streaming response
|
||||
Flux<AnthropicChatResponse> responseStream = anthropicChatApi.chatCompletionStream(request);
|
||||
|
||||
List<AnthropicChatResponse> responses = responseStream.collectList().block();
|
||||
|
||||
System.out.println(responses);
|
||||
----
|
||||
|
||||
Follow the link:./src/main/java/org/springframework/ai/bedrock/anthropic/api/AnthropicChatBedrockApi.java[AnthropicChatBedrockApi.java]'s JavaDoc for further information.
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2023 the original author or authors.
|
||||
* 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.
|
||||
@@ -62,12 +62,7 @@ public class BedrockAnthropicChatAutoConfiguration {
|
||||
public BedrockAnthropicChatClient anthropicChatClient(AnthropicChatBedrockApi anthropicApi,
|
||||
BedrockAnthropicChatProperties properties) {
|
||||
|
||||
return new BedrockAnthropicChatClient(anthropicApi).withTemperature(properties.getTemperature())
|
||||
.withTopP(properties.getTopP())
|
||||
.withMaxTokensToSample(properties.getMaxTokensToSample())
|
||||
.withTopK(properties.getTopK())
|
||||
.withStopSequences(properties.getStopSequences())
|
||||
.withAnthropicVersion(properties.getAnthropicVersion());
|
||||
return new BedrockAnthropicChatClient(anthropicApi, properties.getOptions());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2023 the original author or authors.
|
||||
* 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.
|
||||
@@ -18,9 +18,10 @@ package org.springframework.ai.autoconfigure.bedrock.anthropic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi;
|
||||
import org.springframework.ai.bedrock.anthropic.AnthropicChatOptions;
|
||||
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Configuration properties for Bedrock Anthropic.
|
||||
@@ -44,46 +45,12 @@ public class BedrockAnthropicChatProperties {
|
||||
*/
|
||||
private String model = AnthropicChatModel.CLAUDE_V2.id();
|
||||
|
||||
/**
|
||||
* Controls the randomness of the output. Values can range over [0.0,1.0], inclusive.
|
||||
* A value closer to 1.0 will produce responses that are more varied, while a value
|
||||
* closer to 0.0 will typically result in less surprising responses from the
|
||||
* generative. This value specifies default to be used by the backend while making the
|
||||
* call to the generative.
|
||||
*/
|
||||
private Float temperature = 0.7f;
|
||||
|
||||
/**
|
||||
* The maximum cumulative probability of tokens to consider when sampling. The
|
||||
* generative uses combined Top-k and nucleus sampling. Nucleus sampling considers the
|
||||
* smallest set of tokens whose probability sum is at least topP.
|
||||
*/
|
||||
private Float topP = null;
|
||||
|
||||
/**
|
||||
* Specify the maximum number of tokens to use in the generated response. Note that
|
||||
* the models may stop before reaching this maximum. This parameter only specifies the
|
||||
* absolute maximum number of tokens to generate. We recommend a limit of 4,000 tokens
|
||||
* for optimal performance.
|
||||
*/
|
||||
private Integer maxTokensToSample = 300;
|
||||
|
||||
/**
|
||||
* Specify the number of token choices the generative uses to generate the next token.
|
||||
*/
|
||||
private Integer topK = 10;
|
||||
|
||||
/**
|
||||
* Configure up to four sequences that the generative recognizes. After a stop
|
||||
* sequence, the generative stops generating further tokens. The returned text doesn't
|
||||
* contain the stop sequence.
|
||||
*/
|
||||
private List<String> stopSequences = List.of("\n\nHuman:");
|
||||
|
||||
/**
|
||||
* The version of the generative to use. The default value is bedrock-2023-05-31.
|
||||
*/
|
||||
private String anthropicVersion = AnthropicChatBedrockApi.DEFAULT_ANTHROPIC_VERSION;
|
||||
private AnthropicChatOptions options = AnthropicChatOptions.builder()
|
||||
.withTemperature(0.7f)
|
||||
.withMaxTokensToSample(300)
|
||||
.withTopK(10)
|
||||
.withStopSequences(List.of("\n\nHuman:"))
|
||||
.build();
|
||||
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
@@ -101,52 +68,15 @@ public class BedrockAnthropicChatProperties {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public Float getTemperature() {
|
||||
return this.temperature;
|
||||
public AnthropicChatOptions getOptions() {
|
||||
return options;
|
||||
}
|
||||
|
||||
public void setTemperature(Float temperature) {
|
||||
this.temperature = temperature;
|
||||
}
|
||||
public void setOptions(AnthropicChatOptions options) {
|
||||
Assert.notNull(options, "AnthropicChatOptions must not be null");
|
||||
Assert.notNull(options.getTemperature(), "AnthropicChatOptions.temperature must not be null");
|
||||
|
||||
public Float getTopP() {
|
||||
return this.topP;
|
||||
}
|
||||
|
||||
public void setTopP(Float topP) {
|
||||
this.topP = topP;
|
||||
}
|
||||
|
||||
public Integer getMaxTokensToSample() {
|
||||
return maxTokensToSample;
|
||||
}
|
||||
|
||||
public void setMaxTokensToSample(Integer maxTokensToSample) {
|
||||
this.maxTokensToSample = maxTokensToSample;
|
||||
}
|
||||
|
||||
public Integer getTopK() {
|
||||
return topK;
|
||||
}
|
||||
|
||||
public void setTopK(Integer topK) {
|
||||
this.topK = topK;
|
||||
}
|
||||
|
||||
public List<String> getStopSequences() {
|
||||
return stopSequences;
|
||||
}
|
||||
|
||||
public void setStopSequences(List<String> stopSequences) {
|
||||
this.stopSequences = stopSequences;
|
||||
}
|
||||
|
||||
public String getAnthropicVersion() {
|
||||
return anthropicVersion;
|
||||
}
|
||||
|
||||
public void setAnthropicVersion(String anthropicVersion) {
|
||||
this.anthropicVersion = anthropicVersion;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2023-2023 the original author or authors.
|
||||
* 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.
|
||||
@@ -52,9 +52,9 @@ public class BedrockAnthropicChatAutoConfigurationIT {
|
||||
.withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=true",
|
||||
"spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"),
|
||||
"spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"),
|
||||
"spring.ai.bedrock.anthropic.chat.model=" + AnthropicChatModel.CLAUDE_V2.id(),
|
||||
"spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(),
|
||||
"spring.ai.bedrock.anthropic.chat.temperature=0.5", "spring.ai.bedrock.anthropic.chat.maxGenLen=500")
|
||||
"spring.ai.bedrock.anthropic.chat.model=" + AnthropicChatModel.CLAUDE_V2.id(),
|
||||
"spring.ai.bedrock.anthropic.chat.options.temperature=0.5")
|
||||
.withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class));
|
||||
|
||||
private final Message systemMessage = new SystemPromptTemplate("""
|
||||
@@ -106,7 +106,7 @@ public class BedrockAnthropicChatAutoConfigurationIT {
|
||||
"spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY",
|
||||
"spring.ai.bedrock.anthropic.chat.model=MODEL_XYZ",
|
||||
"spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(),
|
||||
"spring.ai.bedrock.anthropic.chat.temperature=0.55")
|
||||
"spring.ai.bedrock.anthropic.chat.options.temperature=0.55")
|
||||
.withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class))
|
||||
.run(context -> {
|
||||
var anthropicChatProperties = context.getBean(BedrockAnthropicChatProperties.class);
|
||||
@@ -115,7 +115,7 @@ public class BedrockAnthropicChatAutoConfigurationIT {
|
||||
assertThat(anthropicChatProperties.isEnabled()).isTrue();
|
||||
assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id());
|
||||
|
||||
assertThat(anthropicChatProperties.getTemperature()).isEqualTo(0.55f);
|
||||
assertThat(anthropicChatProperties.getOptions().getTemperature()).isEqualTo(0.55f);
|
||||
assertThat(anthropicChatProperties.getModel()).isEqualTo("MODEL_XYZ");
|
||||
|
||||
assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY");
|
||||
|
||||
Reference in New Issue
Block a user