diff --git a/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClient.java b/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClient.java index d1641ca58..20c81e536 100644 --- a/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClient.java +++ b/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClient.java @@ -22,15 +22,20 @@ import org.springframework.ai.chat.ChatResponse; import reactor.core.publisher.Flux; import org.springframework.ai.bedrock.MessageToPromptConverter; +import org.springframework.ai.bedrock.anthropic.AnthropicChatOptions; +import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatRequest; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatResponse; import org.springframework.ai.chat.ChatClient; +import org.springframework.ai.chat.ChatOptions; import org.springframework.ai.chat.StreamingChatClient; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.metadata.ChatGenerationMetadata; import org.springframework.ai.chat.metadata.Usage; import org.springframework.ai.chat.prompt.Prompt; +import org.springframework.ai.model.ModelOptionsUtils; +import org.springframework.util.Assert; /** * Java {@link ChatClient} and {@link StreamingChatClient} for the Bedrock Llama2 chat @@ -43,40 +48,25 @@ public class BedrockLlama2ChatClient implements ChatClient, StreamingChatClient private final Llama2ChatBedrockApi chatApi; - private Float temperature; - - private Float topP; - - private Integer maxGenLen; + private final BedrockLlama2ChatOptions defaultOptions; public BedrockLlama2ChatClient(Llama2ChatBedrockApi chatApi) { + this(chatApi, + BedrockLlama2ChatOptions.builder().withTemperature(0.8f).withTopP(0.9f).withMaxGenLen(100).build()); + } + + public BedrockLlama2ChatClient(Llama2ChatBedrockApi chatApi, BedrockLlama2ChatOptions options) { + Assert.notNull(chatApi, "Llama2ChatBedrockApi must not be null"); + Assert.notNull(options, "BedrockLlama2ChatOptions must not be null"); + this.chatApi = chatApi; - } - - public BedrockLlama2ChatClient withTemperature(Float temperature) { - this.temperature = temperature; - return this; - } - - public BedrockLlama2ChatClient withTopP(Float topP) { - this.topP = topP; - return this; - } - - public BedrockLlama2ChatClient withMaxGenLen(Integer maxGenLen) { - this.maxGenLen = maxGenLen; - return this; + this.defaultOptions = options; } @Override public ChatResponse call(Prompt prompt) { - final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions()); - var request = Llama2ChatRequest.builder(promptValue) - .withTemperature(this.temperature) - .withTopP(this.topP) - .withMaxGenLen(this.maxGenLen) - .build(); + var request = createRequest(prompt); Llama2ChatResponse response = this.chatApi.chatCompletion(request); @@ -87,13 +77,7 @@ public class BedrockLlama2ChatClient implements ChatClient, StreamingChatClient @Override public Flux stream(Prompt prompt) { - final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions()); - - var request = Llama2ChatRequest.builder(promptValue) - .withTemperature(this.temperature) - .withTopP(this.topP) - .withMaxGenLen(this.maxGenLen) - .build(); + var request = createRequest(prompt); Flux fluxResponse = this.chatApi.chatCompletionStream(request); @@ -119,4 +103,33 @@ public class BedrockLlama2ChatClient implements ChatClient, StreamingChatClient }; } + /** + * Accessible for testing. + */ + Llama2ChatRequest createRequest(Prompt prompt) { + + final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions()); + + Llama2ChatRequest request = Llama2ChatRequest.builder(promptValue).build(); + + if (this.defaultOptions != null) { + request = ModelOptionsUtils.merge(request, this.defaultOptions, Llama2ChatRequest.class); + } + + if (prompt.getOptions() != null) { + if (prompt.getOptions() instanceof ChatOptions runtimeOptions) { + BedrockLlama2ChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions, + ChatOptions.class, BedrockLlama2ChatOptions.class); + + request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, Llama2ChatRequest.class); + } + else { + throw new IllegalArgumentException("Prompt options are not of type ChatOptions: " + + prompt.getOptions().getClass().getSimpleName()); + } + } + + return request; + } + } diff --git a/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatOptions.java b/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatOptions.java new file mode 100644 index 000000000..c968b7577 --- /dev/null +++ b/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatOptions.java @@ -0,0 +1,114 @@ +/* + * 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.llama2; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.springframework.ai.chat.ChatOptions; + +/** + * @author Christian Tzolov + */ +@JsonInclude(Include.NON_NULL) +public class BedrockLlama2ChatOptions implements ChatOptions { + + /** + * The temperature value controls the randomness of the generated text. Use a lower + * value to decrease randomness in the response. + */ + private @JsonProperty("temperature") Float temperature; + + /** + * The topP value controls the diversity of the generated text. Use a lower value to + * ignore less probable options. Set to 0 or 1.0 to disable. + */ + private @JsonProperty("top_p") Float topP; + + /** + * The maximum length of the generated text. + */ + private @JsonProperty("max_gen_len") Integer maxGenLen; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private BedrockLlama2ChatOptions options = new BedrockLlama2ChatOptions(); + + public Builder withTemperature(Float temperature) { + this.options.setTemperature(temperature); + return this; + } + + public Builder withTopP(Float topP) { + this.options.setTopP(topP); + return this; + } + + public Builder withMaxGenLen(Integer maxGenLen) { + this.options.setMaxGenLen(maxGenLen); + return this; + } + + public BedrockLlama2ChatOptions build() { + return this.options; + } + + } + + public Float getTemperature() { + return this.temperature; + } + + public void setTemperature(Float temperature) { + this.temperature = temperature; + } + + public Float getTopP() { + return this.topP; + } + + public void setTopP(Float topP) { + this.topP = topP; + } + + public Integer getMaxGenLen() { + return this.maxGenLen; + } + + public void setMaxGenLen(Integer maxGenLen) { + this.maxGenLen = maxGenLen; + } + + @Override + @JsonIgnore + public Integer getTopK() { + throw new UnsupportedOperationException("Unsupported option: 'TopK'"); + } + + @Override + @JsonIgnore + public void setTopK(Integer topK) { + throw new UnsupportedOperationException("Unsupported option: 'TopK'"); + } + +} diff --git a/models/spring-ai-bedrock/src/test/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClientIT.java b/models/spring-ai-bedrock/src/test/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClientIT.java index 951d22406..fae4991c5 100644 --- a/models/spring-ai-bedrock/src/test/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClientIT.java +++ b/models/spring-ai-bedrock/src/test/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClientIT.java @@ -166,7 +166,8 @@ class BedrockLlama2ChatClientIT { @Bean public BedrockLlama2ChatClient llama2ChatClient(Llama2ChatBedrockApi llama2Api) { - return new BedrockLlama2ChatClient(llama2Api); + return new BedrockLlama2ChatClient(llama2Api, + BedrockLlama2ChatOptions.builder().withTemperature(0.5f).withMaxGenLen(100).withTopP(0.9f).build()); } } diff --git a/models/spring-ai-bedrock/src/test/java/org/springframework/ai/bedrock/llama2/BedrockLlama2CreateRequestTests.java b/models/spring-ai-bedrock/src/test/java/org/springframework/ai/bedrock/llama2/BedrockLlama2CreateRequestTests.java new file mode 100644 index 000000000..20e7ec1b0 --- /dev/null +++ b/models/spring-ai-bedrock/src/test/java/org/springframework/ai/bedrock/llama2/BedrockLlama2CreateRequestTests.java @@ -0,0 +1,60 @@ +/* + * 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.llama2; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import software.amazon.awssdk.regions.Region; + +import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi; +import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel; +import org.springframework.ai.chat.prompt.Prompt; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Christian Tzolov + */ +public class BedrockLlama2CreateRequestTests { + + private Llama2ChatBedrockApi api = new Llama2ChatBedrockApi(Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(), + EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); + + @Test + public void createRequestWithChatOptions() { + + var client = new BedrockLlama2ChatClient(api, + BedrockLlama2ChatOptions.builder().withTemperature(66.6f).withMaxGenLen(666).withTopP(0.66f).build()); + + var request = client.createRequest(new Prompt("Test message content")); + + assertThat(request.prompt()).isNotEmpty(); + assertThat(request.temperature()).isEqualTo(66.6f); + assertThat(request.topP()).isEqualTo(0.66f); + assertThat(request.maxGenLen()).isEqualTo(666); + + request = client.createRequest(new Prompt("Test message content", + BedrockLlama2ChatOptions.builder().withTemperature(99.9f).withMaxGenLen(999).withTopP(0.99f).build())); + + assertThat(request.prompt()).isNotEmpty(); + assertThat(request.temperature()).isEqualTo(99.9f); + assertThat(request.topP()).isEqualTo(0.99f); + assertThat(request.maxGenLen()).isEqualTo(999); + } + +} diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/images/bedrock/bedrock-llama2-chat-api.jpg b/spring-ai-docs/src/main/antora/modules/ROOT/images/bedrock/bedrock-llama2-chat-api.jpg new file mode 100644 index 000000000..2c0d3c4f6 Binary files /dev/null and b/spring-ai-docs/src/main/antora/modules/ROOT/images/bedrock/bedrock-llama2-chat-api.jpg differ diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc b/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc index 44e2fe649..452c7e019 100644 --- a/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc +++ b/spring-ai-docs/src/main/antora/modules/ROOT/nav.adoc @@ -7,6 +7,7 @@ *** xref:api/clients/azure-openai-chat.adoc[] *** xref:api/clients/bedrock.adoc[] **** xref:api/clients/bedrock/bedrock-anthropic.adoc[] +**** xref:api/clients/bedrock/bedrock-llama2.adoc[] *** xref:api/clients/huggingface.adoc[] *** xref:api/clients/ollama-chat.adoc[] ** xref:api/prompt.adoc[] diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock-llama2.adoc b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock-llama2.adoc deleted file mode 100644 index 1187479e4..000000000 --- a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock-llama2.adoc +++ /dev/null @@ -1,106 +0,0 @@ -= Amazon Bedrock Anthropic - -https://ai.meta.com/llama/[Meta's Llama 2 Chat] is part of the Llama 2 collection of large language models. -It excels in dialogue-based applications with a parameter scale ranging from 7 billion to 70 billion. -Leveraging public datasets and over 1 million human annotations, Llama Chat offers context-aware dialogues. - -Trained on 2 trillion tokens from public data sources, Llama-2-Chat provides extensive knowledge for insightful conversations. -Rigorous testing, including over 1,000 hours of red-teaming and annotation, ensures both performance and safety, making it a reliable choice for AI-driven dialogues. - -The https://aws.amazon.com/bedrock/llama-2/[AWS Llama 2 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] ----- - - org.springframework.ai - spring-ai-bedrock-ai-spring-boot-starter - 0.8.0-SNAPSHOT - ----- - -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.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. -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.llama2.chat` is the property prefix that configures the `ChatClient` implementation for Llama2. - -[cols="8,4,3"] -|==== -| Property | Description | Default - -| spring.ai.bedrock.llama2.chat.enabled | Enable or disable support for Llama2 | false -| spring.ai.bedrock.llama2.chat.model | The model id to use (See Below) | meta.llama2-70b-chat-v1 -| spring.ai.bedrock.llama2.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.llama2.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.llama2.chat.max-gen-len | Specify the maximum number of tokens to use in the generated response. The model truncates the response once the generated text exceeds maxGenLen. | 300 -|==== - -Look at the Spring AI enumeration, `Llama2ChatModel` for other model IDs. The other value supported is `meta.llama2-13b-chat-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]. \ No newline at end of file diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock.adoc b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock.adoc index e9fb8d914..06f1e2f07 100644 --- a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock.adoc +++ b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock.adoc @@ -85,7 +85,7 @@ Next, you can use the `spring.ai.bedrock...*` properties For more information, refer to the documentation below for each supported model. * 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` +* xref:api/clients/bedrock/bedrock-llama2.adoc[Spring AI Bedrock Llama2 Chat]: `spring.ai.bedrock.llama2.chat.enabled=true` // * [Spring AI Bedrock Cohere Chat](./README_COHERE_CHAT.md) - `spring.ai.bedrock.cohere.chat.enabled=true` diff --git a/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock/bedrock-llama2.adoc b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock/bedrock-llama2.adoc new file mode 100644 index 000000000..21ed31d00 --- /dev/null +++ b/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/bedrock/bedrock-llama2.adoc @@ -0,0 +1,203 @@ += Bedrock Llama2 Chat + +https://ai.meta.com/llama/[Meta's Llama 2 Chat] is part of the Llama 2 collection of large language models. +It excels in dialogue-based applications with a parameter scale ranging from 7 billion to 70 billion. +Leveraging public datasets and over 1 million human annotations, Llama Chat offers context-aware dialogues. + +Trained on 2 trillion tokens from public data sources, Llama-2-Chat provides extensive knowledge for insightful conversations. +Rigorous testing, including over 1,000 hours of red-teaming and annotation, ensures both performance and safety, making it a reliable choice for AI-driven dialogues. + +The https://aws.amazon.com/bedrock/llama-2/[AWS Llama 2 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. + + +Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file: + +[source,xml] +---- + + org.springframework.ai + spring-ai-bedrock + 0.8.0-SNAPSHOT + +---- + +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. + +The link:./src/main/java/org/springframework/ai/bedrock/llama2/BedrockLlama2ChatClient.java[BedrockLlama2ChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the `Llama2ChatBedrockApi` library to connect to the Bedrock Llama2 service. + +Here is how to create and use a `BedrockLlama2ChatClient`: + +[source,java] +---- +Llama2ChatBedrockApi api = new Llama2ChatBedrockApi(Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(), + EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); + +BedrockLlama2ChatClient chatClient = new BedrockLlama2ChatClient(api, + BedrockLlama2ChatOptions.builder() + .withTemperature(0.5f) + .withMaxGenLen(100) + .withTopP(0.9f).build()); + +ChatResponse response = chatClient.call( + new Prompt("Generate the names of 5 famous pirates.")); + +// Or with streaming responses +Flux response = chatClient.stream( + new Prompt("Generate the names of 5 famous pirates.")); +---- + +=== BedrockLlama2ChatClient Auto-configuration + +or you can leverage the `spring-ai-bedrock-ai-spring-boot-starter` Spring Boot starter: + +[source,xml] +---- + + org.springframework.ai + spring-ai-bedrock-ai-spring-boot-starter + 0.8.0-SNAPSHOT + +---- + +or to your Gradle `build.gradle` build file. + +[source,gradle] +---- +dependencies { + implementation 'org.springframework.ai:spring-ai-bedrock-ai-spring-boot-starter:0.8.0-SNAPSHOT' +} +---- + +==== Enable Llama2 Chat 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. + +Create an `application.properties` file in the `src/main/resources` directory and add the following properties to configure the Llama2 Chat client. + +[source] +---- +spring.ai.bedrock.llama2.chat.enabled=true +spring.ai.bedrock.llama2.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,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.llama2.chat` is the property prefix that configures the `ChatClient` implementation for Llama2. + +[cols="2,5,1"] +|==== +| Property | Description | Default + +| spring.ai.bedrock.llama2.chat.enabled | Enable or disable support for Llama2 | false +| spring.ai.bedrock.llama2.chat.model | The model id to use (See Below) | meta.llama2-70b-chat-v1 +| spring.ai.bedrock.llama2.chat.options.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.llama2.chat.options.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.llama2.chat.options.max-gen-len | Specify the maximum number of tokens to use in the generated response. The model truncates the response once the generated text exceeds maxGenLen. | 300 +|==== + +Look at the Spring AI enumeration, `Llama2ChatModel` for other model IDs. The other value supported is `meta.llama2-13b-chat-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 Llama2ChatBedrockApi Library + +link:./src/main/java/org/springframework/ai/bedrock/llama2/api/Llama2ChatBedrockApi.java[Llama2ChatBedrockApi] provides is lightweight Java client on top of AWS Bedrock https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html[Meta Llama 2 and Llama 2 Chat models]. + +Following class diagram illustrates the Llama2ChatBedrockApi interface and building blocks: + +image::bedrock/bedrock-llama2-chat-api.jpg[Llama2ChatBedrockApi Class Diagram] + +The Llama2ChatBedrockApi supports the `meta.llama2-13b-chat-v1` and `meta.llama2-70b-chat-v1` models. + +Also the Llama2ChatBedrockApi 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] +---- +Llama2ChatBedrockApi llama2ChatApi = new Llama2ChatBedrockApi( + Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(), + Region.US_EAST_1.id()); + +Llama2ChatRequest request = Llama2ChatRequest.builder("Hello, my name is") + .withTemperature(0.9f) + .withTopP(0.9f) + .withMaxGenLen(20) + .build(); + +Llama2ChatResponse response = llama2ChatApi.chatCompletion(request); + +System.out.println(response.generation()); + +// Streaming response +Flux responseStream = llama2ChatApi.chatCompletionStream(request); + +List responses = responseStream.collectList().block(); + +System.out.println(responses); +---- + +Follow the link:./src/main/java/org/springframework/ai/bedrock/llama2/api/Llama2ChatBedrockApi.java[Llama2ChatBedrockApi.java]'s JavaDoc for further information. + + diff --git a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/anthropic/BedrockAnthropicChatProperties.java b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/anthropic/BedrockAnthropicChatProperties.java index a230aef0c..660224911 100644 --- a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/anthropic/BedrockAnthropicChatProperties.java +++ b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/anthropic/BedrockAnthropicChatProperties.java @@ -21,6 +21,7 @@ import java.util.List; 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.boot.context.properties.NestedConfigurationProperty; import org.springframework.util.Assert; /** @@ -45,6 +46,7 @@ public class BedrockAnthropicChatProperties { */ private String model = AnthropicChatModel.CLAUDE_V2.id(); + @NestedConfigurationProperty private AnthropicChatOptions options = AnthropicChatOptions.builder() .withTemperature(0.7f) .withMaxTokensToSample(300) diff --git a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfiguration.java b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfiguration.java index af657e887..0d45de272 100644 --- a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfiguration.java +++ b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfiguration.java @@ -60,9 +60,8 @@ public class BedrockLlama2ChatAutoConfiguration { @Bean public BedrockLlama2ChatClient llama2ChatClient(Llama2ChatBedrockApi llama2Api, BedrockLlama2ChatProperties properties) { - return new BedrockLlama2ChatClient(llama2Api).withTemperature(properties.getTemperature()) - .withTopP(properties.getTopP()) - .withMaxGenLen(properties.getMaxGenLen()); + + return new BedrockLlama2ChatClient(llama2Api, properties.getOptions()); } } diff --git a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatProperties.java b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatProperties.java index 9d2c3d7e2..81968601d 100644 --- a/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatProperties.java +++ b/spring-ai-spring-boot-autoconfigure/src/main/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatProperties.java @@ -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. @@ -16,8 +16,10 @@ package org.springframework.ai.autoconfigure.bedrock.llama2; +import org.springframework.ai.bedrock.llama2.BedrockLlama2ChatOptions; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * Configuration properties for Bedrock Llama2. @@ -35,33 +37,17 @@ public class BedrockLlama2ChatProperties { */ private boolean enabled = false; - /** - * 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. The - * generative truncates the response once the generated text exceeds maxGenLen. - */ - private Integer maxGenLen = 300; - /** * The generative id to use. See the {@link Llama2ChatModel} for the supported models. */ private String model = Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(); + @NestedConfigurationProperty + private BedrockLlama2ChatOptions options = BedrockLlama2ChatOptions.builder() + .withTemperature(0.7f) + .withMaxGenLen(300) + .build(); + public boolean isEnabled() { return this.enabled; } @@ -78,28 +64,12 @@ public class BedrockLlama2ChatProperties { this.model = model; } - public Float getTemperature() { - return this.temperature; + public BedrockLlama2ChatOptions getOptions() { + return this.options; } - public void setTemperature(Float temperature) { - this.temperature = temperature; - } - - public Float getTopP() { - return this.topP; - } - - public void setTopP(Float topP) { - this.topP = topP; - } - - public Integer getMaxGenLen() { - return this.maxGenLen; - } - - public void setMaxGenLen(Integer topK) { - this.maxGenLen = topK; + public void setOptions(BedrockLlama2ChatOptions options) { + this.options = options; } } diff --git a/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfigurationIT.java b/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfigurationIT.java index adf027cd2..da91e6b3e 100644 --- a/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfigurationIT.java +++ b/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/bedrock/llama2/BedrockLlama2ChatAutoConfigurationIT.java @@ -54,7 +54,8 @@ public class BedrockLlama2ChatAutoConfigurationIT { "spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"), "spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(), "spring.ai.bedrock.llama2.chat.model=" + Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(), - "spring.ai.bedrock.llama2.chat.temperature=0.5", "spring.ai.bedrock.llama2.chat.maxGenLen=500") + "spring.ai.bedrock.llama2.chat.options.temperature=0.5", + "spring.ai.bedrock.llama2.chat.options.maxGenLen=500") .withConfiguration(AutoConfigurations.of(BedrockLlama2ChatAutoConfiguration.class)); private final Message systemMessage = new SystemPromptTemplate(""" @@ -106,7 +107,8 @@ public class BedrockLlama2ChatAutoConfigurationIT { "spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY", "spring.ai.bedrock.llama2.chat.model=MODEL_XYZ", "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), - "spring.ai.bedrock.llama2.chat.temperature=0.55", "spring.ai.bedrock.llama2.chat.maxGenLen=123") + "spring.ai.bedrock.llama2.chat.options.temperature=0.55", + "spring.ai.bedrock.llama2.chat.options.maxGenLen=123") .withConfiguration(AutoConfigurations.of(BedrockLlama2ChatAutoConfiguration.class)) .run(context -> { var llama2ChatProperties = context.getBean(BedrockLlama2ChatProperties.class); @@ -115,8 +117,8 @@ public class BedrockLlama2ChatAutoConfigurationIT { assertThat(llama2ChatProperties.isEnabled()).isTrue(); assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id()); - assertThat(llama2ChatProperties.getTemperature()).isEqualTo(0.55f); - assertThat(llama2ChatProperties.getMaxGenLen()).isEqualTo(123); + assertThat(llama2ChatProperties.getOptions().getTemperature()).isEqualTo(0.55f); + assertThat(llama2ChatProperties.getOptions().getMaxGenLen()).isEqualTo(123); assertThat(llama2ChatProperties.getModel()).isEqualTo("MODEL_XYZ"); assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY");