This commit is contained in:
Josh Long
2024-05-17 17:55:33 +02:00
parent 1b1daa7ee7
commit a2147e8572
157 changed files with 1026 additions and 809 deletions

View File

@@ -26,6 +26,7 @@ import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.connector.ChatConnector;
import reactor.core.publisher.Flux;
import org.springframework.ai.anthropic.api.AnthropicApi;
@@ -38,7 +39,6 @@ import org.springframework.ai.anthropic.api.AnthropicApi.Role;
import org.springframework.ai.anthropic.api.AnthropicApi.StreamResponse;
import org.springframework.ai.anthropic.api.AnthropicApi.Usage;
import org.springframework.ai.anthropic.metadata.AnthropicChatResponseMetadata;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -56,16 +56,16 @@ import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* The {@link ChatClient} implementation for the Anthropic service.
* The {@link ChatConnector} implementation for the Anthropic service.
*
* @author Christian Tzolov
* @since 1.0.0
*/
public class AnthropicChatClient extends
public class AnthropicChatConnector extends
AbstractFunctionCallSupport<AnthropicApi.RequestMessage, AnthropicApi.ChatCompletionRequest, ResponseEntity<AnthropicApi.ChatCompletion>>
implements ChatClient, StreamingChatClient {
implements ChatConnector, StreamingChatClient {
private static final Logger logger = LoggerFactory.getLogger(AnthropicChatClient.class);
private static final Logger logger = LoggerFactory.getLogger(AnthropicChatConnector.class);
public static final String DEFAULT_MODEL_NAME = AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue();
@@ -89,10 +89,10 @@ public class AnthropicChatClient extends
public final RetryTemplate retryTemplate;
/**
* Construct a new {@link AnthropicChatClient} instance.
* Construct a new {@link AnthropicChatConnector} instance.
* @param anthropicApi the lower-level API for the Anthropic service.
*/
public AnthropicChatClient(AnthropicApi anthropicApi) {
public AnthropicChatConnector(AnthropicApi anthropicApi) {
this(anthropicApi,
AnthropicChatOptions.builder()
.withModel(DEFAULT_MODEL_NAME)
@@ -102,34 +102,34 @@ public class AnthropicChatClient extends
}
/**
* Construct a new {@link AnthropicChatClient} instance.
* Construct a new {@link AnthropicChatConnector} instance.
* @param anthropicApi the lower-level API for the Anthropic service.
* @param defaultOptions the default options used for the chat completion requests.
*/
public AnthropicChatClient(AnthropicApi anthropicApi, AnthropicChatOptions defaultOptions) {
public AnthropicChatConnector(AnthropicApi anthropicApi, AnthropicChatOptions defaultOptions) {
this(anthropicApi, defaultOptions, RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
/**
* Construct a new {@link AnthropicChatClient} instance.
* Construct a new {@link AnthropicChatConnector} instance.
* @param anthropicApi the lower-level API for the Anthropic service.
* @param defaultOptions the default options used for the chat completion requests.
* @param retryTemplate the retry template used to retry the Anthropic API calls.
*/
public AnthropicChatClient(AnthropicApi anthropicApi, AnthropicChatOptions defaultOptions,
public AnthropicChatConnector(AnthropicApi anthropicApi, AnthropicChatOptions defaultOptions,
RetryTemplate retryTemplate) {
this(anthropicApi, defaultOptions, retryTemplate, null);
}
/**
* Construct a new {@link AnthropicChatClient} instance.
* Construct a new {@link AnthropicChatConnector} instance.
* @param anthropicApi the lower-level API for the Anthropic service.
* @param defaultOptions the default options used for the chat completion requests.
* @param retryTemplate the retry template used to retry the Anthropic API calls.
* @param functionCallbackContext the function callback context used to store the
* state of the function calls.
*/
public AnthropicChatClient(AnthropicApi anthropicApi, AnthropicChatOptions defaultOptions,
public AnthropicChatConnector(AnthropicApi anthropicApi, AnthropicChatOptions defaultOptions,
RetryTemplate retryTemplate, FunctionCallbackContext functionCallbackContext) {
super(functionCallbackContext);
@@ -144,7 +144,7 @@ public class AnthropicChatClient extends
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
ChatCompletionRequest request = createRequest(prompt, false);

View File

@@ -51,11 +51,11 @@ public class AnthropicChatOptions implements ChatOptions, FunctionCallingOptions
private @JsonProperty("top_k") Integer topK;
/**
* Tool Function Callbacks to register with the ChatClient. For Prompt
* Tool Function Callbacks to register with the ChatConnector. For Prompt
* Options the functionCallbacks are automatically enabled for the duration of the
* prompt execution. For Default Options the functionCallbacks are registered but
* disabled by default. Use the enableFunctions to set the functions from the registry
* to be used by the ChatClient chat completion requests.
* to be used by the ChatConnector chat completion requests.
*/
@NestedConfigurationProperty
@JsonIgnore

View File

@@ -29,7 +29,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.ai.anthropic.api.AnthropicApi;
import org.springframework.ai.anthropic.api.tool.MockWeatherService;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -56,12 +56,12 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = AnthropicTestConfiguration.class, properties = "spring.ai.retry.on-http-codes=429")
@EnabledIfEnvironmentVariable(named = "ANTHROPIC_API_KEY", matches = ".+")
class AnthropicChatClientIT {
class AnthropicChatConnectorIT {
private static final Logger logger = LoggerFactory.getLogger(AnthropicChatClientIT.class);
private static final Logger logger = LoggerFactory.getLogger(AnthropicChatConnectorIT.class);
@Autowired
protected ChatClient chatClient;
protected ChatConnector chatConnector;
@Autowired
protected StreamingChatClient streamingChatClient;
@@ -76,7 +76,7 @@ class AnthropicChatClientIT {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Bob", "voice", "pirate"));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = chatClient.call(prompt);
ChatResponse response = chatConnector.execute(prompt);
assertThat(response.getResults()).hasSize(1);
assertThat(response.getMetadata().getUsage().getGenerationTokens()).isGreaterThan(0);
assertThat(response.getMetadata().getUsage().getPromptTokens()).isGreaterThan(0);
@@ -102,7 +102,7 @@ class AnthropicChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.chatClient.call(prompt).getResult();
Generation generation = this.chatConnector.execute(prompt).getResult();
List<String> list = listOutputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -120,7 +120,7 @@ class AnthropicChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatConnector.execute(prompt).getResult();
Map<String, Object> result = mapOutputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -142,7 +142,7 @@ class AnthropicChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatConnector.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = beanOutputConverter.convert(generation.getOutput().getContent());
logger.info("" + actorsFilms);
@@ -187,14 +187,14 @@ class AnthropicChatClientIT {
var userMessage = new UserMessage("Explain what do you see on this picture?",
List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData)));
var response = chatClient.call(new Prompt(List.of(userMessage)));
var response = chatConnector.execute(new Prompt(List.of(userMessage)));
logger.info(response.getResult().getOutput().getContent());
assertThat(response.getResult().getOutput().getContent()).contains("bananas", "apple", "basket");
}
@Test
void functionCallTest() {
void functionExecuteTest() {
UserMessage userMessage = new UserMessage(
"What's the weather like in San Francisco, Tokyo and Paris? Return the result in Celsius.");
@@ -209,7 +209,7 @@ class AnthropicChatClientIT {
.build()))
.build();
ChatResponse response = chatClient.call(new Prompt(messages, promptOptions));
ChatResponse response = chatConnector.execute(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);

View File

@@ -38,8 +38,8 @@ public class AnthropicTestConfiguration {
}
@Bean
public AnthropicChatClient openAiChatClient(AnthropicApi api) {
AnthropicChatClient anthropicChatClient = new AnthropicChatClient(api);
public AnthropicChatConnector openAiChatClient(AnthropicApi api) {
AnthropicChatConnector anthropicChatClient = new AnthropicChatConnector(api);
return anthropicChatClient;
}

View File

@@ -30,7 +30,7 @@ public class ChatCompletionRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new AnthropicChatClient(new AnthropicApi("TEST"),
var client = new AnthropicChatConnector(new AnthropicApi("TEST"),
AnthropicChatOptions.builder().withModel("DEFAULT_MODEL").withTemperature(66.6f).build());
var request = client.createRequest(new Prompt("Test message content"), false);

View File

@@ -38,7 +38,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.azure.openai.metadata.AzureOpenAiChatResponseMetadata;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -63,7 +63,7 @@ import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* {@link ChatClient} implementation for {@literal Microsoft Azure AI} backed by
* {@link ChatConnector} implementation for {@literal Microsoft Azure AI} backed by
* {@link OpenAIClient}.
*
* @author Mark Pollack
@@ -71,12 +71,12 @@ import java.util.concurrent.atomic.AtomicBoolean;
* @author John Blum
* @author Christian Tzolov
* @author Grogdunn
* @see ChatClient
* @see ChatConnector
* @see com.azure.ai.openai.OpenAIClient
*/
public class AzureOpenAiChatClient
public class AzureOpenAiChatConnector
extends AbstractFunctionCallSupport<ChatRequestMessage, ChatCompletionsOptions, ChatCompletions>
implements ChatClient, StreamingChatClient {
implements ChatConnector, StreamingChatClient {
private static final String DEFAULT_DEPLOYMENT_NAME = "gpt-35-turbo";
@@ -94,7 +94,7 @@ public class AzureOpenAiChatClient
*/
private final OpenAIClient openAIClient;
public AzureOpenAiChatClient(OpenAIClient microsoftOpenAiClient) {
public AzureOpenAiChatConnector(OpenAIClient microsoftOpenAiClient) {
this(microsoftOpenAiClient,
AzureOpenAiChatOptions.builder()
.withDeploymentName(DEFAULT_DEPLOYMENT_NAME)
@@ -102,11 +102,11 @@ public class AzureOpenAiChatClient
.build());
}
public AzureOpenAiChatClient(OpenAIClient microsoftOpenAiClient, AzureOpenAiChatOptions options) {
public AzureOpenAiChatConnector(OpenAIClient microsoftOpenAiClient, AzureOpenAiChatOptions options) {
this(microsoftOpenAiClient, options, null);
}
public AzureOpenAiChatClient(OpenAIClient microsoftOpenAiClient, AzureOpenAiChatOptions options,
public AzureOpenAiChatConnector(OpenAIClient microsoftOpenAiClient, AzureOpenAiChatOptions options,
FunctionCallbackContext functionCallbackContext) {
super(functionCallbackContext);
Assert.notNull(microsoftOpenAiClient, "com.azure.ai.openai.OpenAIClient must not be null");
@@ -117,10 +117,10 @@ public class AzureOpenAiChatClient
/**
* @deprecated since 0.8.0, use
* {@link #AzureOpenAiChatClient(OpenAIClient, AzureOpenAiChatOptions)} instead.
* {@link #AzureOpenAiChatConnector(OpenAIClient, AzureOpenAiChatOptions)} instead.
*/
@Deprecated(forRemoval = true, since = "0.8.0")
public AzureOpenAiChatClient withDefaultOptions(AzureOpenAiChatOptions defaultOptions) {
public AzureOpenAiChatConnector withDefaultOptions(AzureOpenAiChatOptions defaultOptions) {
Assert.notNull(defaultOptions, "DefaultOptions must not be null");
this.defaultOptions = defaultOptions;
return this;
@@ -131,7 +131,7 @@ public class AzureOpenAiChatClient
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
ChatCompletionsOptions options = toAzureChatCompletionsOptions(prompt);
options.setStream(false);

View File

@@ -127,11 +127,11 @@ public class AzureOpenAiChatOptions implements FunctionCallingOptions, ChatOptio
private String deploymentName;
/**
* OpenAI Tool Function Callbacks to register with the ChatClient. For Prompt Options
* the functionCallbacks are automatically enabled for the duration of the prompt
* execution. For Default Options the functionCallbacks are registered but disabled by
* default. Use the enableFunctions to set the functions from the registry to be used
* by the ChatClient chat completion requests.
* OpenAI Tool Function Callbacks to register with the ChatConnector. For Prompt
* Options the functionCallbacks are automatically enabled for the duration of the
* prompt execution. For Default Options the functionCallbacks are registered but
* disabled by default. Use the enableFunctions to set the functions from the registry
* to be used by the ChatConnector chat completion requests.
*/
@NestedConfigurationProperty
@JsonIgnore

View File

@@ -53,7 +53,7 @@ public class AzureChatCompletionsOptionsTests {
.withUser("user")
.build();
var client = new AzureOpenAiChatClient(mockClient, defaultOptions);
var client = new AzureOpenAiChatConnector(mockClient, defaultOptions);
var requestOptions = client.toAzureChatCompletionsOptions(new Prompt("Test message content"));

View File

@@ -46,13 +46,13 @@ import org.springframework.core.convert.support.DefaultConversionService;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = AzureOpenAiChatClientIT.TestConfiguration.class)
@SpringBootTest(classes = AzureOpenAiChatConnectorIT.TestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+")
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+")
class AzureOpenAiChatClientIT {
class AzureOpenAiChatConnectorIT {
@Autowired
private AzureOpenAiChatClient chatClient;
private AzureOpenAiChatConnector chatClient;
record ActorsFilms(String actor, List<String> movies) {
}
@@ -69,7 +69,7 @@ class AzureOpenAiChatClientIT {
UserMessage userMessage = new UserMessage("Generate the names of 5 famous pirates.");
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = chatClient.call(prompt);
ChatResponse response = chatClient.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -86,7 +86,7 @@ class AzureOpenAiChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatClient.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -105,7 +105,7 @@ class AzureOpenAiChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatClient.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -124,7 +124,7 @@ class AzureOpenAiChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatClient.execute(prompt).getResult();
ActorsFilms actorsFilms = outputConverter.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isNotNull();
@@ -145,7 +145,7 @@ class AzureOpenAiChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatClient.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
System.out.println(actorsFilms);
@@ -194,8 +194,8 @@ class AzureOpenAiChatClientIT {
}
@Bean
public AzureOpenAiChatClient azureOpenAiChatClient(OpenAIClient openAIClient) {
return new AzureOpenAiChatClient(openAIClient,
public AzureOpenAiChatConnector azureOpenAiChatClient(OpenAIClient openAIClient) {
return new AzureOpenAiChatConnector(openAIClient,
AzureOpenAiChatOptions.builder().withDeploymentName("gpt-35-turbo").withMaxTokens(200).build());
}

View File

@@ -59,8 +59,8 @@ public class MockAzureOpenAiTestConfiguration {
}
@Bean
AzureOpenAiChatClient azureOpenAiChatClient(OpenAIClient microsoftAzureOpenAiClient) {
return new AzureOpenAiChatClient(microsoftAzureOpenAiClient);
AzureOpenAiChatConnector azureOpenAiChatClient(OpenAIClient microsoftAzureOpenAiClient) {
return new AzureOpenAiChatConnector(microsoftAzureOpenAiClient);
}
}

View File

@@ -29,7 +29,7 @@ import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.azure.openai.AzureOpenAiChatClient;
import org.springframework.ai.azure.openai.AzureOpenAiChatConnector;
import org.springframework.ai.azure.openai.AzureOpenAiChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
@@ -46,21 +46,21 @@ import reactor.core.publisher.Flux;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = AzureOpenAiChatClientFunctionCallIT.TestConfiguration.class)
@SpringBootTest(classes = AzureOpenAiChatConnectorFunctionCallIT.TestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+")
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+")
class AzureOpenAiChatClientFunctionCallIT {
class AzureOpenAiChatConnectorFunctionCallIT {
private static final Logger logger = LoggerFactory.getLogger(AzureOpenAiChatClientFunctionCallIT.class);
private static final Logger logger = LoggerFactory.getLogger(AzureOpenAiChatConnectorFunctionCallIT.class);
@Autowired
private String selectedModel;
@Autowired
private AzureOpenAiChatClient chatClient;
private AzureOpenAiChatConnector chatClient;
@Test
void functionCallTest() {
void functionExecuteTest() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, in Tokyo, and in Paris?");
@@ -75,7 +75,7 @@ class AzureOpenAiChatClientFunctionCallIT {
.build()))
.build();
ChatResponse response = chatClient.call(new Prompt(messages, promptOptions));
ChatResponse response = chatClient.execute(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);
@@ -85,7 +85,7 @@ class AzureOpenAiChatClientFunctionCallIT {
}
@Test
void streamFunctionCallTest() {
void streamFunctionExecuteTest() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");
List<Message> messages = new ArrayList<>(List.of(userMessage));
@@ -129,8 +129,8 @@ class AzureOpenAiChatClientFunctionCallIT {
}
@Bean
public AzureOpenAiChatClient azureOpenAiChatClient(OpenAIClient openAIClient, String selectedModel) {
return new AzureOpenAiChatClient(openAIClient,
public AzureOpenAiChatConnector azureOpenAiChatClient(OpenAIClient openAIClient, String selectedModel) {
return new AzureOpenAiChatConnector(openAIClient,
AzureOpenAiChatOptions.builder().withDeploymentName(selectedModel).withMaxTokens(500).build());
}

View File

@@ -23,7 +23,7 @@ import com.azure.ai.openai.models.ContentFilterResultsForChoice;
import com.azure.ai.openai.models.ContentFilterSeverity;
import org.junit.jupiter.api.Test;
import org.springframework.ai.azure.openai.AzureOpenAiChatClient;
import org.springframework.ai.azure.openai.AzureOpenAiChatConnector;
import org.springframework.ai.azure.openai.MockAzureOpenAiTestConfiguration;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
@@ -55,7 +55,7 @@ import org.springframework.web.context.request.WebRequest;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit Tests for {@link AzureOpenAiChatClient} asserting AI metadata.
* Unit Tests for {@link AzureOpenAiChatConnector} asserting AI metadata.
*
* @author John Blum
* @author Christian Tzolov
@@ -63,19 +63,19 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@SpringBootTest
@ActiveProfiles("spring-ai-azure-openai-mocks")
@ContextConfiguration(classes = AzureOpenAiChatClientMetadataTests.TestConfiguration.class)
@ContextConfiguration(classes = AzureOpenAiChatConnectorMetadataTests.TestConfiguration.class)
@SuppressWarnings("unused")
class AzureOpenAiChatClientMetadataTests {
class AzureOpenAiChatConnectorMetadataTests {
@Autowired
private AzureOpenAiChatClient aiClient;
private AzureOpenAiChatConnector aiClient;
@Test
void azureOpenAiMetadataCapturedDuringGeneration() {
Prompt prompt = new Prompt("Can I fly like a bird?");
ChatResponse response = this.aiClient.call(prompt);
ChatResponse response = this.aiClient.execute(prompt);
assertThat(response).isNotNull();

View File

@@ -17,7 +17,7 @@ package org.springframework.ai.bedrock.anthropic;
import java.util.List;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
@@ -33,19 +33,19 @@ import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.ModelOptionsUtils;
/**
* Java {@link ChatClient} and {@link StreamingChatClient} for the Bedrock Anthropic chat
* generative.
* Java {@link ChatConnector} and {@link StreamingChatClient} for the Bedrock Anthropic
* chat generative.
*
* @author Christian Tzolov
* @since 0.8.0
*/
public class BedrockAnthropicChatClient implements ChatClient, StreamingChatClient {
public class BedrockAnthropicChatConnector implements ChatConnector, StreamingChatClient {
private final AnthropicChatBedrockApi anthropicChatApi;
private final AnthropicChatOptions defaultOptions;
public BedrockAnthropicChatClient(AnthropicChatBedrockApi chatApi) {
public BedrockAnthropicChatConnector(AnthropicChatBedrockApi chatApi) {
this(chatApi,
AnthropicChatOptions.builder()
.withTemperature(0.8f)
@@ -55,13 +55,13 @@ public class BedrockAnthropicChatClient implements ChatClient, StreamingChatClie
.build());
}
public BedrockAnthropicChatClient(AnthropicChatBedrockApi chatApi, AnthropicChatOptions options) {
public BedrockAnthropicChatConnector(AnthropicChatBedrockApi chatApi, AnthropicChatOptions options) {
this.anthropicChatApi = chatApi;
this.defaultOptions = options;
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
AnthropicChatRequest request = createRequest(prompt);

View File

@@ -22,7 +22,7 @@ import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.An
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.MediaContent;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.ChatCompletionMessage;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.ChatCompletionMessage.Role;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -43,20 +43,20 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
* Java {@link ChatClient} and {@link StreamingChatClient} for the Bedrock Anthropic chat
* generative.
* Java {@link ChatConnector} and {@link StreamingChatClient} for the Bedrock Anthropic
* chat generative.
*
* @author Ben Middleton
* @author Christian Tzolov
* @since 1.0.0
*/
public class BedrockAnthropic3ChatClient implements ChatClient, StreamingChatClient {
public class BedrockAnthropic3ChatConnector implements ChatConnector, StreamingChatClient {
private final Anthropic3ChatBedrockApi anthropicChatApi;
private final Anthropic3ChatOptions defaultOptions;
public BedrockAnthropic3ChatClient(Anthropic3ChatBedrockApi chatApi) {
public BedrockAnthropic3ChatConnector(Anthropic3ChatBedrockApi chatApi) {
this(chatApi,
Anthropic3ChatOptions.builder()
.withTemperature(0.8f)
@@ -66,13 +66,13 @@ public class BedrockAnthropic3ChatClient implements ChatClient, StreamingChatCli
.build());
}
public BedrockAnthropic3ChatClient(Anthropic3ChatBedrockApi chatApi, Anthropic3ChatOptions options) {
public BedrockAnthropic3ChatConnector(Anthropic3ChatBedrockApi chatApi, Anthropic3ChatOptions options) {
this.anthropicChatApi = chatApi;
this.defaultOptions = options;
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
AnthropicChatRequest request = createRequest(prompt);

View File

@@ -17,6 +17,7 @@ package org.springframework.ai.bedrock.cohere;
import java.util.List;
import org.springframework.ai.chat.connector.ChatConnector;
import reactor.core.publisher.Flux;
import org.springframework.ai.bedrock.BedrockUsage;
@@ -24,7 +25,6 @@ import org.springframework.ai.bedrock.MessageToPromptConverter;
import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi;
import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest;
import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatResponse;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
@@ -39,17 +39,17 @@ import org.springframework.util.Assert;
* @author Christian Tzolov
* @since 0.8.0
*/
public class BedrockCohereChatClient implements ChatClient, StreamingChatClient {
public class BedrockCohereChatConnector implements ChatConnector, StreamingChatClient {
private final CohereChatBedrockApi chatApi;
private final BedrockCohereChatOptions defaultOptions;
public BedrockCohereChatClient(CohereChatBedrockApi chatApi) {
public BedrockCohereChatConnector(CohereChatBedrockApi chatApi) {
this(chatApi, BedrockCohereChatOptions.builder().build());
}
public BedrockCohereChatClient(CohereChatBedrockApi chatApi, BedrockCohereChatOptions options) {
public BedrockCohereChatConnector(CohereChatBedrockApi chatApi, BedrockCohereChatOptions options) {
Assert.notNull(chatApi, "CohereChatBedrockApi must not be null");
Assert.notNull(options, "BedrockCohereChatOptions must not be null");
@@ -58,7 +58,7 @@ public class BedrockCohereChatClient implements ChatClient, StreamingChatClient
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
CohereChatResponse response = this.chatApi.chatCompletion(this.createRequest(prompt, false));
List<Generation> generations = response.generations().stream().map(g -> {
return new Generation(g.text());

View File

@@ -19,7 +19,7 @@ package org.springframework.ai.bedrock.jurassic2;
import org.springframework.ai.bedrock.MessageToPromptConverter;
import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi;
import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatRequest;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
@@ -29,18 +29,18 @@ import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.Assert;
/**
* Java {@link ChatClient} for the Bedrock Jurassic2 chat generative model.
* Java {@link ChatConnector} for the Bedrock Jurassic2 chat generative model.
*
* @author Ahmed Yousri
* @since 1.0.0
*/
public class BedrockAi21Jurassic2ChatClient implements ChatClient {
public class BedrockAi21Jurassic2ChatConnector implements ChatConnector {
private final Ai21Jurassic2ChatBedrockApi chatApi;
private final BedrockAi21Jurassic2ChatOptions defaultOptions;
public BedrockAi21Jurassic2ChatClient(Ai21Jurassic2ChatBedrockApi chatApi,
public BedrockAi21Jurassic2ChatConnector(Ai21Jurassic2ChatBedrockApi chatApi,
BedrockAi21Jurassic2ChatOptions options) {
Assert.notNull(chatApi, "Ai21Jurassic2ChatBedrockApi must not be null");
Assert.notNull(options, "BedrockAi21Jurassic2ChatOptions must not be null");
@@ -49,7 +49,7 @@ public class BedrockAi21Jurassic2ChatClient implements ChatClient {
this.defaultOptions = options;
}
public BedrockAi21Jurassic2ChatClient(Ai21Jurassic2ChatBedrockApi chatApi) {
public BedrockAi21Jurassic2ChatConnector(Ai21Jurassic2ChatBedrockApi chatApi) {
this(chatApi,
BedrockAi21Jurassic2ChatOptions.builder()
.withTemperature(0.8f)
@@ -59,7 +59,7 @@ public class BedrockAi21Jurassic2ChatClient implements ChatClient {
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
var request = createRequest(prompt);
var response = this.chatApi.chatCompletion(request);
@@ -114,8 +114,8 @@ public class BedrockAi21Jurassic2ChatClient implements ChatClient {
return this;
}
public BedrockAi21Jurassic2ChatClient build() {
return new BedrockAi21Jurassic2ChatClient(chatApi,
public BedrockAi21Jurassic2ChatConnector build() {
return new BedrockAi21Jurassic2ChatConnector(chatApi,
options != null ? options : BedrockAi21Jurassic2ChatOptions.builder().build());
}

View File

@@ -17,13 +17,13 @@ package org.springframework.ai.bedrock.llama;
import java.util.List;
import org.springframework.ai.chat.connector.ChatConnector;
import reactor.core.publisher.Flux;
import org.springframework.ai.bedrock.MessageToPromptConverter;
import org.springframework.ai.bedrock.llama.api.LlamaChatBedrockApi;
import org.springframework.ai.bedrock.llama.api.LlamaChatBedrockApi.LlamaChatRequest;
import org.springframework.ai.bedrock.llama.api.LlamaChatBedrockApi.LlamaChatResponse;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
@@ -35,25 +35,25 @@ import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.Assert;
/**
* Java {@link ChatClient} and {@link StreamingChatClient} for the Bedrock Llama chat
* Java {@link ChatConnector} and {@link StreamingChatClient} for the Bedrock Llama chat
* generative.
*
* @author Christian Tzolov
* @author Wei Jiang
* @since 0.8.0
*/
public class BedrockLlamaChatClient implements ChatClient, StreamingChatClient {
public class BedrockLlamaChatConnector implements ChatConnector, StreamingChatClient {
private final LlamaChatBedrockApi chatApi;
private final BedrockLlamaChatOptions defaultOptions;
public BedrockLlamaChatClient(LlamaChatBedrockApi chatApi) {
public BedrockLlamaChatConnector(LlamaChatBedrockApi chatApi) {
this(chatApi,
BedrockLlamaChatOptions.builder().withTemperature(0.8f).withTopP(0.9f).withMaxGenLen(100).build());
}
public BedrockLlamaChatClient(LlamaChatBedrockApi chatApi, BedrockLlamaChatOptions options) {
public BedrockLlamaChatConnector(LlamaChatBedrockApi chatApi, BedrockLlamaChatOptions options) {
Assert.notNull(chatApi, "LlamaChatBedrockApi must not be null");
Assert.notNull(options, "BedrockLlamaChatOptions must not be null");
@@ -62,7 +62,7 @@ public class BedrockLlamaChatClient implements ChatClient, StreamingChatClient {
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
var request = createRequest(prompt);

View File

@@ -17,6 +17,7 @@ package org.springframework.ai.bedrock.titan;
import java.util.List;
import org.springframework.ai.chat.connector.ChatConnector;
import reactor.core.publisher.Flux;
import org.springframework.ai.bedrock.MessageToPromptConverter;
@@ -24,7 +25,6 @@ import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi;
import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest;
import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatResponse;
import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatResponseChunk;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
@@ -39,17 +39,17 @@ import org.springframework.util.Assert;
* @author Christian Tzolov
* @since 0.8.0
*/
public class BedrockTitanChatClient implements ChatClient, StreamingChatClient {
public class BedrockTitanChatConnector implements ChatConnector, StreamingChatClient {
private final TitanChatBedrockApi chatApi;
private final BedrockTitanChatOptions defaultOptions;
public BedrockTitanChatClient(TitanChatBedrockApi chatApi) {
public BedrockTitanChatConnector(TitanChatBedrockApi chatApi) {
this(chatApi, BedrockTitanChatOptions.builder().withTemperature(0.8f).build());
}
public BedrockTitanChatClient(TitanChatBedrockApi chatApi, BedrockTitanChatOptions defaultOptions) {
public BedrockTitanChatConnector(TitanChatBedrockApi chatApi, BedrockTitanChatOptions defaultOptions) {
Assert.notNull(chatApi, "ChatApi must not be null");
Assert.notNull(defaultOptions, "DefaultOptions must not be null");
this.chatApi = chatApi;
@@ -57,7 +57,7 @@ public class BedrockTitanChatClient implements ChatClient, StreamingChatClient {
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
TitanChatResponse response = this.chatApi.chatCompletion(this.createRequest(prompt));
List<Generation> generations = response.results().stream().map(result -> {
return new Generation(result.outputText());

View File

@@ -55,12 +55,12 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
class BedrockAnthropicChatClientIT {
class BedrockAnthropicChatConnectorIT {
private static final Logger logger = LoggerFactory.getLogger(BedrockAnthropicChatClientIT.class);
private static final Logger logger = LoggerFactory.getLogger(BedrockAnthropicChatConnectorIT.class);
@Autowired
private BedrockAnthropicChatClient client;
private BedrockAnthropicChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -101,7 +101,7 @@ class BedrockAnthropicChatClientIT {
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -119,7 +119,7 @@ class BedrockAnthropicChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputParser.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -137,7 +137,7 @@ class BedrockAnthropicChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -161,7 +161,7 @@ class BedrockAnthropicChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConvert.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -209,8 +209,8 @@ class BedrockAnthropicChatClientIT {
}
@Bean
public BedrockAnthropicChatClient anthropicChatClient(AnthropicChatBedrockApi anthropicApi) {
return new BedrockAnthropicChatClient(anthropicApi);
public BedrockAnthropicChatConnector anthropicChatClient(AnthropicChatBedrockApi anthropicApi) {
return new BedrockAnthropicChatConnector(anthropicApi);
}
}

View File

@@ -38,7 +38,7 @@ public class BedrockAnthropicCreateRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new BedrockAnthropicChatClient(anthropicChatApi,
var client = new BedrockAnthropicChatConnector(anthropicChatApi,
AnthropicChatOptions.builder()
.withTemperature(66.6f)
.withTopK(66)

View File

@@ -59,12 +59,12 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
class BedrockAnthropic3ChatClientIT {
class BedrockAnthropic3ChatConnectorIT {
private static final Logger logger = LoggerFactory.getLogger(BedrockAnthropic3ChatClientIT.class);
private static final Logger logger = LoggerFactory.getLogger(BedrockAnthropic3ChatConnectorIT.class);
@Autowired
private BedrockAnthropic3ChatClient client;
private BedrockAnthropic3ChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -105,7 +105,7 @@ class BedrockAnthropic3ChatClientIT {
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -123,7 +123,7 @@ class BedrockAnthropic3ChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -142,7 +142,7 @@ class BedrockAnthropic3ChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -166,7 +166,7 @@ class BedrockAnthropic3ChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -211,7 +211,7 @@ class BedrockAnthropic3ChatClientIT {
var userMessage = new UserMessage("Explain what do you see o this picture?",
List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData)));
var response = client.call(new Prompt(List.of(userMessage)));
var response = client.execute(new Prompt(List.of(userMessage)));
logger.info(response.getResult().getOutput().getContent());
assertThat(response.getResult().getOutput().getContent()).contains("bananas", "apple", "basket");
@@ -228,8 +228,8 @@ class BedrockAnthropic3ChatClientIT {
}
@Bean
public BedrockAnthropic3ChatClient anthropicChatClient(Anthropic3ChatBedrockApi anthropicApi) {
return new BedrockAnthropic3ChatClient(anthropicApi);
public BedrockAnthropic3ChatConnector anthropicChatClient(Anthropic3ChatBedrockApi anthropicApi) {
return new BedrockAnthropic3ChatConnector(anthropicApi);
}
}

View File

@@ -37,7 +37,7 @@ public class BedrockAnthropic3CreateRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new BedrockAnthropic3ChatClient(anthropicChatApi,
var client = new BedrockAnthropic3ChatConnector(anthropicChatApi,
Anthropic3ChatOptions.builder()
.withTemperature(66.6f)
.withTopK(66)

View File

@@ -54,10 +54,10 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
class BedrockCohereChatClientIT {
class BedrockCohereChatConnectorIT {
@Autowired
private BedrockCohereChatClient client;
private BedrockCohereChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -98,7 +98,7 @@ class BedrockCohereChatClientIT {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -115,7 +115,7 @@ class BedrockCohereChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -134,7 +134,7 @@ class BedrockCohereChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -157,7 +157,7 @@ class BedrockCohereChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -205,8 +205,8 @@ class BedrockCohereChatClientIT {
}
@Bean
public BedrockCohereChatClient cohereChatClient(CohereChatBedrockApi cohereApi) {
return new BedrockCohereChatClient(cohereApi);
public BedrockCohereChatConnector cohereChatClient(CohereChatBedrockApi cohereApi) {
return new BedrockCohereChatConnector(cohereApi);
}
}

View File

@@ -45,7 +45,7 @@ public class BedrockCohereChatCreateRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new BedrockCohereChatClient(chatApi,
var client = new BedrockCohereChatConnector(chatApi,
BedrockCohereChatOptions.builder()
.withTemperature(66.6f)
.withTopK(66)

View File

@@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
class BedrockAi21Jurassic2ChatClientIT {
class BedrockAi21Jurassic2ChatConnectorIT {
@Autowired
private BedrockAi21Jurassic2ChatClient client;
private BedrockAi21Jurassic2ChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -66,7 +66,7 @@ class BedrockAi21Jurassic2ChatClientIT {
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -83,7 +83,7 @@ class BedrockAi21Jurassic2ChatClientIT {
UserMessage userMessage = new UserMessage("Can you express happiness using an emoji like 😄 ?");
Prompt prompt = new Prompt(List.of(userMessage), options);
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).matches(content -> content.contains("😄"));
}
@@ -103,7 +103,7 @@ class BedrockAi21Jurassic2ChatClientIT {
Prompt prompt = new Prompt(List.of(userMessage, systemMessage), options);
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).doesNotContain("😄");
}
@@ -120,7 +120,7 @@ class BedrockAi21Jurassic2ChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -135,7 +135,7 @@ class BedrockAi21Jurassic2ChatClientIT {
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("AI");
}
@@ -152,9 +152,9 @@ class BedrockAi21Jurassic2ChatClientIT {
}
@Bean
public BedrockAi21Jurassic2ChatClient bedrockAi21Jurassic2ChatClient(
public BedrockAi21Jurassic2ChatConnector bedrockAi21Jurassic2ChatClient(
Ai21Jurassic2ChatBedrockApi jurassic2ChatBedrockApi) {
return new BedrockAi21Jurassic2ChatClient(jurassic2ChatBedrockApi,
return new BedrockAi21Jurassic2ChatConnector(jurassic2ChatBedrockApi,
BedrockAi21Jurassic2ChatOptions.builder()
.withTemperature(0.5f)
.withMaxTokens(100)

View File

@@ -54,10 +54,10 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
class BedrockLlamaChatClientIT {
class BedrockLlamaChatConnectorIT {
@Autowired
private BedrockLlamaChatClient client;
private BedrockLlamaChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -98,7 +98,7 @@ class BedrockLlamaChatClientIT {
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -116,7 +116,7 @@ class BedrockLlamaChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -134,7 +134,7 @@ class BedrockLlamaChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -158,7 +158,7 @@ class BedrockLlamaChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -206,8 +206,8 @@ class BedrockLlamaChatClientIT {
}
@Bean
public BedrockLlamaChatClient llamaChatClient(LlamaChatBedrockApi llamaApi) {
return new BedrockLlamaChatClient(llamaApi,
public BedrockLlamaChatConnector llamaChatClient(LlamaChatBedrockApi llamaApi) {
return new BedrockLlamaChatConnector(llamaApi,
BedrockLlamaChatOptions.builder().withTemperature(0.5f).withMaxGenLen(100).withTopP(0.9f).build());
}

View File

@@ -45,7 +45,7 @@ public class BedrockLlamaCreateRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new BedrockLlamaChatClient(api,
var client = new BedrockLlamaChatConnector(api,
BedrockLlamaChatOptions.builder().withTemperature(66.6f).withMaxGenLen(666).withTopP(0.66f).build());
var request = client.createRequest(new Prompt("Test message content"));

View File

@@ -55,10 +55,10 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
class BedrockTitanChatClientIT {
class BedrockTitanChatConnectorIT {
@Autowired
private BedrockTitanChatClient client;
private BedrockTitanChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -99,7 +99,7 @@ class BedrockTitanChatClientIT {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -117,7 +117,7 @@ class BedrockTitanChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -138,7 +138,7 @@ class BedrockTitanChatClientIT {
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -162,7 +162,7 @@ class BedrockTitanChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -211,8 +211,8 @@ class BedrockTitanChatClientIT {
}
@Bean
public BedrockTitanChatClient titanChatClient(TitanChatBedrockApi titanApi) {
return new BedrockTitanChatClient(titanApi);
public BedrockTitanChatConnector titanChatClient(TitanChatBedrockApi titanApi) {
return new BedrockTitanChatConnector(titanApi);
}
}

View File

@@ -41,7 +41,7 @@ public class BedrockTitanChatCreateRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new BedrockTitanChatClient(api,
var client = new BedrockTitanChatConnector(api,
BedrockTitanChatOptions.builder()
.withTemperature(66.6f)
.withTopP(0.66f)

View File

@@ -22,7 +22,7 @@ import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.huggingface.api.TextGenerationInferenceApi;
@@ -34,12 +34,12 @@ import org.springframework.ai.huggingface.model.GenerateResponse;
import org.springframework.ai.chat.prompt.Prompt;
/**
* An implementation of {@link ChatClient} that interfaces with HuggingFace Inference
* An implementation of {@link ChatConnector} that interfaces with HuggingFace Inference
* Endpoints for text generation.
*
* @author Mark Pollack
*/
public class HuggingfaceChatClient implements ChatClient {
public class HuggingfaceChatConnector implements ChatConnector {
/**
* Token required for authenticating with the HuggingFace Inference API.
@@ -68,11 +68,12 @@ public class HuggingfaceChatClient implements ChatClient {
private int maxNewTokens = 1000;
/**
* Constructs a new HuggingfaceChatClient with the specified API token and base path.
* Constructs a new HuggingfaceChatConnector with the specified API token and base
* path.
* @param apiToken The API token for HuggingFace.
* @param basePath The base path for API requests.
*/
public HuggingfaceChatClient(final String apiToken, String basePath) {
public HuggingfaceChatConnector(final String apiToken, String basePath) {
this.apiToken = apiToken;
this.apiClient.setBasePath(basePath);
this.apiClient.addDefaultHeader("Authorization", "Bearer " + this.apiToken);
@@ -85,7 +86,7 @@ public class HuggingfaceChatClient implements ChatClient {
* @return ChatResponse containing the generated text and other related details.
*/
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
GenerateRequest generateRequest = new GenerateRequest();
generateRequest.setInputs(prompt.getContents());
GenerateParameters generateParameters = new GenerateParameters();

View File

@@ -23,7 +23,7 @@ import org.springframework.util.StringUtils;
public class HuggingfaceTestConfiguration {
@Bean
public HuggingfaceChatClient huggingfaceChatClient() {
public HuggingfaceChatConnector huggingfaceChatClient() {
String apiKey = System.getenv("HUGGINGFACE_API_KEY");
if (!StringUtils.hasText(apiKey)) {
throw new IllegalArgumentException(
@@ -31,7 +31,7 @@ public class HuggingfaceTestConfiguration {
}
// Created aws-mistral-7b-instruct-v0-1-805 via
// https://ui.endpoints.huggingface.co/
HuggingfaceChatClient huggingfaceChatClient = new HuggingfaceChatClient(apiKey,
HuggingfaceChatConnector huggingfaceChatClient = new HuggingfaceChatConnector(apiKey,
"https://f6hg7b3cvlmntp5i.us-east-1.aws.endpoints.huggingface.cloud");
return huggingfaceChatClient;
}

View File

@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.huggingface.HuggingfaceChatClient;
import org.springframework.ai.huggingface.HuggingfaceChatConnector;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -33,7 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ClientIT {
@Autowired
protected HuggingfaceChatClient huggingfaceChatClient;
protected HuggingfaceChatConnector huggingfaceChatClient;
@Test
void helloWorldCompletion() {
@@ -46,7 +46,7 @@ public class ClientIT {
[/INST]
""";
Prompt prompt = new Prompt(mistral7bInstruct);
ChatResponse chatResponse = huggingfaceChatClient.call(prompt);
ChatResponse chatResponse = huggingfaceChatClient.execute(prompt);
assertThat(chatResponse.getResult().getOutput().getContent()).isNotEmpty();
String expectedResponse = """
```json

View File

@@ -17,7 +17,7 @@ package org.springframework.ai.mistralai;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -50,9 +50,9 @@ import java.util.concurrent.ConcurrentHashMap;
* @author Grogdunn
* @since 0.8.1
*/
public class MistralAiChatClient extends
public class MistralAiChatConnector extends
AbstractFunctionCallSupport<MistralAiApi.ChatCompletionMessage, MistralAiApi.ChatCompletionRequest, ResponseEntity<MistralAiApi.ChatCompletion>>
implements ChatClient, StreamingChatClient {
implements ChatConnector, StreamingChatClient {
private final Logger log = LoggerFactory.getLogger(getClass());
@@ -68,7 +68,7 @@ public class MistralAiChatClient extends
private final RetryTemplate retryTemplate;
public MistralAiChatClient(MistralAiApi mistralAiApi) {
public MistralAiChatConnector(MistralAiApi mistralAiApi) {
this(mistralAiApi,
MistralAiChatOptions.builder()
.withTemperature(0.7f)
@@ -78,11 +78,11 @@ public class MistralAiChatClient extends
.build());
}
public MistralAiChatClient(MistralAiApi mistralAiApi, MistralAiChatOptions options) {
public MistralAiChatConnector(MistralAiApi mistralAiApi, MistralAiChatOptions options) {
this(mistralAiApi, options, null, RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
public MistralAiChatClient(MistralAiApi mistralAiApi, MistralAiChatOptions options,
public MistralAiChatConnector(MistralAiApi mistralAiApi, MistralAiChatOptions options,
FunctionCallbackContext functionCallbackContext, RetryTemplate retryTemplate) {
super(functionCallbackContext);
Assert.notNull(mistralAiApi, "MistralAiApi must not be null");
@@ -94,7 +94,7 @@ public class MistralAiChatClient extends
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
var request = createRequest(prompt, false);
return retryTemplate.execute(ctx -> {

View File

@@ -101,11 +101,11 @@ public class MistralAiChatOptions implements FunctionCallingOptions, ChatOptions
private @JsonProperty("tool_choice") ToolChoice toolChoice;
/**
* MistralAI Tool Function Callbacks to register with the ChatClient. For Prompt
* MistralAI Tool Function Callbacks to register with the ChatConnector. For Prompt
* Options the functionCallbacks are automatically enabled for the duration of the
* prompt execution. For Default Options the functionCallbacks are registered but
* disabled by default. Use the enableFunctions to set the functions from the registry
* to be used by the ChatClient chat completion requests.
* to be used by the ChatConnector chat completion requests.
*/
@NestedConfigurationProperty
@JsonIgnore

View File

@@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".+")
public class MistralAiChatCompletionRequestTest {
MistralAiChatClient chatClient = new MistralAiChatClient(new MistralAiApi("test"));
MistralAiChatConnector chatClient = new MistralAiChatConnector(new MistralAiApi("test"));
@Test
void chatCompletionDefaultRequestTest() {

View File

@@ -27,7 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -56,12 +56,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@SpringBootTest(classes = MistralAiTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".+")
class MistralAiChatClientIT {
class MistralAiChatConnectorIT {
private static final Logger logger = LoggerFactory.getLogger(MistralAiChatClientIT.class);
private static final Logger logger = LoggerFactory.getLogger(MistralAiChatConnectorIT.class);
@Autowired
protected ChatClient chatClient;
protected ChatConnector chatConnector;
@Autowired
protected StreamingChatClient streamingChatClient;
@@ -90,7 +90,7 @@ class MistralAiChatClientIT {
// NOTE: Mistral expects the system message to be before the user message or will
// fail with 400 error.
Prompt prompt = new Prompt(List.of(systemMessage, userMessage));
ChatResponse response = chatClient.call(prompt);
ChatResponse response = chatConnector.execute(prompt);
assertThat(response.getResults()).hasSize(1);
assertThat(response.getResults().get(0).getOutput().getContent()).contains("Blackbeard");
}
@@ -108,7 +108,7 @@ class MistralAiChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.chatClient.call(prompt).getResult();
Generation generation = this.chatConnector.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -126,7 +126,7 @@ class MistralAiChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatConnector.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -148,7 +148,7 @@ class MistralAiChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatConnector.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
logger.info("" + actorsFilms);
@@ -186,7 +186,7 @@ class MistralAiChatClientIT {
}
@Test
void functionCallTest() {
void functionExecuteTest() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco?");
@@ -201,7 +201,7 @@ class MistralAiChatClientIT {
.build()))
.build();
ChatResponse response = chatClient.call(new Prompt(messages, promptOptions));
ChatResponse response = chatConnector.execute(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);
@@ -209,7 +209,7 @@ class MistralAiChatClientIT {
}
@Test
void streamFunctionCallTest() {
void streamFunctionExecuteTest() {
UserMessage userMessage = new UserMessage("What's the weather like in Tokyo, Japan?");

View File

@@ -82,7 +82,7 @@ public class MistralAiRetryTests {
private @Mock MistralAiApi mistralAiApi;
private MistralAiChatClient chatClient;
private MistralAiChatConnector chatClient;
private MistralAiEmbeddingClient embeddingClient;
@@ -92,7 +92,7 @@ public class MistralAiRetryTests {
retryListener = new TestRetryListener();
retryTemplate.registerListener(retryListener);
chatClient = new MistralAiChatClient(mistralAiApi,
chatClient = new MistralAiChatConnector(mistralAiApi,
MistralAiChatOptions.builder()
.withTemperature(0.7f)
.withTopP(1f)
@@ -118,7 +118,7 @@ public class MistralAiRetryTests {
.thenThrow(new TransientAiException("Transient Error 2"))
.thenReturn(ResponseEntity.of(Optional.of(expectedChatCompletion)));
var result = chatClient.call(new Prompt("text"));
var result = chatClient.execute(new Prompt("text"));
assertThat(result).isNotNull();
assertThat(result.getResult().getOutput().getContent()).isSameAs("Response");
@@ -130,7 +130,7 @@ public class MistralAiRetryTests {
public void mistralAiChatNonTransientError() {
when(mistralAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class)))
.thenThrow(new RuntimeException("Non Transient Error"));
assertThrows(RuntimeException.class, () -> chatClient.call(new Prompt("text")));
assertThrows(RuntimeException.class, () -> chatClient.execute(new Prompt("text")));
}
@Test

View File

@@ -41,8 +41,8 @@ public class MistralAiTestConfiguration {
}
@Bean
public MistralAiChatClient mistralAiChatClient(MistralAiApi mistralAiApi) {
return new MistralAiChatClient(mistralAiApi,
public MistralAiChatConnector mistralAiChatClient(MistralAiApi mistralAiApi) {
return new MistralAiChatConnector(mistralAiApi,
MistralAiChatOptions.builder().withModel(MistralAiApi.ChatModel.MIXTRAL.getValue()).build());
}

View File

@@ -21,7 +21,7 @@ import java.util.List;
import org.springframework.ai.ollama.metadata.OllamaChatResponseMetadata;
import reactor.core.publisher.Flux;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -39,7 +39,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* {@link ChatClient} implementation for {@literal Ollama}.
* {@link ChatConnector} implementation for {@literal Ollama}.
*
* Ollama allows developers to run large language models and generate embeddings locally.
* It supports open-source models available on [Ollama AI
@@ -52,7 +52,7 @@ import org.springframework.util.StringUtils;
* @author Christian Tzolov
* @since 0.8.0
*/
public class OllamaChatClient implements ChatClient, StreamingChatClient {
public class OllamaChatConnector implements ChatConnector, StreamingChatClient {
/**
* Low-level Ollama API library.
@@ -64,11 +64,11 @@ public class OllamaChatClient implements ChatClient, StreamingChatClient {
*/
private OllamaOptions defaultOptions;
public OllamaChatClient(OllamaApi chatApi) {
public OllamaChatConnector(OllamaApi chatApi) {
this(chatApi, OllamaOptions.create().withModel(OllamaOptions.DEFAULT_MODEL));
}
public OllamaChatClient(OllamaApi chatApi, OllamaOptions defaultOptions) {
public OllamaChatConnector(OllamaApi chatApi, OllamaOptions defaultOptions) {
Assert.notNull(chatApi, "OllamaApi must not be null");
Assert.notNull(defaultOptions, "DefaultOptions must not be null");
this.chatApi = chatApi;
@@ -79,7 +79,7 @@ public class OllamaChatClient implements ChatClient, StreamingChatClient {
* @deprecated Use {@link OllamaOptions#setModel} instead.
*/
@Deprecated
public OllamaChatClient withModel(String model) {
public OllamaChatConnector withModel(String model) {
this.defaultOptions.setModel(model);
return this;
}
@@ -88,13 +88,13 @@ public class OllamaChatClient implements ChatClient, StreamingChatClient {
* @deprecated Use {@link OllamaOptions} constructor instead.
*/
@Deprecated
public OllamaChatClient withDefaultOptions(OllamaOptions options) {
public OllamaChatConnector withDefaultOptions(OllamaOptions options) {
this.defaultOptions = options;
return this;
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
OllamaApi.ChatResponse response = this.chatApi.chat(ollamaChatRequest(prompt, false));

View File

@@ -56,11 +56,11 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@Testcontainers
@Disabled("For manual smoke testing only.")
class OllamaChatClientIT {
class OllamaChatConnectorIT {
private static String MODEL = "mistral";
private static final Log logger = LogFactory.getLog(OllamaChatClientIT.class);
private static final Log logger = LogFactory.getLog(OllamaChatConnectorIT.class);
@Container
static OllamaContainer ollamaContainer = new OllamaContainer("ollama/ollama:0.1.32");
@@ -77,7 +77,7 @@ class OllamaChatClientIT {
}
@Autowired
private OllamaChatClient client;
private OllamaChatConnector client;
@Test
void roleTest() {
@@ -95,13 +95,13 @@ class OllamaChatClientIT {
Prompt prompt = new Prompt(List.of(userMessage, systemMessage), portableOptions);
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
// ollama specific options
var ollamaOptions = new OllamaOptions().withLowVRAM(true);
response = client.call(new Prompt(List.of(userMessage, systemMessage), ollamaOptions));
response = client.execute(new Prompt(List.of(userMessage, systemMessage), ollamaOptions));
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -109,7 +109,7 @@ class OllamaChatClientIT {
@Test
void usageTest() {
Prompt prompt = new Prompt("Tell me a joke");
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
Usage usage = response.getMetadata().getUsage();
assertThat(usage).isNotNull();
@@ -131,7 +131,7 @@ class OllamaChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -151,7 +151,7 @@ class OllamaChatClientIT {
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -173,7 +173,7 @@ class OllamaChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -219,8 +219,8 @@ class OllamaChatClientIT {
}
@Bean
public OllamaChatClient ollamaChat(OllamaApi ollamaApi) {
return new OllamaChatClient(ollamaApi, OllamaOptions.create().withModel(MODEL).withTemperature(0.9f));
public OllamaChatConnector ollamaChat(OllamaApi ollamaApi) {
return new OllamaChatConnector(ollamaApi, OllamaOptions.create().withModel(MODEL).withTemperature(0.9f));
}
}

View File

@@ -44,11 +44,11 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@Testcontainers
@Disabled("For manual smoke testing only.")
class OllamaChatClientMultimodalIT {
class OllamaChatConnectorMultimodalIT {
private static String MODEL = "llava";
private static final Log logger = LogFactory.getLog(OllamaChatClientIT.class);
private static final Log logger = LogFactory.getLog(OllamaChatConnectorIT.class);
@Container
static OllamaContainer ollamaContainer = new OllamaContainer("ollama/ollama:0.1.32");
@@ -65,7 +65,7 @@ class OllamaChatClientMultimodalIT {
}
@Autowired
private OllamaChatClient client;
private OllamaChatConnector client;
@Test
void multiModalityTest() throws IOException {
@@ -75,7 +75,7 @@ class OllamaChatClientMultimodalIT {
var userMessage = new UserMessage("Explain what do you see on this picture?",
List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData)));
var response = client.call(new Prompt(List.of(userMessage)));
var response = client.execute(new Prompt(List.of(userMessage)));
logger.info(response.getResult().getOutput().getContent());
assertThat(response.getResult().getOutput().getContent()).contains("bananas", "apple", "basket");
@@ -90,8 +90,8 @@ class OllamaChatClientMultimodalIT {
}
@Bean
public OllamaChatClient ollamaChat(OllamaApi ollamaApi) {
return new OllamaChatClient(ollamaApi, OllamaOptions.create().withModel(MODEL).withTemperature(0.9f));
public OllamaChatConnector ollamaChat(OllamaApi ollamaApi) {
return new OllamaChatConnector(ollamaApi, OllamaOptions.create().withModel(MODEL).withTemperature(0.9f));
}
}

View File

@@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class OllamaChatRequestTests {
OllamaChatClient client = new OllamaChatClient(new OllamaApi(),
OllamaChatConnector client = new OllamaChatConnector(new OllamaApi(),
new OllamaOptions().withModel("MODEL_NAME").withTopK(99).withTemperature(66.6f).withNumGPU(1));
@Test
@@ -105,7 +105,7 @@ public class OllamaChatRequestTests {
@Test
public void createRequestWithDefaultOptionsModelOverride() {
OllamaChatClient client2 = new OllamaChatClient(new OllamaApi(),
OllamaChatConnector client2 = new OllamaChatConnector(new OllamaApi(),
new OllamaOptions().withModel("DEFAULT_OPTIONS_MODEL"));
var request = client2.ollamaChatRequest(new Prompt("Test message content"), true);

View File

@@ -17,7 +17,7 @@ package org.springframework.ai.openai;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -58,8 +58,8 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* {@link ChatClient} and {@link StreamingChatClient} implementation for {@literal OpenAI}
* backed by {@link OpenAiApi}.
* {@link ChatConnector} and {@link StreamingChatClient} implementation for
* {@literal OpenAI} backed by {@link OpenAiApi}.
*
* @author Mark Pollack
* @author Christian Tzolov
@@ -68,15 +68,15 @@ import java.util.concurrent.ConcurrentHashMap;
* @author Josh Long
* @author Jemin Huh
* @author Grogdunn
* @see ChatClient
* @see ChatConnector
* @see StreamingChatClient
* @see OpenAiApi
*/
public class OpenAiChatClient extends
public class OpenAiChatConnector extends
AbstractFunctionCallSupport<ChatCompletionMessage, OpenAiApi.ChatCompletionRequest, ResponseEntity<ChatCompletion>>
implements ChatClient, StreamingChatClient {
implements ChatConnector, StreamingChatClient {
private static final Logger logger = LoggerFactory.getLogger(OpenAiChatClient.class);
private static final Logger logger = LoggerFactory.getLogger(OpenAiChatConnector.class);
/**
* The default options used for the chat completion requests.
@@ -94,35 +94,35 @@ public class OpenAiChatClient extends
private final OpenAiApi openAiApi;
/**
* Creates an instance of the OpenAiChatClient.
* Creates an instance of the OpenAiChatConnector.
* @param openAiApi The OpenAiApi instance to be used for interacting with the OpenAI
* Chat API.
* @throws IllegalArgumentException if openAiApi is null
*/
public OpenAiChatClient(OpenAiApi openAiApi) {
public OpenAiChatConnector(OpenAiApi openAiApi) {
this(openAiApi,
OpenAiChatOptions.builder().withModel(OpenAiApi.DEFAULT_CHAT_MODEL).withTemperature(0.7f).build());
}
/**
* Initializes an instance of the OpenAiChatClient.
* Initializes an instance of the OpenAiChatConnector.
* @param openAiApi The OpenAiApi instance to be used for interacting with the OpenAI
* Chat API.
* @param options The OpenAiChatOptions to configure the chat client.
*/
public OpenAiChatClient(OpenAiApi openAiApi, OpenAiChatOptions options) {
public OpenAiChatConnector(OpenAiApi openAiApi, OpenAiChatOptions options) {
this(openAiApi, options, null, RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
/**
* Initializes a new instance of the OpenAiChatClient.
* Initializes a new instance of the OpenAiChatConnector.
* @param openAiApi The OpenAiApi instance to be used for interacting with the OpenAI
* Chat API.
* @param options The OpenAiChatOptions to configure the chat client.
* @param functionCallbackContext The function callback context.
* @param retryTemplate The retry template.
*/
public OpenAiChatClient(OpenAiApi openAiApi, OpenAiChatOptions options,
public OpenAiChatConnector(OpenAiApi openAiApi, OpenAiChatOptions options,
FunctionCallbackContext functionCallbackContext, RetryTemplate retryTemplate) {
super(functionCallbackContext);
Assert.notNull(openAiApi, "OpenAiApi must not be null");
@@ -134,7 +134,7 @@ public class OpenAiChatClient extends
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
ChatCompletionRequest request = createRequest(prompt, false);

View File

@@ -134,10 +134,10 @@ public class OpenAiChatOptions implements FunctionCallingOptions, ChatOptions {
private @JsonProperty("user") String user;
/**
* OpenAI Tool Function Callbacks to register with the ChatClient.
* OpenAI Tool Function Callbacks to register with the ChatConnector.
* For Prompt Options the functionCallbacks are automatically enabled for the duration of the prompt execution.
* For Default Options the functionCallbacks are registered but disabled by default. Use the enableFunctions to set the functions
* from the registry to be used by the ChatClient chat completion requests.
* from the registry to be used by the ChatConnector chat completion requests.
*/
@NestedConfigurationProperty
@JsonIgnore

View File

@@ -0,0 +1,56 @@
package org.springframework.ai.openai;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
class ChatClientTest {
@Configuration
static class ChatClientTestConfiguration {
@Bean
ChatClient client(OpenAiChatConnector openAiChatConnector) {
return ChatClient.builder(openAiChatConnector).defaultSystemPrompt("""
you are customer service agent designed to answer questions
about a the user, {userName}'s, orders. Here are their outstanding orders.
{orders}
""").defaultFunctions("cancelOrder", "refundOrder").build();
}
}
private final ChatClient singularity;
ChatClientTest(@Autowired ChatClient singularity) {
this.singularity = singularity;
}
@Test
void products() throws Exception {
var product0 = this.client.userPrompt("tell me about this product from the merchant {merchant}")
.userPromptParams(Map.of("merchant", "24u92"))
.execute(Product.class);
/*
* var product1 = this.client .build() .userPromptParam("a", "b")
* .functions("cancelOrder", "refundOrder") .execute(new
* ParameterizedTypeReference<Product>() { });
*
* var product2 = this.client
* .userPrompt("tell me about this product from the merchant {merchant}",
* Map.of("merchant", "232")) .execute(Product.class);
*/
}
record Product(String sku) {
}
}

View File

@@ -34,7 +34,7 @@ public class ChatCompletionRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new OpenAiChatClient(new OpenAiApi("TEST"),
var client = new OpenAiChatConnector(new OpenAiApi("TEST"),
OpenAiChatOptions.builder().withModel("DEFAULT_MODEL").withTemperature(66.6f).build());
var request = client.createRequest(new Prompt("Test message content"), false);
@@ -60,7 +60,7 @@ public class ChatCompletionRequestTests {
final String TOOL_FUNCTION_NAME = "CurrentWeather";
var client = new OpenAiChatClient(new OpenAiApi("TEST"),
var client = new OpenAiChatConnector(new OpenAiApi("TEST"),
OpenAiChatOptions.builder().withModel("DEFAULT_MODEL").build());
var request = client.createRequest(new Prompt("Test message content",
@@ -90,7 +90,7 @@ public class ChatCompletionRequestTests {
final String TOOL_FUNCTION_NAME = "CurrentWeather";
var client = new OpenAiChatClient(new OpenAiApi("TEST"),
var client = new OpenAiChatConnector(new OpenAiApi("TEST"),
OpenAiChatOptions.builder()
.withModel("DEFAULT_MODEL")
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())

View File

@@ -51,8 +51,8 @@ public class OpenAiTestConfiguration {
}
@Bean
public OpenAiChatClient openAiChatClient(OpenAiApi api) {
OpenAiChatClient openAiChatClient = new OpenAiChatClient(api);
public OpenAiChatConnector openAiChatClient(OpenAiApi api) {
OpenAiChatConnector openAiChatClient = new OpenAiChatConnector(api);
return openAiChatClient;
}

View File

@@ -26,8 +26,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.document.Document;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.OpenAiTestConfiguration;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.testutils.AbstractIT;
import org.springframework.ai.chat.prompt.Prompt;
@@ -61,7 +61,7 @@ public class AcmeIT extends AbstractIT {
private OpenAiEmbeddingClient embeddingClient;
@Autowired
private OpenAiChatClient chatClient;
private OpenAiChatConnector chatClient;
@Test
void beanTest() {
@@ -108,7 +108,7 @@ public class AcmeIT extends AbstractIT {
logger.info("Asking AI generative to reply to question.");
Prompt prompt = new Prompt(List.of(systemMessage, userMessage));
logger.info("AI responded.");
ChatResponse response = chatClient.call(prompt);
ChatResponse response = chatClient.execute(prompt);
evaluateQuestionAndAnswer(userQuery, response, true);
}

View File

@@ -26,8 +26,8 @@ import org.springframework.ai.chat.metadata.ChatResponseMetadata;
import org.springframework.ai.chat.metadata.PromptMetadata;
import org.springframework.ai.chat.metadata.RateLimit;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
@@ -57,7 +57,7 @@ public class OpenAiChatClientWithChatResponseMetadataTests {
private static String TEST_API_KEY = "sk-1234567890";
@Autowired
private OpenAiChatClient openAiChatClient;
private OpenAiChatConnector openAiChatClient;
@Autowired
private MockRestServiceServer server;
@@ -74,7 +74,7 @@ public class OpenAiChatClientWithChatResponseMetadataTests {
Prompt prompt = new Prompt("Reach for the sky.");
ChatResponse response = this.openAiChatClient.call(prompt);
ChatResponse response = this.openAiChatClient.execute(prompt);
assertThat(response).isNotNull();
@@ -171,8 +171,8 @@ public class OpenAiChatClientWithChatResponseMetadataTests {
}
@Bean
public OpenAiChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
public OpenAiChatConnector openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatConnector(openAiApi);
}
}

View File

@@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionRequest;
@@ -41,14 +41,14 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
*/
@SpringBootTest(classes = OpenAiChatClient2IT.Config.class)
@SpringBootTest(classes = OpenAiChatConnector2IT.Config.class)
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+")
public class OpenAiChatClient2IT {
public class OpenAiChatConnector2IT {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OpenAiChatClient openAiChatClient;
private OpenAiChatConnector openAiChatClient;
@Test
void responseFormatTest() throws JsonMappingException, JsonProcessingException {
@@ -67,7 +67,7 @@ public class OpenAiChatClient2IT {
.withResponseFormat(new ChatCompletionRequest.ResponseFormat("json_object"))
.build());
ChatResponse response = this.openAiChatClient.call(prompt);
ChatResponse response = this.openAiChatClient.execute(prompt);
assertThat(response).isNotNull();
@@ -99,8 +99,8 @@ public class OpenAiChatClient2IT {
}
@Bean
public OpenAiChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
public OpenAiChatConnector openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatConnector(openAiApi);
}
}

View File

@@ -60,9 +60,9 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = OpenAiTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+")
class OpenAiChatClientIT extends AbstractIT {
class OpenAiChatConnectorIT extends AbstractIT {
private static final Logger logger = LoggerFactory.getLogger(OpenAiChatClientIT.class);
private static final Logger logger = LoggerFactory.getLogger(OpenAiChatConnectorIT.class);
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -74,7 +74,7 @@ class OpenAiChatClientIT extends AbstractIT {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Bob", "voice", "pirate"));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = chatClient.call(prompt);
ChatResponse response = chatConnector.execute(prompt);
assertThat(response.getResults()).hasSize(1);
assertThat(response.getResults().get(0).getOutput().getContent()).contains("Blackbeard");
// needs fine tuning... evaluateQuestionAndAnswer(request, response, false);
@@ -93,7 +93,7 @@ class OpenAiChatClientIT extends AbstractIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.chatClient.call(prompt).getResult();
Generation generation = this.chatConnector.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -112,7 +112,7 @@ class OpenAiChatClientIT extends AbstractIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatConnector.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -131,7 +131,7 @@ class OpenAiChatClientIT extends AbstractIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatConnector.execute(prompt).getResult();
ActorsFilms actorsFilms = outputConverter.convert(generation.getOutput().getContent());
}
@@ -151,7 +151,7 @@ class OpenAiChatClientIT extends AbstractIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
Generation generation = chatConnector.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
logger.info("" + actorsFilms);
@@ -189,7 +189,7 @@ class OpenAiChatClientIT extends AbstractIT {
}
@Test
void functionCallTest() {
void functionExecuteTest() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");
@@ -204,7 +204,7 @@ class OpenAiChatClientIT extends AbstractIT {
.build()))
.build();
ChatResponse response = chatClient.call(new Prompt(messages, promptOptions));
ChatResponse response = chatConnector.execute(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);
@@ -214,7 +214,7 @@ class OpenAiChatClientIT extends AbstractIT {
}
@Test
void streamFunctionCallTest() {
void streamFunctionExecuteTest() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");
@@ -255,8 +255,8 @@ class OpenAiChatClientIT extends AbstractIT {
var userMessage = new UserMessage("Explain what do you see on this picture?",
List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData)));
var response = chatClient
.call(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withModel(modelName).build()));
var response = chatConnector
.execute(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withModel(modelName).build()));
logger.info(response.getResult().getOutput().getContent());
assertThat(response.getResult().getOutput().getContent()).contains("bananas", "apple");
@@ -271,8 +271,8 @@ class OpenAiChatClientIT extends AbstractIT {
.of(new Media(MimeTypeUtils.IMAGE_PNG,
new URL("https://docs.spring.io/spring-ai/reference/1.0-SNAPSHOT/_images/multimodal.test.png"))));
ChatResponse response = chatClient
.call(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withModel(modelName).build()));
ChatResponse response = chatConnector
.execute(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withModel(modelName).build()));
logger.info(response.getResult().getOutput().getContent());
assertThat(response.getResult().getOutput().getContent()).contains("bananas", "apple");

View File

@@ -31,7 +31,7 @@ import org.springframework.ai.image.ImageMessage;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.openai.OpenAiAudioTranscriptionClient;
import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.OpenAiEmbeddingOptions;
@@ -107,7 +107,7 @@ public class OpenAiRetryTests {
private @Mock OpenAiImageApi openAiImageApi;
private OpenAiChatClient chatClient;
private OpenAiChatConnector chatClient;
private OpenAiEmbeddingClient embeddingClient;
@@ -121,7 +121,7 @@ public class OpenAiRetryTests {
retryListener = new TestRetryListener();
retryTemplate.registerListener(retryListener);
chatClient = new OpenAiChatClient(openAiApi, OpenAiChatOptions.builder().build(), null, retryTemplate);
chatClient = new OpenAiChatConnector(openAiApi, OpenAiChatOptions.builder().build(), null, retryTemplate);
embeddingClient = new OpenAiEmbeddingClient(openAiApi, MetadataMode.EMBED,
OpenAiEmbeddingOptions.builder().build(), retryTemplate);
audioTranscriptionClient = new OpenAiAudioTranscriptionClient(openAiAudioApi,
@@ -146,7 +146,7 @@ public class OpenAiRetryTests {
.thenThrow(new TransientAiException("Transient Error 2"))
.thenReturn(ResponseEntity.of(Optional.of(expectedChatCompletion)));
var result = chatClient.call(new Prompt("text"));
var result = chatClient.execute(new Prompt("text"));
assertThat(result).isNotNull();
assertThat(result.getResult().getOutput().getContent()).isSameAs("Response");
@@ -158,7 +158,7 @@ public class OpenAiRetryTests {
public void openAiChatNonTransientError() {
when(openAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class)))
.thenThrow(new RuntimeException("Non Transient Error"));
assertThrows(RuntimeException.class, () -> chatClient.call(new Prompt("text")));
assertThrows(RuntimeException.class, () -> chatClient.execute(new Prompt("text")));
}
@Test

View File

@@ -23,6 +23,7 @@ import io.qdrant.client.QdrantGrpcClient;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.chat.service.ChatService;
import org.springframework.ai.chat.service.StreamingChatService;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.qdrant.QdrantContainer;
@@ -36,7 +37,6 @@ import org.springframework.ai.chat.memory.SystemPromptChatMemoryAugmentor;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.evaluation.BaseMemoryTest;
import org.springframework.ai.evaluation.RelevancyEvaluator;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.tokenizer.JTokkitTokenCountEstimator;
@@ -75,8 +75,8 @@ public class ChatMemoryLongTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public OpenAiChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
public OpenAiChatConnector openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatConnector(openAiApi);
}
@Bean
@@ -98,7 +98,7 @@ public class ChatMemoryLongTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public ChatService memoryChatService(OpenAiChatClient chatClient, VectorStore vectorStore,
public ChatService memoryChatService(OpenAiChatConnector chatClient, VectorStore vectorStore,
TokenCountEstimator tokenCountEstimator) {
return PromptTransformingChatService.builder(chatClient)
@@ -110,7 +110,7 @@ public class ChatMemoryLongTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public StreamingChatService memoryStreamingChatService(OpenAiChatClient streamingChatClient,
public StreamingChatService memoryStreamingChatService(OpenAiChatConnector streamingChatClient,
VectorStore vectorStore, TokenCountEstimator tokenCountEstimator) {
return StreamingPromptTransformingChatService.builder(streamingChatClient)
@@ -122,7 +122,7 @@ public class ChatMemoryLongTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public RelevancyEvaluator relevancyEvaluator(OpenAiChatClient chatClient) {
public RelevancyEvaluator relevancyEvaluator(OpenAiChatConnector chatClient) {
return new RelevancyEvaluator(chatClient);
}

View File

@@ -31,7 +31,7 @@ import org.springframework.ai.chat.memory.LastMaxTokenSizeContentTransformer;
import org.springframework.ai.chat.memory.MessageChatMemoryAugmentor;
import org.springframework.ai.evaluation.BaseMemoryTest;
import org.springframework.ai.evaluation.RelevancyEvaluator;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.tokenizer.JTokkitTokenCountEstimator;
import org.springframework.ai.tokenizer.TokenCountEstimator;
@@ -59,8 +59,8 @@ public class ChatMemoryShortTermMessageListIT extends BaseMemoryTest {
}
@Bean
public OpenAiChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
public OpenAiChatConnector openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatConnector(openAiApi);
}
@Bean
@@ -74,7 +74,7 @@ public class ChatMemoryShortTermMessageListIT extends BaseMemoryTest {
}
@Bean
public ChatService memoryChatService(OpenAiChatClient chatClient, ChatMemory chatHistory,
public ChatService memoryChatService(OpenAiChatConnector chatClient, ChatMemory chatHistory,
TokenCountEstimator tokenCountEstimator) {
return PromptTransformingChatService.builder(chatClient)
@@ -86,7 +86,7 @@ public class ChatMemoryShortTermMessageListIT extends BaseMemoryTest {
}
@Bean
public StreamingChatService memoryStreamingChatService(OpenAiChatClient streamingChatClient,
public StreamingChatService memoryStreamingChatService(OpenAiChatConnector streamingChatClient,
ChatMemory chatHistory, TokenCountEstimator tokenCountEstimator) {
return StreamingPromptTransformingChatService.builder(streamingChatClient)
@@ -98,7 +98,7 @@ public class ChatMemoryShortTermMessageListIT extends BaseMemoryTest {
}
@Bean
public RelevancyEvaluator relevancyEvaluator(OpenAiChatClient chatClient) {
public RelevancyEvaluator relevancyEvaluator(OpenAiChatConnector chatClient) {
return new RelevancyEvaluator(chatClient);
}

View File

@@ -32,7 +32,7 @@ import org.springframework.ai.chat.memory.LastMaxTokenSizeContentTransformer;
import org.springframework.ai.chat.memory.SystemPromptChatMemoryAugmentor;
import org.springframework.ai.evaluation.BaseMemoryTest;
import org.springframework.ai.evaluation.RelevancyEvaluator;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.tokenizer.JTokkitTokenCountEstimator;
import org.springframework.ai.tokenizer.TokenCountEstimator;
@@ -60,8 +60,8 @@ public class ChatMemoryShortTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public OpenAiChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
public OpenAiChatConnector openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatConnector(openAiApi);
}
@Bean
@@ -75,7 +75,7 @@ public class ChatMemoryShortTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public ChatService memoryChatService(OpenAiChatClient chatClient, ChatMemory chatHistory,
public ChatService memoryChatService(OpenAiChatConnector chatClient, ChatMemory chatHistory,
TokenCountEstimator tokenCountEstimator) {
return PromptTransformingChatService.builder(chatClient)
@@ -87,7 +87,7 @@ public class ChatMemoryShortTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public StreamingChatService memoryStreamingChatService(OpenAiChatClient streamingChatClient,
public StreamingChatService memoryStreamingChatService(OpenAiChatConnector streamingChatClient,
ChatMemory chatHistory, TokenCountEstimator tokenCountEstimator) {
return StreamingPromptTransformingChatService.builder(streamingChatClient)
@@ -99,7 +99,7 @@ public class ChatMemoryShortTermSystemPromptIT extends BaseMemoryTest {
}
@Bean
public RelevancyEvaluator relevancyEvaluator(OpenAiChatClient chatClient) {
public RelevancyEvaluator relevancyEvaluator(OpenAiChatConnector chatClient) {
return new RelevancyEvaluator(chatClient);
}

View File

@@ -50,10 +50,9 @@ import org.springframework.ai.chat.prompt.transformer.VectorStoreRetriever;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentTransformer;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.evaluation.EvaluationRequest;
import org.springframework.ai.evaluation.EvaluationResponse;
import org.springframework.ai.evaluation.RelevancyEvaluator;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.reader.JsonReader;
@@ -164,8 +163,8 @@ public class LongShortTermChatMemoryWithRagIT {
}
@Bean
public OpenAiChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
public OpenAiChatConnector openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatConnector(openAiApi);
}
@Bean
@@ -187,7 +186,7 @@ public class LongShortTermChatMemoryWithRagIT {
}
@Bean
public ChatService memoryChatService(OpenAiChatClient chatClient, VectorStore vectorStore,
public ChatService memoryChatService(OpenAiChatConnector chatClient, VectorStore vectorStore,
TokenCountEstimator tokenCountEstimator, ChatMemory chatHistory) {
return PromptTransformingChatService.builder(chatClient)
@@ -224,7 +223,7 @@ public class LongShortTermChatMemoryWithRagIT {
}
// @Bean
// public StreamingChatService memoryStreamingChatAgent(OpenAiChatClient
// public StreamingChatService memoryStreamingChatAgent(OpenAiChatConnector
// streamingChatClient,
// VectorStore vectorStore, TokenCountEstimator tokenCountEstimator, ChatHistory
// chatHistory) {
@@ -241,7 +240,7 @@ public class LongShortTermChatMemoryWithRagIT {
// }
@Bean
public RelevancyEvaluator relevancyEvaluator(OpenAiChatClient chatClient) {
public RelevancyEvaluator relevancyEvaluator(OpenAiChatConnector chatClient) {
// Use GPT 4 as a better model for determining relevancy. gpt 3.5 makes basic
// mistakes
OpenAiChatOptions openAiChatOptions = OpenAiChatOptions.builder()

View File

@@ -23,15 +23,16 @@ import io.qdrant.client.QdrantClient;
import io.qdrant.client.QdrantGrpcClient;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.service.ChatService;
import org.springframework.ai.chat.prompt.transformer.TransformerContentType;
import org.springframework.ai.document.Document;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.qdrant.QdrantContainer;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.service.PromptTransformingChatService;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
@@ -39,10 +40,8 @@ import org.springframework.ai.chat.prompt.transformer.ChatServiceContext;
import org.springframework.ai.chat.prompt.transformer.QuestionContextAugmentor;
import org.springframework.ai.chat.prompt.transformer.VectorStoreRetriever;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.evaluation.EvaluationRequest;
import org.springframework.ai.evaluation.EvaluationResponse;
import org.springframework.ai.evaluation.RelevancyEvaluator;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.reader.JsonReader;
@@ -72,7 +71,7 @@ public class OpenAiPromptTransformingChatServiceIT {
@Container
static QdrantContainer qdrantContainer = new QdrantContainer("qdrant/qdrant:v1.9.2");
private final ChatClient chatClient;
private final ChatConnector chatConnector;
private final VectorStore vectorStore;
@@ -82,9 +81,9 @@ public class OpenAiPromptTransformingChatServiceIT {
private ChatService chatService;
@Autowired
public OpenAiPromptTransformingChatServiceIT(ChatClient chatClient, ChatService chatService,
public OpenAiPromptTransformingChatServiceIT(ChatConnector chatConnector, ChatService chatService,
VectorStore vectorStore) {
this.chatClient = chatClient;
this.chatConnector = chatConnector;
this.chatService = chatService;
this.vectorStore = vectorStore;
}
@@ -103,7 +102,7 @@ public class OpenAiPromptTransformingChatServiceIT {
OpenAiChatOptions openAiChatOptions = OpenAiChatOptions.builder()
.withModel(GPT_4_TURBO_PREVIEW.getValue())
.build();
var relevancyEvaluator = new RelevancyEvaluator(this.chatClient, openAiChatOptions);
var relevancyEvaluator = new RelevancyEvaluator(this.chatConnector, openAiChatOptions);
EvaluationResponse evaluationResponse = relevancyEvaluator.evaluate(chatServiceResponse.toEvaluationRequest());
assertTrue(evaluationResponse.isPass(), "Response is not relevant to the question");
@@ -146,8 +145,8 @@ public class OpenAiPromptTransformingChatServiceIT {
}
@Bean
public ChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
public ChatConnector openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatConnector(openAiApi);
}
@Bean
@@ -164,8 +163,8 @@ public class OpenAiPromptTransformingChatServiceIT {
}
@Bean
public ChatService chatService(ChatClient chatClient, VectorStore vectorStore) {
return PromptTransformingChatService.builder(chatClient)
public ChatService chatService(ChatConnector chatConnector, VectorStore vectorStore) {
return PromptTransformingChatService.builder(chatConnector)
.withRetrievers(List.of(new VectorStoreRetriever(vectorStore, SearchRequest.defaults())))
.withAugmentors(List.of(new QuestionContextAugmentor()))
.build();

View File

@@ -21,7 +21,7 @@ import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.prompt.Prompt;
@@ -43,7 +43,7 @@ public abstract class AbstractIT {
private static final Logger logger = LoggerFactory.getLogger(AbstractIT.class);
@Autowired
protected ChatClient chatClient;
protected ChatConnector chatConnector;
@Autowired
protected StreamingChatClient streamingChatClient;
@@ -85,12 +85,12 @@ public abstract class AbstractIT {
}
Message userMessage = userPromptTemplate.createMessage();
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
String yesOrNo = chatClient.call(prompt).getResult().getOutput().getContent();
String yesOrNo = chatConnector.execute(prompt).getResult().getOutput().getContent();
logger.info("Is Answer related to question: " + yesOrNo);
if (yesOrNo.equalsIgnoreCase("no")) {
SystemMessage notRelatedSystemMessage = new SystemMessage(qaEvaluatorNotRelatedResource);
prompt = new Prompt(List.of(userMessage, notRelatedSystemMessage));
String reasonForFailure = chatClient.call(prompt).getResult().getOutput().getContent();
String reasonForFailure = chatConnector.execute(prompt).getResult().getOutput().getContent();
fail(reasonForFailure);
}
else {

View File

@@ -24,8 +24,8 @@ import org.junit.jupiter.api.Test;
import org.springframework.ai.document.DefaultContentFormatter;
import org.springframework.ai.document.Document;
import org.springframework.ai.openai.OpenAiChatConnector;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.transformer.ContentFormatTransformer;
import org.springframework.ai.transformer.KeywordMetadataEnricher;
import org.springframework.ai.transformer.SummaryMetadataEnricher;
@@ -163,18 +163,18 @@ public class MetadataTransformerIT {
}
@Bean
public OpenAiChatClient openAiChatClient(OpenAiApi openAiApi) {
OpenAiChatClient openAiChatClient = new OpenAiChatClient(openAiApi);
public OpenAiChatConnector openAiChatClient(OpenAiApi openAiApi) {
OpenAiChatConnector openAiChatClient = new OpenAiChatConnector(openAiApi);
return openAiChatClient;
}
@Bean
public KeywordMetadataEnricher keywordMetadata(OpenAiChatClient aiClient) {
public KeywordMetadataEnricher keywordMetadata(OpenAiChatConnector aiClient) {
return new KeywordMetadataEnricher(aiClient, 5);
}
@Bean
public SummaryMetadataEnricher summaryMetadata(OpenAiChatClient aiClient) {
public SummaryMetadataEnricher summaryMetadata(OpenAiChatConnector aiClient) {
return new SummaryMetadataEnricher(aiClient,
List.of(SummaryType.PREVIOUS, SummaryType.CURRENT, SummaryType.NEXT));
}

View File

@@ -32,7 +32,7 @@ import com.google.cloud.vertexai.generativeai.PartMaker;
import com.google.cloud.vertexai.generativeai.ResponseStream;
import com.google.protobuf.Struct;
import com.google.protobuf.util.JsonFormat;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -65,9 +65,9 @@ import java.util.stream.Collectors;
* @author Grogdunn
* @since 0.8.1
*/
public class VertexAiGeminiChatClient
extends AbstractFunctionCallSupport<Content, VertexAiGeminiChatClient.GeminiRequest, GenerateContentResponse>
implements ChatClient, StreamingChatClient, DisposableBean {
public class VertexAiGeminiChatConnector
extends AbstractFunctionCallSupport<Content, VertexAiGeminiChatConnector.GeminiRequest, GenerateContentResponse>
implements ChatConnector, StreamingChatClient, DisposableBean {
private final static boolean IS_RUNTIME_CALL = true;
@@ -117,7 +117,7 @@ public class VertexAiGeminiChatClient
}
public VertexAiGeminiChatClient(VertexAI vertexAI) {
public VertexAiGeminiChatConnector(VertexAI vertexAI) {
this(vertexAI,
VertexAiGeminiChatOptions.builder()
.withModel(ChatModel.GEMINI_PRO_VISION.getValue())
@@ -125,11 +125,11 @@ public class VertexAiGeminiChatClient
.build());
}
public VertexAiGeminiChatClient(VertexAI vertexAI, VertexAiGeminiChatOptions options) {
public VertexAiGeminiChatConnector(VertexAI vertexAI, VertexAiGeminiChatOptions options) {
this(vertexAI, options, null);
}
public VertexAiGeminiChatClient(VertexAI vertexAI, VertexAiGeminiChatOptions options,
public VertexAiGeminiChatConnector(VertexAI vertexAI, VertexAiGeminiChatOptions options,
FunctionCallbackContext functionCallbackContext) {
super(functionCallbackContext);
@@ -145,7 +145,7 @@ public class VertexAiGeminiChatClient
// https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/gemini
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
var geminiRequest = createGeminiRequest(prompt);

View File

@@ -77,10 +77,10 @@ public class VertexAiGeminiChatOptions implements FunctionCallingOptions, ChatOp
private @JsonProperty("modelName") String model;
/**
* Tool Function Callbacks to register with the ChatClient.
* Tool Function Callbacks to register with the ChatConnector.
* For Prompt Options the functionCallbacks are automatically enabled for the duration of the prompt execution.
* For Default Options the functionCallbacks are registered but disabled by default. Use the enableFunctions to set the functions
* from the registry to be used by the ChatClient chat completion requests.
* from the registry to be used by the ChatConnector chat completion requests.
*/
@NestedConfigurationProperty
@JsonIgnore

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.ai.vertexai.gemini.aot;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatConnector;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
@@ -34,7 +34,7 @@ public class VertexAiGeminiRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
var mcs = MemberCategory.values();
for (var tr : findJsonAnnotatedClassesInPackage(VertexAiGeminiChatClient.class))
for (var tr : findJsonAnnotatedClassesInPackage(VertexAiGeminiChatConnector.class))
hints.reflection().registerType(tr, mcs);
}

View File

@@ -53,10 +53,10 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*")
class VertexAiGeminiChatClientIT {
class VertexAiGeminiChatConnectorIT {
@Autowired
private VertexAiGeminiChatClient client;
private VertexAiGeminiChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -70,7 +70,7 @@ class VertexAiGeminiChatClientIT {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@@ -87,7 +87,7 @@ class VertexAiGeminiChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputParser.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -106,7 +106,7 @@ class VertexAiGeminiChatClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -129,7 +129,7 @@ class VertexAiGeminiChatClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConvert.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -191,7 +191,7 @@ class VertexAiGeminiChatClientIT {
var userMessage = new UserMessage("Explain what do you see o this picture?",
List.of(new Media(MimeTypeUtils.IMAGE_PNG, data)));
var response = client.call(new Prompt(List.of(userMessage)));
var response = client.execute(new Prompt(List.of(userMessage)));
// Response should contain something like:
// I see a bunch of bananas in a golden basket. The bananas are ripe and yellow.
@@ -231,10 +231,10 @@ class VertexAiGeminiChatClientIT {
}
@Bean
public VertexAiGeminiChatClient vertexAiEmbedding(VertexAI vertexAi) {
return new VertexAiGeminiChatClient(vertexAi,
public VertexAiGeminiChatConnector vertexAiEmbedding(VertexAI vertexAi) {
return new VertexAiGeminiChatConnector(vertexAi,
VertexAiGeminiChatOptions.builder()
.withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO_VISION.getValue())
.withModel(VertexAiGeminiChatConnector.ChatModel.GEMINI_PRO_VISION.getValue())
.build());
}

View File

@@ -19,7 +19,7 @@ import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatConnector;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
@@ -38,7 +38,7 @@ class VertexAiGeminiRuntimeHintsTests {
RuntimeHints runtimeHints = new RuntimeHints();
VertexAiGeminiRuntimeHints vertexAiGeminiRuntimeHints = new VertexAiGeminiRuntimeHints();
vertexAiGeminiRuntimeHints.registerHints(runtimeHints, null);
Set<TypeReference> jsonAnnotatedClasses = findJsonAnnotatedClassesInPackage(VertexAiGeminiChatClient.class);
Set<TypeReference> jsonAnnotatedClasses = findJsonAnnotatedClassesInPackage(VertexAiGeminiChatConnector.class);
for (TypeReference jsonAnnotatedClass : jsonAnnotatedClasses) {
assertThat(runtimeHints).matches(reflection().onType(jsonAnnotatedClass));
}

View File

@@ -23,11 +23,11 @@ import java.util.stream.Collectors;
import com.google.cloud.vertexai.Transport;
import com.google.cloud.vertexai.VertexAI;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
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.vertexai.gemini.VertexAiGeminiChatConnector;
import reactor.core.publisher.Flux;
import org.springframework.ai.chat.ChatResponse;
@@ -38,7 +38,6 @@ import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.function.FunctionCallbackWrapper;
import org.springframework.ai.model.function.FunctionCallbackWrapper.Builder.SchemaType;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
@@ -50,12 +49,12 @@ import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*")
public class VertexAiGeminiChatClientFunctionCallingIT {
public class VertexAiGeminiChatConnectorFunctionCallingIT {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private VertexAiGeminiChatClient vertexGeminiClient;
private VertexAiGeminiChatConnector vertexGeminiClient;
@AfterEach
public void afterEach() {
@@ -69,7 +68,7 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
@Test
// @Disabled("Google Vertex AI degraded support for parallel function calls")
public void functionCallExplicitOpenApiSchema() {
public void functionExecuteExplicitOpenApiSchema() {
UserMessage userMessage = new UserMessage(
"What's the weather like in San Francisco, in Paris and in Tokyo, Japan?"
@@ -98,8 +97,8 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
""";
var promptOptions = VertexAiGeminiChatOptions.builder()
// .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue())
.withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO_1_5_PRO.getValue())
// .withModel(VertexAiGeminiChatConnector.ChatModel.GEMINI_PRO.getValue())
.withModel(VertexAiGeminiChatConnector.ChatModel.GEMINI_PRO_1_5_PRO.getValue())
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withName("get_current_weather")
.withDescription("Get the current weather in a given location")
@@ -107,7 +106,7 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
.build()))
.build();
ChatResponse response = vertexGeminiClient.call(new Prompt(messages, promptOptions));
ChatResponse response = vertexGeminiClient.execute(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);
@@ -119,15 +118,15 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
}
@Test
public void functionCallTestInferredOpenApiSchema() {
public void functionExecuteTestInferredOpenApiSchema() {
UserMessage userMessage = new UserMessage("What's the weather like in Paris? Use Celsius units.");
List<Message> messages = new ArrayList<>(List.of(userMessage));
var promptOptions = VertexAiGeminiChatOptions.builder()
.withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO_1_5_PRO.getValue())
// .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue())
.withModel(VertexAiGeminiChatConnector.ChatModel.GEMINI_PRO_1_5_PRO.getValue())
// .withModel(VertexAiGeminiChatConnector.ChatModel.GEMINI_PRO.getValue())
.withFunctionCallbacks(List.of(
FunctionCallbackWrapper.builder(new MockWeatherService())
.withSchemaType(SchemaType.OPEN_API_SCHEMA)
@@ -142,14 +141,14 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
.build()))
.build();
ChatResponse response = vertexGeminiClient.call(new Prompt(messages, promptOptions));
ChatResponse response = vertexGeminiClient.execute(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);
assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15.0", "15");
ChatResponse response2 = vertexGeminiClient
.call(new Prompt("What is the payment status for transaction 696?", promptOptions));
.execute(new Prompt("What is the payment status for transaction 696?", promptOptions));
logger.info("Response: {}", response2);
@@ -158,7 +157,7 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
}
@Test
public void functionCallTestInferredOpenApiSchemaStream() {
public void functionExecuteTestInferredOpenApiSchemaStream() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco in Celsius units?");
// UserMessage userMessage = new UserMessage(
@@ -168,7 +167,7 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
List<Message> messages = new ArrayList<>(List.of(userMessage));
var promptOptions = VertexAiGeminiChatOptions.builder()
.withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue())
.withModel(VertexAiGeminiChatConnector.ChatModel.GEMINI_PRO.getValue())
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withSchemaType(SchemaType.OPEN_API_SCHEMA)
.withName("getCurrentWeather")
@@ -224,10 +223,10 @@ public class VertexAiGeminiChatClientFunctionCallingIT {
}
@Bean
public VertexAiGeminiChatClient vertexAiEmbedding(VertexAI vertexAi) {
return new VertexAiGeminiChatClient(vertexAi,
public VertexAiGeminiChatConnector vertexAiEmbedding(VertexAI vertexAi) {
return new VertexAiGeminiChatConnector(vertexAi,
VertexAiGeminiChatOptions.builder()
.withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue())
.withModel(VertexAiGeminiChatConnector.ChatModel.GEMINI_PRO.getValue())
.withTemperature(0.9f)
.build());
}

View File

@@ -18,7 +18,7 @@ package org.springframework.ai.vertexai.palm2;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
@@ -35,18 +35,18 @@ import org.springframework.util.CollectionUtils;
/**
* @author Christian Tzolov
*/
public class VertexAiPaLm2ChatClient implements ChatClient {
public class VertexAiPaLm2ChatConnector implements ChatConnector {
private final VertexAiPaLm2Api vertexAiApi;
private final VertexAiPaLm2ChatOptions defaultOptions;
public VertexAiPaLm2ChatClient(VertexAiPaLm2Api vertexAiApi) {
public VertexAiPaLm2ChatConnector(VertexAiPaLm2Api vertexAiApi) {
this(vertexAiApi,
VertexAiPaLm2ChatOptions.builder().withTemperature(0.7f).withCandidateCount(1).withTopK(20).build());
}
public VertexAiPaLm2ChatClient(VertexAiPaLm2Api vertexAiApi, VertexAiPaLm2ChatOptions defaultOptions) {
public VertexAiPaLm2ChatConnector(VertexAiPaLm2Api vertexAiApi, VertexAiPaLm2ChatOptions defaultOptions) {
Assert.notNull(defaultOptions, "Default options must not be null!");
Assert.notNull(vertexAiApi, "VertexAiPaLm2Api must not be null!");
@@ -55,7 +55,7 @@ public class VertexAiPaLm2ChatClient implements ChatClient {
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
GenerateMessageRequest request = createRequest(prompt);

View File

@@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat;
class VertexAiPaLm2ChatGenerationClientIT {
@Autowired
private VertexAiPaLm2ChatClient client;
private VertexAiPaLm2ChatConnector client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@@ -62,7 +62,7 @@ class VertexAiPaLm2ChatGenerationClientIT {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Bartholomew");
}
@@ -79,7 +79,7 @@ class VertexAiPaLm2ChatGenerationClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "ice cream flavors.", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = this.client.call(prompt).getResult();
Generation generation = this.client.execute(prompt).getResult();
List<String> list = outputConverter.convert(generation.getOutput().getContent());
assertThat(list).hasSize(5);
@@ -98,7 +98,7 @@ class VertexAiPaLm2ChatGenerationClientIT {
PromptTemplate promptTemplate = new PromptTemplate(template,
Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
Map<String, Object> result = outputConverter.convert(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
@@ -120,7 +120,7 @@ class VertexAiPaLm2ChatGenerationClientIT {
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
Generation generation = client.execute(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputConverter.convert(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
@@ -136,8 +136,8 @@ class VertexAiPaLm2ChatGenerationClientIT {
}
@Bean
public VertexAiPaLm2ChatClient vertexAiEmbedding(VertexAiPaLm2Api vertexAiApi) {
return new VertexAiPaLm2ChatClient(vertexAiApi);
public VertexAiPaLm2ChatConnector vertexAiEmbedding(VertexAiPaLm2Api vertexAiApi) {
return new VertexAiPaLm2ChatConnector(vertexAiApi);
}
}

View File

@@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class VertexAiPaLm2ChatRequestTests {
VertexAiPaLm2ChatClient client = new VertexAiPaLm2ChatClient(new VertexAiPaLm2Api("bla"));
VertexAiPaLm2ChatConnector client = new VertexAiPaLm2ChatConnector(new VertexAiPaLm2Api("bla"));
@Test
public void createRequestWithDefaultOptions() {

View File

@@ -20,7 +20,7 @@ import java.util.Map;
import reactor.core.publisher.Flux;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -35,7 +35,7 @@ import org.springframework.ai.watsonx.utils.MessageToPromptConverter;
import org.springframework.util.Assert;
/**
* {@link ChatClient} implementation for {@literal watsonx.ai}.
* {@link ChatConnector} implementation for {@literal watsonx.ai}.
*
* watsonx.ai allows developers to use large language models within a SaaS service. It
* supports multiple open-source models as well as IBM created models
@@ -48,13 +48,13 @@ import org.springframework.util.Assert;
* @author Christian Tzolov
* @since 1.0.0
*/
public class WatsonxAiChatClient implements ChatClient, StreamingChatClient {
public class WatsonxAiChatConnector implements ChatConnector, StreamingChatClient {
private final WatsonxAiApi watsonxAiApi;
private final WatsonxAiChatOptions defaultOptions;
public WatsonxAiChatClient(WatsonxAiApi watsonxAiApi) {
public WatsonxAiChatConnector(WatsonxAiApi watsonxAiApi) {
this(watsonxAiApi,
WatsonxAiChatOptions.builder()
.withTemperature(0.7f)
@@ -68,7 +68,7 @@ public class WatsonxAiChatClient implements ChatClient, StreamingChatClient {
.build());
}
public WatsonxAiChatClient(WatsonxAiApi watsonxAiApi, WatsonxAiChatOptions defaultOptions) {
public WatsonxAiChatConnector(WatsonxAiApi watsonxAiApi, WatsonxAiChatOptions defaultOptions) {
Assert.notNull(watsonxAiApi, "watsonxAiApi cannot be null");
Assert.notNull(defaultOptions, "defaultOptions cannot be null");
this.watsonxAiApi = watsonxAiApi;
@@ -76,7 +76,7 @@ public class WatsonxAiChatClient implements ChatClient, StreamingChatClient {
}
@Override
public ChatResponse call(Prompt prompt) {
public ChatResponse execute(Prompt prompt) {
WatsonxAiRequest request = request(prompt);

View File

@@ -46,9 +46,9 @@ import static org.mockito.Mockito.when;
* @author Pablo Sanchidrian Herrera
* @author John Jairo Moreno Rojas
*/
public class WatsonxAiChatClientTest {
public class WatsonxAiChatConnectorTest {
WatsonxAiChatClient chatClient = new WatsonxAiChatClient(mock(WatsonxAiApi.class));
WatsonxAiChatConnector chatClient = new WatsonxAiChatConnector(mock(WatsonxAiApi.class));
@Test
public void testCreateRequestWithNoModelId() {
@@ -155,9 +155,9 @@ public class WatsonxAiChatClientTest {
}
@Test
public void testCallMethod() {
public void testExecuteMethod() {
WatsonxAiApi mockChatApi = mock(WatsonxAiApi.class);
WatsonxAiChatClient client = new WatsonxAiChatClient(mockChatApi);
WatsonxAiChatConnector client = new WatsonxAiChatConnector(mockChatApi);
Prompt prompt = new Prompt(List.of(new SystemMessage("Your prompt here")),
WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build());
@@ -177,7 +177,7 @@ public class WatsonxAiChatClientTest {
Map.of("warnings", List.of(Map.of("message", "the message", "id", "disclaimer_warning")))));
ChatResponse expectedResponse = new ChatResponse(List.of(expectedGenerator));
ChatResponse response = client.call(prompt);
ChatResponse response = client.execute(prompt);
Assert.assertEquals(expectedResponse.getResults().size(), response.getResults().size());
Assert.assertEquals(expectedResponse.getResult().getOutput(), response.getResult().getOutput());
@@ -186,7 +186,7 @@ public class WatsonxAiChatClientTest {
@Test
public void testStreamMethod() {
WatsonxAiApi mockChatApi = mock(WatsonxAiApi.class);
WatsonxAiChatClient client = new WatsonxAiChatClient(mockChatApi);
WatsonxAiChatConnector client = new WatsonxAiChatConnector(mockChatApi);
Prompt prompt = new Prompt(List.of(new SystemMessage("Your prompt here")),
WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build());

View File

@@ -1,44 +1,175 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.chat;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.messages.Media;
import org.springframework.core.ParameterizedTypeReference;
import java.util.Arrays;
import java.util.*;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.model.ModelClient;
@FunctionalInterface
public interface ChatClient extends ModelClient<Prompt, ChatResponse> {
/**
* @author Mark Pollack
* @author Christian Tsolov
* @author Josh Long
*/
public class ChatClient {
private final ChatConnector connector;
private final String userPrompt, systemPrompt;
private final List<String> functions;
private final List<Media> media;
public ChatClient(ChatConnector connector, String defaultSystemPrompt, String defaultUserPrompt,
List<String> defaultFunctions, List<Media> defaultMedia) {
this.connector = connector;
this.userPrompt = defaultUserPrompt;
this.systemPrompt = defaultSystemPrompt;
this.functions = defaultFunctions;
this.media = defaultMedia;
default String call(String message) {
Prompt prompt = new Prompt(new UserMessage(message));
Generation generation = call(prompt).getResult();
return (generation != null) ? generation.getOutput().getContent() : "";
}
default String call(Message... messages) {
Prompt prompt = new Prompt(Arrays.asList(messages));
Generation generation = call(prompt).getResult();
return (generation != null) ? generation.getOutput().getContent() : "";
public ChatClientRequest build() {
return new ChatClientRequest(this.userPrompt, this.systemPrompt, this.functions, this.media);
}
@Override
ChatResponse call(Prompt prompt);
public ChatClientRequest userPrompt(String userPrompt, Map<String, String> params) {
var ccr = new ChatClientRequest(userPrompt, this.systemPrompt, this.functions, this.media);
ccr.userPromptParams(params);
return ccr;
}
public ChatClientRequest userPrompt(String userPrompt) {
return new ChatClientRequest(userPrompt, this.systemPrompt, this.functions, this.media);
}
public static class ChatClientRequest {
private String userPrompt = "";
private String systemPrompt = "";
private final List<Media> media = new ArrayList<>();
private final List<String> functions = new ArrayList<>();
private final Map<String, String> userPromptParams = new HashMap<>();
private final Map<String, String> systemPromptParams = new HashMap<>();
List<Media> media() {
return this.media;
}
String systemPrompt() {
return this.systemPrompt;
}
String userPrompt() {
return this.userPrompt;
}
List<String> functions() {
return this.functions;
}
public ChatClientRequest(String userPrompt, String systemPrompt, List<String> functions, List<Media> media) {
this.userPrompt = userPrompt;
this.systemPrompt = systemPrompt;
this.functions.addAll(functions);
this.media.addAll(media);
}
public ChatClientRequest userPromptParam(String key, String value) {
this.userPromptParams.put(key, value);
return this;
}
public ChatClientRequest systemPromptParam(String key, String value) {
this.systemPromptParams.put(key, value);
return this;
}
public ChatClientRequest systemPromptParams(Map<String, String> systemPromptParams) {
this.systemPromptParams.putAll(systemPromptParams);
return this;
}
public ChatClientRequest userPromptParams(Map<String, String> userPromptParams) {
this.userPromptParams.putAll(userPromptParams);
return this;
}
public ChatClientRequest userPrompt(String userPrompt) {
this.userPrompt = userPrompt;
return this;
}
public ChatClientRequest systemPrompt(String systemPrompt) {
this.systemPrompt = systemPrompt;
return this;
}
public ChatClientRequest media(Media... media) {
this.media.addAll(Arrays.asList(media));
return this;
}
public ChatClientRequest functions(String... functions) {
this.functions.addAll(Arrays.asList(functions));
return this;
}
public <T> T chat(Class<T> clzz) {
return null;
}
public <T> T chat(ParameterizedTypeReference<T> clzz) {
return null;
}
}
public static class ChatClientBuilder {
private final ChatConnector connector;
private final List<Media> defaultMedia = new ArrayList<>();
private final List<String> defaultFunctions = new ArrayList<>();
private String defaultSystemPrompt;
private String defaultUserPrompt;
ChatClientBuilder(ChatConnector connector) {
this.connector = connector;
}
public ChatClient build() {
return new ChatClient(this.connector, this.defaultSystemPrompt, this.defaultUserPrompt,
this.defaultFunctions, this.defaultMedia);
}
public ChatClientBuilder defaultSystemPrompt(String systemPrompt) {
return this;
}
public ChatClientBuilder defaultFunctions(String... functionNames) {
return this;
}
public ChatClientBuilder defaultUserPrompt(String userPrompt) {
return this;
}
}
public static ChatClientBuilder builder(ChatConnector connector) {
return new ChatClientBuilder(connector);
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.chat.connector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
public interface ChatConnector {
/*
* default String call(String message) { Prompt prompt = new Prompt(new
* UserMessage(message)); Generation generation = call(prompt).getResult(); return
* (generation != null) ? generation.getOutput().getContent() : ""; }
*
* public String call(Message... messages) { Prompt prompt = new
* Prompt(Arrays.asList(messages)); Generation generation = call(prompt).getResult();
* return (generation != null) ? generation.getOutput().getContent() : ""; }
*/
ChatResponse execute(Prompt prompt);
}

View File

@@ -15,7 +15,7 @@
*/
package org.springframework.ai.chat.service;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.transformer.ChatServiceContext;
import org.springframework.ai.chat.prompt.transformer.PromptTransformer;
@@ -35,7 +35,7 @@ import java.util.Objects;
*/
public class PromptTransformingChatService implements ChatService {
private ChatClient chatClient;
private ChatConnector chatConnector;
private List<PromptTransformer> retrievers;
@@ -45,19 +45,19 @@ public class PromptTransformingChatService implements ChatService {
private List<ChatServiceListener> chatServiceListeners;
public PromptTransformingChatService(ChatClient chatClient, List<PromptTransformer> retrievers,
public PromptTransformingChatService(ChatConnector chatConnector, List<PromptTransformer> retrievers,
List<PromptTransformer> documentPostProcessors, List<PromptTransformer> augmentors,
List<ChatServiceListener> chatServiceListeners) {
Objects.requireNonNull(chatClient, "chatClient must not be null");
this.chatClient = chatClient;
Objects.requireNonNull(chatConnector, "chatConnector must not be null");
this.chatConnector = chatConnector;
this.retrievers = retrievers;
this.documentPostProcessors = documentPostProcessors;
this.augmentors = augmentors;
this.chatServiceListeners = chatServiceListeners;
}
public static Builder builder(ChatClient chatClient) {
return new Builder().withChatClient(chatClient);
public static Builder builder(ChatConnector chatConnector) {
return new Builder().withChatClient(chatConnector);
}
@Override
@@ -86,7 +86,7 @@ public class PromptTransformingChatService implements ChatService {
}
// Perform generation
ChatResponse chatResponse = this.chatClient.call(chatServiceContext.getPrompt());
ChatResponse chatResponse = this.chatConnector.execute(chatServiceContext.getPrompt());
// Invoke Listeners onComplete
ChatServiceResponse chatServiceResponse = new ChatServiceResponse(chatServiceContext, chatResponse);
@@ -98,7 +98,7 @@ public class PromptTransformingChatService implements ChatService {
public static class Builder {
private ChatClient chatClient;
private ChatConnector chatConnector;
private List<PromptTransformer> retrievers = new ArrayList<>();
@@ -108,8 +108,8 @@ public class PromptTransformingChatService implements ChatService {
private List<ChatServiceListener> chatServiceListeners = new ArrayList<>();
public Builder withChatClient(ChatClient chatClient) {
this.chatClient = chatClient;
public Builder withChatClient(ChatConnector chatConnector) {
this.chatConnector = chatConnector;
return this;
}
@@ -134,7 +134,7 @@ public class PromptTransformingChatService implements ChatService {
}
public PromptTransformingChatService build() {
return new PromptTransformingChatService(chatClient, retrievers, documentPostProcessors, augmentors,
return new PromptTransformingChatService(chatConnector, retrievers, documentPostProcessors, augmentors,
chatServiceListeners);
}

View File

@@ -1,6 +1,6 @@
package org.springframework.ai.evaluation;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
@@ -31,14 +31,14 @@ public class RelevancyEvaluator implements Evaluator {
private final ChatOptions chatOptions;
private ChatClient chatClient;
private ChatConnector chatConnector;
public RelevancyEvaluator(ChatClient chatClient) {
this(chatClient, ChatOptionsBuilder.builder().build());
public RelevancyEvaluator(ChatConnector chatConnector) {
this(chatConnector, ChatOptionsBuilder.builder().build());
}
public RelevancyEvaluator(ChatClient chatClient, ChatOptions chatOptions) {
this.chatClient = chatClient;
public RelevancyEvaluator(ChatConnector chatConnector, ChatOptions chatOptions) {
this.chatConnector = chatConnector;
this.chatOptions = chatOptions;
}
@@ -52,7 +52,7 @@ public class RelevancyEvaluator implements Evaluator {
Message message = promptTemplate
.createMessage(Map.of("query", query, "response", response, "context", context));
ChatResponse chatResponse = this.chatClient.call(new Prompt(message, this.chatOptions));
ChatResponse chatResponse = this.chatConnector.execute(new Prompt(message, this.chatOptions));
var evaluationResponse = chatResponse.getResult().getOutput().getContent();
boolean passing = false;

View File

@@ -54,7 +54,7 @@ abstract class AbstractFunctionCallback<I, O> implements Function<I, O>, Functio
/**
* Constructs a new {@link AbstractFunctionCallback} with the given name, description,
* input type and default object mapper.
* @param name Function name. Should be unique within the ChatClient's function
* @param name Function name. Should be unique within the ChatConnector's function
* registry.
* @param description Function description. Used as a "system prompt" by the model to
* decide if the function should be called.

View File

@@ -24,33 +24,33 @@ import java.util.Set;
public interface FunctionCallingOptions {
/**
* Function Callbacks to be registered with the ChatClient. For Prompt Options the
* Function Callbacks to be registered with the ChatConnector. For Prompt Options the
* functionCallbacks are automatically enabled for the duration of the prompt
* execution. For Default Options the FunctionCallbacks are registered but disabled by
* default. You have to use "functions" property to list the function names from the
* ChatClient registry to be used in the chat completion requests.
* @return Return the Function Callbacks to be registered with the ChatClient.
* ChatConnector registry to be used in the chat completion requests.
* @return Return the Function Callbacks to be registered with the ChatConnector.
*/
List<FunctionCallback> getFunctionCallbacks();
/**
* Set the Function Callbacks to be registered with the ChatClient.
* Set the Function Callbacks to be registered with the ChatConnector.
* @param functionCallbacks the Function Callbacks to be registered with the
* ChatClient.
* ChatConnector.
*/
void setFunctionCallbacks(List<FunctionCallback> functionCallbacks);
/**
* @return List of function names from the ChatClient registry to be used in the next
* chat completion requests.
* @return List of function names from the ChatConnector registry to be used in the
* next chat completion requests.
*/
Set<String> getFunctions();
/**
* Set the list of function names from the ChatClient registry to be used in the next
* chat completion requests.
* @param functions the list of function names from the ChatClient registry to be used
* in the next chat completion requests.
* Set the list of function names from the ChatConnector registry to be used in the
* next chat completion requests.
* @param functions the list of function names from the ChatConnector registry to be
* used in the next chat completion requests.
*/
void setFunctions(Set<String> functions);

View File

@@ -18,7 +18,7 @@ package org.springframework.ai.transformer;
import java.util.List;
import java.util.Map;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentTransformer;
import org.springframework.ai.chat.prompt.Prompt;
@@ -43,18 +43,18 @@ public class KeywordMetadataEnricher implements DocumentTransformer {
/**
* Model predictor
*/
private final ChatClient chatClient;
private final ChatConnector chatConnector;
/**
* The number of keywords to extract.
*/
private final int keywordCount;
public KeywordMetadataEnricher(ChatClient chatClient, int keywordCount) {
Assert.notNull(chatClient, "ChatClient must not be null");
public KeywordMetadataEnricher(ChatConnector chatConnector, int keywordCount) {
Assert.notNull(chatConnector, "ChatConnector must not be null");
Assert.isTrue(keywordCount >= 1, "Document count must be >= 1");
this.chatClient = chatClient;
this.chatConnector = chatConnector;
this.keywordCount = keywordCount;
}
@@ -64,7 +64,7 @@ public class KeywordMetadataEnricher implements DocumentTransformer {
var template = new PromptTemplate(String.format(KEYWORDS_TEMPLATE, keywordCount));
Prompt prompt = template.create(Map.of(CONTEXT_STR_PLACEHOLDER, document.getContent()));
String keywords = this.chatClient.call(prompt).getResult().getOutput().getContent();
String keywords = this.chatConnector.execute(prompt).getResult().getOutput().getContent();
document.getMetadata().putAll(Map.of(EXCERPT_KEYWORDS_METADATA_KEY, keywords));
}
return documents;

View File

@@ -20,7 +20,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentTransformer;
import org.springframework.ai.document.MetadataMode;
@@ -62,7 +62,7 @@ public class SummaryMetadataEnricher implements DocumentTransformer {
/**
* AI client.
*/
private final ChatClient chatClient;
private final ChatConnector chatConnector;
/**
* Number of documents from front to use for title extraction.
@@ -76,16 +76,16 @@ public class SummaryMetadataEnricher implements DocumentTransformer {
*/
private final String summaryTemplate;
public SummaryMetadataEnricher(ChatClient chatClient, List<SummaryType> summaryTypes) {
this(chatClient, summaryTypes, DEFAULT_SUMMARY_EXTRACT_TEMPLATE, MetadataMode.ALL);
public SummaryMetadataEnricher(ChatConnector chatConnector, List<SummaryType> summaryTypes) {
this(chatConnector, summaryTypes, DEFAULT_SUMMARY_EXTRACT_TEMPLATE, MetadataMode.ALL);
}
public SummaryMetadataEnricher(ChatClient chatClient, List<SummaryType> summaryTypes, String summaryTemplate,
public SummaryMetadataEnricher(ChatConnector chatConnector, List<SummaryType> summaryTypes, String summaryTemplate,
MetadataMode metadataMode) {
Assert.notNull(chatClient, "ChatClient must not be null");
Assert.notNull(chatConnector, "ChatConnector must not be null");
Assert.hasText(summaryTemplate, "Summary template must not be empty");
this.chatClient = chatClient;
this.chatConnector = chatConnector;
this.summaryTypes = CollectionUtils.isEmpty(summaryTypes) ? List.of(SummaryType.CURRENT) : summaryTypes;
this.metadataMode = metadataMode;
this.summaryTemplate = summaryTemplate;
@@ -101,7 +101,7 @@ public class SummaryMetadataEnricher implements DocumentTransformer {
Prompt prompt = new PromptTemplate(this.summaryTemplate)
.create(Map.of(CONTEXT_STR_PLACEHOLDER, documentContext));
documentSummaries.add(this.chatClient.call(prompt).getResult().getOutput().getContent());
documentSummaries.add(this.chatConnector.execute(prompt).getResult().getOutput().getContent());
}
for (int i = 0; i < documentSummaries.size(); i++) {

View File

@@ -30,16 +30,17 @@ import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.prompt.Prompt;
/**
* Unit Tests for {@link ChatClient}.
* Unit Tests for {@link ChatConnector}.
*
* @author John Blum
* @since 0.2.0
*/
class ChatClientTests {
class ChatConnectorTests {
@Test
void generateWithStringCallsGenerateWithPromptAndReturnsResponseCorrectly() {
@@ -47,7 +48,7 @@ class ChatClientTests {
String userMessage = "Zero Wing";
String responseMessage = "All your bases are belong to us";
ChatClient mockClient = Mockito.mock(ChatClient.class);
ChatConnector mockClient = Mockito.mock(ChatConnector.class);
AssistantMessage mockAssistantMessage = Mockito.mock(AssistantMessage.class);
when(mockAssistantMessage.getContent()).thenReturn(responseMessage);
@@ -64,7 +65,7 @@ class ChatClientTests {
// ChatResponse response = spy(new
// ChatResponse(Collections.singletonList(generation)));
doCallRealMethod().when(mockClient).call(anyString());
doCallRealMethod().when(mockClient).execute(anyString());
doAnswer(invocationOnMock -> {
@@ -75,12 +76,12 @@ class ChatClientTests {
return response;
}).when(mockClient).call(any(Prompt.class));
}).when(mockClient).execute(any(Prompt.class));
assertThat(mockClient.call(userMessage)).isEqualTo(responseMessage);
assertThat(mockClient.execute(userMessage)).isEqualTo(responseMessage);
verify(mockClient, times(1)).call(eq(userMessage));
verify(mockClient, times(1)).call(isA(Prompt.class));
verify(mockClient, times(1)).execute(eq(userMessage));
verify(mockClient, times(1)).execute(isA(Prompt.class));
verify(response, times(1)).getResult();
verify(generation, times(1)).getOutput();
verify(mockAssistantMessage, times(1)).getContent();

View File

@@ -25,7 +25,7 @@ import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.connector.ChatConnector;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
@@ -48,7 +48,7 @@ import static org.mockito.Mockito.when;
public class ChatMemoryTests {
@Mock
ChatClient chatClient;
ChatConnector chatConnector;
@Mock
StreamingChatClient streamingChatClient;
@@ -61,7 +61,7 @@ public class ChatMemoryTests {
ChatMemory chatHistory = new InMemoryChatMemory();
PromptTransformingChatService chatService = PromptTransformingChatService.builder(chatClient)
PromptTransformingChatService chatService = PromptTransformingChatService.builder(chatConnector)
.withRetrievers(List.of(ChatMemoryRetriever.builder().withChatHistory(chatHistory).build()))
.withContentPostProcessors(
List.of(new LastMaxTokenSizeContentTransformer(new JTokkitTokenCountEstimator(), 10)))
@@ -77,7 +77,7 @@ public class ChatMemoryTests {
ChatMemory chatHistory = new InMemoryChatMemory();
PromptTransformingChatService chatService = PromptTransformingChatService.builder(chatClient)
PromptTransformingChatService chatService = PromptTransformingChatService.builder(chatConnector)
.withRetrievers(List.of(new ChatMemoryRetriever(chatHistory)))
.withContentPostProcessors(
List.of(new LastMaxTokenSizeContentTransformer(new JTokkitTokenCountEstimator(), 10)))
@@ -90,7 +90,7 @@ public class ChatMemoryTests {
public void chatClientUserMessages(PromptTransformingChatService chatService, ChatMemory chatHistory) {
when(chatClient.call(promptCaptor.capture()))
when(chatConnector.execute(promptCaptor.capture()))
.thenReturn(new ChatResponse(List.of(new Generation("assistant:1"))))
.thenReturn(new ChatResponse(List.of(new Generation("assistant:2"))))
.thenReturn(new ChatResponse(List.of(new Generation("assistant:3"))));

View File

@@ -2,7 +2,7 @@
link:https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html[Amazon Bedrock] is a managed service that provides foundation models from various AI providers, available through a unified API.
Spring AI supports https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids-arns.html[all the Chat and Embedding AI models] available through Amazon Bedrock by implementing the Spring interfaces `ChatClient`, `StreamingChatClient`, and `EmbeddingClient`.
Spring AI supports https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids-arns.html[all the Chat and Embedding AI models] available through Amazon Bedrock by implementing the Spring interfaces `ChatConnector`, `StreamingChatClient`, and `EmbeddingClient`.
Additionally, Spring AI provides Spring Auto-Configurations and Boot Starters for all clients, making it easy to bootstrap and configure for the Bedrock models.

View File

@@ -132,7 +132,7 @@ TIP: In addition to the model specific https://github.com/spring-projects/spring
== Function Calling
You can register custom Java functions with the `AnthropicChatClient` and have the Anthropic Claude model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
You can register custom Java functions with the `AnthropicChatConnector` and have the Anthropic Claude model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This is a powerful technique to connect the LLM capabilities with external tools and APIs.
Read more about xref:api/chat/functions/anthropic-chat-functions.adoc[Anthropic Function Calling].
@@ -194,7 +194,7 @@ spring.ai.anthropic.chat.options.max-tokens=450
TIP: replace the `api-key` with your Anthropic credentials.
This will create a `AnthropicChatClient` implementation that you can inject into your class.
This will create a `AnthropicChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -224,7 +224,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-anthropic/src/main/java/org/springframework/ai/anthropic/AnthropicChatClient.java[AnthropicChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Anthropic service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-anthropic/src/main/java/org/springframework/ai/anthropic/AnthropicChatClient.java[AnthropicChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Anthropic service.
Add the `spring-ai-anthropic` dependency to your project's Maven `pom.xml` file:
@@ -247,7 +247,7 @@ dependencies {
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
Next, create a `AnthropicChatClient` and use it for text generations:
Next, create a `AnthropicChatConnector` and use it for text generations:
[source,java]
----

View File

@@ -88,7 +88,7 @@ The prefix `spring.ai.azure.openai` is the property prefix to configure the conn
| spring.ai.azure.openai.endpoint | The endpoint from the Azure AI OpenAI `Keys and Endpoint` section under `Resource Management` | -
|====
The prefix `spring.ai.azure.openai.chat` is the property prefix that configures the `ChatClient` implementation for Azure OpenAI.
The prefix `spring.ai.azure.openai.chat` is the property prefix that configures the `ChatConnector` implementation for Azure OpenAI.
[cols="3,5,3"]
|====
@@ -157,7 +157,7 @@ spring.ai.azure.openai.chat.options.temperature=0.7
TIP: replace the `api-key` and `endpoint` with your Azure OpenAI credentials.
This will create a `AzureOpenAiChatClient` implementation that you can inject into your class.
This will create a `AzureOpenAiChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
@@ -188,7 +188,7 @@ public class ChatController {
== Manual Configuration
The link:https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiChatClient.java[AzureOpenAiChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the link:https://learn.microsoft.com/en-us/java/api/overview/azure/ai-openai-readme?view=azure-java-preview[Azure OpenAI Java Client].
The link:https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-azure-openai/src/main/java/org/springframework/ai/azure/openai/AzureOpenAiChatClient.java[AzureOpenAiChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the link:https://learn.microsoft.com/en-us/java/api/overview/azure/ai-openai-readme?view=azure-java-preview[Azure OpenAI Java Client].
To enable it, add the `spring-ai-azure-openai` dependency to your project's Maven `pom.xml` file:
[source, xml]
@@ -210,9 +210,9 @@ dependencies {
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
TIP: The `spring-ai-azure-openai` dependency also provide the access to the `AzureOpenAiChatClient`. For more information about the `AzureOpenAiChatClient` refer to the link:../chat/azure-openai-chat.html[Azure OpenAI Chat] section.
TIP: The `spring-ai-azure-openai` dependency also provide the access to the `AzureOpenAiChatConnector`. For more information about the `AzureOpenAiChatConnector` refer to the link:../chat/azure-openai-chat.html[Azure OpenAI Chat] section.
Next, create an `AzureOpenAiChatClient` instance and use it to generate text responses:
Next, create an `AzureOpenAiChatConnector` instance and use it to generate text responses:
[source,java]
----

View File

@@ -138,7 +138,7 @@ spring.ai.bedrock.anthropic.chat.options.top-k=15
TIP: replace the `regions`, `access-key` and `secret-key` with your AWS credentials.
This will create a `BedrockAnthropicChatClient` implementation that you can inject into your class.
This will create a `BedrockAnthropicChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -168,7 +168,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/anthropic/BedrockAnthropicChatClient.java[BedrockAnthropicChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Anthropic service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/anthropic/BedrockAnthropicChatClient.java[BedrockAnthropicChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Anthropic service.
Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file:

View File

@@ -179,7 +179,7 @@ spring.ai.bedrock.anthropic3.chat.options.top-k=15
TIP: replace the `regions`, `access-key` and `secret-key` with your AWS credentials.
This will create a `BedrockAnthropicChatClient` implementation that you can inject into your class.
This will create a `BedrockAnthropicChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -209,7 +209,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/anthropic3/BedrockAnthropic3ChatClient.java[BedrockAnthropic3ChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Anthropic service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/anthropic3/BedrockAnthropic3ChatClient.java[BedrockAnthropic3ChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Anthropic service.
Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file:

View File

@@ -130,7 +130,7 @@ spring.ai.bedrock.cohere.chat.options.temperature=0.8
TIP: replace the `regions`, `access-key` and `secret-key` with your AWS credentials.
This will create a `BedrockCohereChatClient` implementation that you can inject into your class.
This will create a `BedrockCohereChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -160,7 +160,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/cohere/BedrockCohereChatClient.java[BedrockCohereChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Cohere service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/cohere/BedrockCohereChatClient.java[BedrockCohereChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Cohere service.
Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file:

View File

@@ -123,7 +123,7 @@ spring.ai.bedrock.jurassic2.chat.options.temperature=0.8
TIP: replace the `regions`, `access-key` and `secret-key` with your AWS credentials.
This will create a `BedrockAi21Jurassic2ChatClient` implementation that you can inject into your class.
This will create a `BedrockAi21Jurassic2ChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -148,7 +148,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/jurassic2/BedrockAi21Jurassic2ChatClient.java[BedrockAi21Jurassic2ChatClient] implements the `ChatClient` uses the <<low-level-api>> to connect to the Bedrock Jurassic-2 service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/jurassic2/BedrockAi21Jurassic2ChatClient.java[BedrockAi21Jurassic2ChatClient] implements the `ChatConnector` uses the <<low-level-api>> to connect to the Bedrock Jurassic-2 service.
Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file:

View File

@@ -128,7 +128,7 @@ spring.ai.bedrock.llama.chat.options.temperature=0.8
TIP: replace the `regions`, `access-key` and `secret-key` with your AWS credentials.
This will create a `BedrockLlamaChatClient` implementation that you can inject into your class.
This will create a `BedrockLlamaChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -158,7 +158,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama/BedrockLlamaChatClient.java[BedrockLlamaChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Anthropic service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/llama/BedrockLlamaChatClient.java[BedrockLlamaChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Anthropic service.
Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file:

View File

@@ -126,7 +126,7 @@ spring.ai.bedrock.titan.chat.options.temperature=0.8
TIP: replace the `regions`, `access-key` and `secret-key` with your AWS credentials.
This will create a `BedrockTitanChatClient` implementation that you can inject into your class.
This will create a `BedrockTitanChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -156,7 +156,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/titan/BedrockTitanChatClient.java[BedrockTitanChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Titanic service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-bedrock/src/main/java/org/springframework/ai/bedrock/titan/BedrockTitanChatClient.java[BedrockTitanChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Bedrock Titanic service.
Add the `spring-ai-bedrock` dependency to your project's Maven `pom.xml` file:

View File

@@ -1,6 +1,6 @@
= Anthropic Function Calling
You can register custom Java functions with the `AnthropicChatClient` and have the Anthropic models intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
You can register custom Java functions with the `AnthropicChatConnector` and have the Anthropic models intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This allows you to connect the LLM capabilities with external tools and APIs.
The `claude-3-opus`, `claude-3-sonnet` and `claude-3-haiku` link:https://docs.anthropic.com/claude/docs/tool-use#tool-use-best-practices-and-limitations[models are trained to detect when a function should be called] and to respond with JSON that adheres to the function signature.
@@ -15,7 +15,7 @@ The `description` helps the model to understand when to call the function.
As a developer, you need to implement a function that takes the function call arguments sent from the AI model, and respond with the result back to the model.
Your function can in turn invoke other 3rd party services to provide the results.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatClient`.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatConnector`.
Under the hood, Spring wraps your POJO (the function) with the appropriate adapter code that enables interaction with the AI Model, saving you from writing tedious boilerplate code.
The basis of the underlying infrastructure is the link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallback.java[FunctionCallback.java] interface and the companion link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallbackWrapper.java[FunctionCallbackWrapper.java] utility class to simplify the implementation and registration of Java callback functions.
@@ -70,7 +70,7 @@ We start with describing the most POJO friendly options.
In this approach you define `@Beans` in your application context as you would any other Spring managed object.
Internally, Spring AI `ChatClient` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
Internally, Spring AI `ChatConnector` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
The name of the `@Bean` is passed as a `ChatOption`.
@@ -136,7 +136,7 @@ static class Config {
}
----
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `AnthropicChatClient`.
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `AnthropicChatConnector`.
It also provides a description (2) and an optional response converter (3) to convert the response into a text as expected by the model.
NOTE: By default, the response converter does a JSON serialization of the Response object.
@@ -159,7 +159,7 @@ ChatResponse response = chatClient.call(new Prompt(List.of(userMessage),
logger.info("Response: {}", response);
----
// NOTE: You can can have multiple functions registered in your `ChatClient` but only those enabled in the prompt request will be considered for the function calling.
// NOTE: You can can have multiple functions registered in your `ChatConnector` but only those enabled in the prompt request will be considered for the function calling.
Above user question will trigger 3 calls to `CurrentWeather` function (one for each city) and produce the final response.
@@ -187,5 +187,5 @@ NOTE: The in-prompt registered functions are enabled by default for the duration
This approach allows to dynamically chose different functions to be called based on the user input.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/anthropic/tool/FunctionCallWithPromptFunctionIT.java[FunctionCallWithPromptFunctionIT.java] integration test provides a complete example of how to register a function with the `AnthropicChatClient` and use it in a prompt request.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/anthropic/tool/FunctionCallWithPromptFunctionIT.java[FunctionCallWithPromptFunctionIT.java] integration test provides a complete example of how to register a function with the `AnthropicChatConnector` and use it in a prompt request.

View File

@@ -2,7 +2,7 @@
Function calling lets developers create a description of a function in their code, then pass that description to a language model in a request. The response from the model includes the name of a function that matches the description and the arguments to call it with.
You can register custom Java functions with the `AzureOpenAiChatClient` and have the model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
You can register custom Java functions with the `AzureOpenAiChatConnector` and have the model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This allows you to connect the LLM capabilities with external tools and APIs.
The Azure models are trained to detect when a function should be called and to respond with JSON that adheres to the function signature.
@@ -16,7 +16,7 @@ In general, the custom functions need to provide a function `name`, `description
As a developer, you need to implement a function that takes the function call arguments sent from the AI model, and respond with the result back to the model.
Your function can in turn invoke other 3rd party services to provide the results.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatClient`.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatConnector`.
Under the hood, Spring wraps your POJO (the function) with the appropriate adapter code that enables interaction with the AI Model, saving you from writing tedious boilerplate code.
The basis of the underlying infrastructure is the link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallback.java[FunctionCallback.java] interface and the companion link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallbackWrapper.java[FunctionCallbackWrapper.java] utility class to simplify the implementation and registration of Java callback functions.
@@ -70,7 +70,7 @@ We start with describing the most POJO friendly options.
In this approach you define `@Beans` in your application context as you would any other Spring managed object.
Internally, Spring AI `ChatClient` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
Internally, Spring AI `ChatConnector` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
The name of the `@Bean` is passed as a `ChatOption`.
@@ -156,7 +156,7 @@ ChatResponse response = chatClient.call(new Prompt(List.of(userMessage),
logger.info("Response: {}", response);
----
// NOTE: You can can have multiple functions registered in your `ChatClient` but only those enabled in the prompt request will be considered for the function calling.
// NOTE: You can can have multiple functions registered in your `ChatConnector` but only those enabled in the prompt request will be considered for the function calling.
Above user question will trigger 3 calls to `CurrentWeather` function (one for each city) and the final response will be something like this:
@@ -194,5 +194,5 @@ NOTE: The in-prompt registered functions are enabled by default for the duration
This approach allows to dynamically chose different functions to be called based on the user input.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/azure/tool/FunctionCallWithPromptFunctionIT.java[FunctionCallWithPromptFunctionIT.java] integration test provides a complete example of how to register a function with the `AzureOpenAiChatClient` and use it in a prompt request.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/azure/tool/FunctionCallWithPromptFunctionIT.java[FunctionCallWithPromptFunctionIT.java] integration test provides a complete example of how to register a function with the `AzureOpenAiChatConnector` and use it in a prompt request.

View File

@@ -1,6 +1,6 @@
= Mistral AI Function Calling
You can register custom Java functions with the `MistralAiChatClient` and have the Mistral AI models intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
You can register custom Java functions with the `MistralAiChatConnector` and have the Mistral AI models intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This allows you to connect the LLM capabilities with external tools and APIs.
The `open-mixtral-8x22b`, `mistral_small_latest`, and `mistral_large_latest` models are trained to detect when a function should be called and to respond with JSON that adheres to the function signature.
@@ -15,7 +15,7 @@ The `description` helps the model to understand when to call the function.
As a developer, you need to implement a function that takes the function call arguments sent from the AI model, and respond with the result back to the model.
Your function can in turn invoke other 3rd party services to provide the results.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatClient`.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatConnector`.
Under the hood, Spring wraps your POJO (the function) with the appropriate adapter code that enables interaction with the AI Model, saving you from writing tedious boilerplate code.
The basis of the underlying infrastructure is the link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallback.java[FunctionCallback.java] interface and the companion link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallbackWrapper.java[FunctionCallbackWrapper.java] utility class to simplify the implementation and registration of Java callback functions.
@@ -70,7 +70,7 @@ We start with describing the most POJO friendly options.
In this approach you define `@Beans` in your application context as you would any other Spring managed object.
Internally, Spring AI `ChatClient` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
Internally, Spring AI `ChatConnector` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
The name of the `@Bean` is passed as a `ChatOption`.
@@ -139,7 +139,7 @@ static class Config {
}
----
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `MistralAiChatClient`.
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `MistralAiChatConnector`.
It also provides a description (2) and an optional response converter (3) to convert the response into a text as expected by the model.
NOTE: By default, the response converter does a JSON serialization of the Response object.
@@ -162,7 +162,7 @@ ChatResponse response = chatClient.call(new Prompt(List.of(userMessage),
logger.info("Response: {}", response);
----
// NOTE: You can can have multiple functions registered in your `ChatClient` but only those enabled in the prompt request will be considered for the function calling.
// NOTE: You can can have multiple functions registered in your `ChatConnector` but only those enabled in the prompt request will be considered for the function calling.
Above user question will trigger 3 calls to `CurrentWeather` function (one for each city) and produce the final response.
@@ -190,7 +190,7 @@ NOTE: The in-prompt registered functions are enabled by default for the duration
This approach allows to dynamically chose different functions to be called based on the user input.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/mistralai/tool/PaymentStatusPromptIT.java[PaymentStatusPromptIT.java] integration test provides a complete example of how to register a function with the `MistralAiChatClient` and use it in a prompt request.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/mistralai/tool/PaymentStatusPromptIT.java[PaymentStatusPromptIT.java] integration test provides a complete example of how to register a function with the `MistralAiChatConnector` and use it in a prompt request.
== Appendices

View File

@@ -1,6 +1,6 @@
= Function Calling
You can register custom Java functions with the `OpenAiChatClient` and have the OpenAI model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
You can register custom Java functions with the `OpenAiChatConnector` and have the OpenAI model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This allows you to connect the LLM capabilities with external tools and APIs.
The OpenAI models are trained to detect when a function should be called and to respond with JSON that adheres to the function signature.
@@ -11,12 +11,12 @@ In general, the custom functions need to provide a function `name`, `descriptio
As a developer, you need to implement a function that takes the function call arguments sent from the AI model, and respond with the result back to the model. Your function can in turn invoke other 3rd party services to provide the results.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatClient`.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatConnector`.
Under the hood, Spring wraps your POJO (the function) with the appropriate adapter code that enables interaction with the AI Model, saving you from writing tedious boilerplate code.
The basis of the underlying infrastructure is the link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallback.java[FunctionCallback.java] interface and the companion link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallbackWrapper.java[FunctionCallbackWrapper.java] utility class to simplify the implementation and registration of Java callback functions.
// Additionally, the Auto-Configuration provides a way to auto-register any Function<I, O> beans definition as function calling candidates in the `ChatClient`.
// Additionally, the Auto-Configuration provides a way to auto-register any Function<I, O> beans definition as function calling candidates in the `ChatConnector`.
== How it works
@@ -71,7 +71,7 @@ We start with describing the most POJO friendly options.
In this approach you define `@Beans` in your application context as you would any other Spring managed object.
Internally, Spring AI `ChatClient` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
Internally, Spring AI `ChatConnector` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
The name of the `@Bean` is passed as a `ChatOption`.
@@ -136,7 +136,7 @@ static class Config {
}
----
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `OpenAiChatClient`.
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `OpenAiChatConnector`.
It also provides a description (2) and an optional response converter (3) to convert the response into a text as expected by the model.
NOTE: By default, the response converter does a JSON serialization of the Response object.
@@ -159,7 +159,7 @@ ChatResponse response = chatClient.call(new Prompt(List.of(userMessage),
logger.info("Response: {}", response);
----
// NOTE: You can can have multiple functions registered in your `ChatClient` but only those enabled in the prompt request will be considered for the function calling.
// NOTE: You can can have multiple functions registered in your `ChatConnector` but only those enabled in the prompt request will be considered for the function calling.
Above user question will trigger 3 calls to `CurrentWeather` function (one for each city) and the final response will be something like this:
@@ -197,11 +197,11 @@ NOTE: The in-prompt registered functions are enabled by default for the duration
This approach allows to dynamically chose different functions to be called based on the user input.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/openai/tool/FunctionCallbackInPromptIT.java[FunctionCallbackInPromptIT.java] integration test provides a complete example of how to register a function with the `OpenAiChatClient` and use it in a prompt request.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/openai/tool/FunctionCallbackInPromptIT.java[FunctionCallbackInPromptIT.java] integration test provides a complete example of how to register a function with the `OpenAiChatConnector` and use it in a prompt request.
//
// === Register Functions with Default Options
//
// You can programmatically register functions with the `OpenAiChatClient` using the `OpenAiChatOptions#withFunctionCallbacks`:
// You can programmatically register functions with the `OpenAiChatConnector` using the `OpenAiChatOptions#withFunctionCallbacks`:
//
// [source,java]
// ----
@@ -215,7 +215,7 @@ The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot
// new MockWeatherService()))) // function code
// .build();
//
// OpenAiChatClient chatClient = new OpenAiChatClient(openaiApi, defaultOptions);
// OpenAiChatConnector chatClient = new OpenAiChatConnector(openaiApi, defaultOptions);
//
// UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");
//
@@ -223,7 +223,7 @@ The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot
// OpenAiChatOptions.builder().withFunction("CurrentWeather").build())); // Enable the function
// ----
//
// NOTE: Functions are registered when OpenAiChatClient is created, by you must enable in the Prompt the functions to be used in the request.
// NOTE: Functions are registered when OpenAiChatConnector is created, by you must enable in the Prompt the functions to be used in the request.
== Appendices:

View File

@@ -6,7 +6,7 @@ The parallel function calling is gone as well.
Function calling lets developers create a description of a function in their code, then pass that description to a language model in a request. The response from the model includes the name of a function that matches the description and the arguments to call it with.
You can register custom Java functions with the `VertexAiGeminiChatClient` and have the Gemini Pro model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
You can register custom Java functions with the `VertexAiGeminiChatConnector` and have the Gemini Pro model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This allows you to connect the LLM capabilities with external tools and APIs.
The VertexAI Gemini Pro model is trained to detect when a function should be called and to respond with JSON that adheres to the function signature.
@@ -18,12 +18,12 @@ In general, the custom functions need to provide a function `name`, `description
As a developer, you need to implement a function that takes the function call arguments sent from the AI model, and respond with the result back to the model.
Your function can in turn invoke other 3rd party services to provide the results.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatClient`.
Spring AI makes this as easy as defining a `@Bean` definition that returns a `java.util.Function` and supplying the bean name as an option when invoking the `ChatConnector`.
Under the hood, Spring wraps your POJO (the function) with the appropriate adapter code that enables interaction with the AI Model, saving you from writing tedious boilerplate code.
The basis of the underlying infrastructure is the link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallback.java[FunctionCallback.java] interface and the companion link:https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/model/function/FunctionCallbackWrapper.java[FunctionCallbackWrapper.java] utility class to simplify the implementation and registration of Java callback functions.
// Additionally, the Auto-Configuration provides a way to auto-register any Function<I, O> beans definition as function calling candidates in the `ChatClient`.
// Additionally, the Auto-Configuration provides a way to auto-register any Function<I, O> beans definition as function calling candidates in the `ChatConnector`.
== How it works
@@ -74,7 +74,7 @@ We start with describing the most POJO friendly options.
In this approach you define `@Beans` in your application context as you would any other Spring managed object.
Internally, Spring AI `ChatClient` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
Internally, Spring AI `ChatConnector` will create an instance of a `FunctionCallbackWrapper` wrapper that adds the logic for it being invoked via the AI model.
The name of the `@Bean` is passed as a `ChatOption`.
@@ -139,7 +139,7 @@ static class Config {
}
----
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `VertexAiGeminiChatClient`.
It wraps the 3rd party `MockWeatherService` function and registers it as a `CurrentWeather` function with the `VertexAiGeminiChatConnector`.
It also provides a description (2) and sets the Schema type to Open API type (3).
NOTE: The default response converter does a JSON serialization of the Response object.
@@ -162,7 +162,7 @@ ChatResponse response = chatClient.call(new Prompt(List.of(userMessage),
logger.info("Response: {}", response);
----
// NOTE: You can can have multiple functions registered in your `ChatClient` but only those enabled in the prompt request will be considered for the function calling.
// NOTE: You can can have multiple functions registered in your `ChatConnector` but only those enabled in the prompt request will be considered for the function calling.
Above user question will trigger 3 calls to `CurrentWeather` function (one for each city) and the final response will be something like this:
@@ -201,5 +201,5 @@ NOTE: The in-prompt registered functions are enabled by default for the duration
This approach allows to dynamically chose different functions to be called based on the user input.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/gemini/tool/FunctionCallWithPromptFunctionIT.java[FunctionCallWithPromptFunctionIT.java] integration test provides a complete example of how to register a function with the `VertexAiGeminiChatClient` and use it in a prompt request.
The https://github.com/spring-projects/spring-ai/blob/main/spring-ai-spring-boot-autoconfigure/src/test/java/org/springframework/ai/autoconfigure/gemini/tool/FunctionCallWithPromptFunctionIT.java[FunctionCallWithPromptFunctionIT.java] integration test provides a complete example of how to register a function with the `VertexAiGeminiChatConnector` and use it in a prompt request.

View File

@@ -103,7 +103,7 @@ The prefix `spring.ai.mistralai.chat` is the property prefix that lets you confi
| spring.ai.mistralai.chat.options.functionCallbacks | MistralAI Tool Function Callbacks to register with the ChatClient. | -
|====
NOTE: You can override the common `spring.ai.mistralai.base-url` and `spring.ai.mistralai.api-key` for the `ChatClient` and `EmbeddingClient` implementations.
NOTE: You can override the common `spring.ai.mistralai.base-url` and `spring.ai.mistralai.api-key` for the `ChatConnector` and `EmbeddingClient` implementations.
The `spring.ai.mistralai.chat.base-url` and `spring.ai.mistralai.chat.api-key` properties if set take precedence over the common properties.
This is useful if you want to use different MistralAI accounts for different models and different model endpoints.
@@ -153,7 +153,7 @@ spring.ai.mistralai.chat.options.temperature=0.7
TIP: replace the `api-key` with your OpenAI credentials.
This will create a `MistralAiChatClient` implementation that you can inject into your class.
This will create a `MistralAiChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -183,7 +183,7 @@ public class ChatController {
== Manual Configuration
The link:https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-mistral-ai/src/main/java/org/springframework/ai/mistralai/MistralAiChatClient.java[MistralAiChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the MistralAI service.
The link:https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-mistral-ai/src/main/java/org/springframework/ai/mistralai/MistralAiChatClient.java[MistralAiChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the MistralAI service.
Add the `spring-ai-mistral-ai` dependency to your project's Maven `pom.xml` file:
@@ -206,7 +206,7 @@ dependencies {
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
Next, create a `MistralAiChatClient` and use it for text generations:
Next, create a `MistralAiChatConnector` and use it for text generations:
[source,java]
----

View File

@@ -1,7 +1,7 @@
= Ollama Chat
With https://ollama.ai/[Ollama] you can run various Large Language Models (LLMs) locally and generate text from them.
Spring AI supports the Ollama text generation with `OllamaChatClient`.
Spring AI supports the Ollama text generation with `OllamaChatConnector`.
== Prerequisites
@@ -185,7 +185,7 @@ spring.ai.ollama.chat.options.temperature=0.7
TIP: replace the `base-url` with your Ollama server URL.
This will create a `OllamaChatClient` implementation that you can inject into your class.
This will create a `OllamaChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -216,8 +216,8 @@ public class ChatController {
== Manual Configuration
If you don't want to use the Spring Boot auto-configuration, you can manually configure the `OllamaChatClient` in your application.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-ollama/src/main/java/org/springframework/ai/ollama/OllamaChatClient.java[OllamaChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Ollama service.
If you don't want to use the Spring Boot auto-configuration, you can manually configure the `OllamaChatConnector` in your application.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-ollama/src/main/java/org/springframework/ai/ollama/OllamaChatClient.java[OllamaChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the Ollama service.
To use it add the `spring-ai-ollama` dependency to your project's Maven `pom.xml` file:
@@ -243,7 +243,7 @@ TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Man
TIP: The `spring-ai-ollama` dependency provides access also to the `OllamaEmbeddingClient`.
For more information about the `OllamaEmbeddingClient` refer to the link:../embeddings/ollama-embeddings.html[Ollama Embedding Client] section.
Next, create an `OllamaChatClient` instance and use it to text generations requests:
Next, create an `OllamaChatConnector` instance and use it to text generations requests:
[source,java]
----
@@ -274,7 +274,7 @@ image::ollama-chat-completion-api.jpg[OllamaApi Chat Completion API Diagram, 800
Here is a simple snippet showing how to use the API programmatically:
NOTE: The `OllamaApi` is low level api and is not recommended for direct use. Use the `OllamaChatClient` instead.
NOTE: The `OllamaApi` is low level api and is not recommended for direct use. Use the `OllamaChatConnector` instead.
[source,java]
----

View File

@@ -107,7 +107,7 @@ The prefix `spring.ai.openai.chat` is the property prefix that lets you configur
| spring.ai.openai.chat.options.functions | List of functions, identified by their names, to enable for function calling in a single prompt requests. Functions with those names must exist in the functionCallbacks registry. | -
|====
NOTE: You can override the common `spring.ai.openai.base-url` and `spring.ai.openai.api-key` for the `ChatClient` and `EmbeddingClient` implementations.
NOTE: You can override the common `spring.ai.openai.base-url` and `spring.ai.openai.api-key` for the `ChatConnector` and `EmbeddingClient` implementations.
The `spring.ai.openai.chat.base-url` and `spring.ai.openai.chat.api-key` properties if set take precedence over the common properties.
This is useful if you want to use different OpenAI accounts for different models and different model endpoints.
@@ -209,7 +209,7 @@ spring.ai.openai.chat.options.temperature=0.7
TIP: replace the `api-key` with your OpenAI credentials.
This will create a `OpenAiChatClient` implementation that you can inject into your class.
This will create a `OpenAiChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -239,7 +239,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatClient.java[OpenAiChatClient] implements the `ChatClient` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the OpenAI service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatClient.java[OpenAiChatClient] implements the `ChatConnector` and `StreamingChatClient` and uses the <<low-level-api>> to connect to the OpenAI service.
Add the `spring-ai-openai` dependency to your project's Maven `pom.xml` file:
@@ -262,7 +262,7 @@ dependencies {
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
Next, create a `OpenAiChatClient` and use it for text generations:
Next, create a `OpenAiChatConnector` and use it for text generations:
[source,java]
----

View File

@@ -150,7 +150,7 @@ spring.ai.vertex.ai.gemini.chat.options.temperature=0.5
TIP: replace the `api-key` with your VertexAI credentials.
This will create a `VertexAiGeminiChatClient` implementation that you can inject into your class.
This will create a `VertexAiGeminiChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -180,7 +180,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-vertex-ai-gemini/src/main/java/org/springframework/ai/vertexai/gemini/VertexAiGeminiChatClient.java[VertexAiGeminiChatClient] implements the `ChatClient` and uses the `VertexAI` to connect to the Vertex AI Gemini service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-vertex-ai-gemini/src/main/java/org/springframework/ai/vertexai/gemini/VertexAiGeminiChatClient.java[VertexAiGeminiChatClient] implements the `ChatConnector` and uses the `VertexAI` to connect to the Vertex AI Gemini service.
Add the `spring-ai-vertex-ai-gemini` dependency to your project's Maven `pom.xml` file:
@@ -203,7 +203,7 @@ dependencies {
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
Next, create a `VertexAiGeminiChatClient` and use it for text generations:
Next, create a `VertexAiGeminiChatConnector` and use it for text generations:
[source,java]
----

View File

@@ -114,7 +114,7 @@ spring.ai.vertex.ai.chat.options.temperature=0.5
TIP: replace the `api-key` with your VertexAI credentials.
This will create a `VertexAiPaLm2ChatClient` implementation that you can inject into your class.
This will create a `VertexAiPaLm2ChatConnector` implementation that you can inject into your class.
Here is an example of a simple `@Controller` class that uses the chat client for text generations.
[source,java]
@@ -144,7 +144,7 @@ public class ChatController {
== Manual Configuration
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/vertexai/paml2/VertexAiPaLm2ChatClient.java[VertexAiPaLm2ChatClient] implements the `ChatClient` and uses the <<low-level-api>> to connect to the VertexAI service.
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/vertexai/paml2/VertexAiPaLm2ChatClient.java[VertexAiPaLm2ChatClient] implements the `ChatConnector` and uses the <<low-level-api>> to connect to the VertexAI service.
Add the `spring-ai-vertex-ai-palm2` dependency to your project's Maven `pom.xml` file:
@@ -167,7 +167,7 @@ dependencies {
TIP: Refer to the xref:getting-started.adoc#dependency-management[Dependency Management] section to add the Spring AI BOM to your build file.
Next, create a `VertexAiPaLm2ChatClient` and use it for text generations:
Next, create a `VertexAiPaLm2ChatConnector` and use it for text generations:
[source,java]
----

View File

@@ -1,7 +1,7 @@
= watsonx.ai Chat
With https://dataplatform.cloud.ibm.com/docs/content/wsj/getting-started/overview-wx.html?context=wx&audience=wdp[watsonx.ai] you can run various Large Language Models (LLMs) locally and generate text from them.
Spring AI supports the watsonx.ai text generation with `WatsonxAiChatClient`.
Spring AI supports the watsonx.ai text generation with `WatsonxAiChatConnector`.
== Prerequisites

Some files were not shown because too many files have changed in this diff Show More