code
stringlengths 1.02k
14.1k
| apis
sequencelengths 1
7
| extract_api
stringlengths 72
2.99k
|
---|---|---|
package com.vmware.tap.accelerators.aichat;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.memory.ConversationBufferMemory;
import org.springframework.ai.memory.Memory;
import org.springframework.ai.operator.AiOperator;
import org.springframework.ai.operator.DefaultPromptTemplateStrings;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
@Configuration
public class AIConfig {
@Bean
@Scope(value="session", proxyMode = ScopedProxyMode.INTERFACES)
Memory memory() {
return new ConversationBufferMemory();
}
@Bean
AiOperator aiOperator(ChatClient aiClient, VectorStore vectorStore, Memory memory) {
return AiOperator.builder()
.aiClient(aiClient)
.promptTemplate(DefaultPromptTemplateStrings.RAG_PROMPT)
.conversationMemory(memory)
.vectorStore(vectorStore)
.build();
}
}
| [
"org.springframework.ai.operator.AiOperator.builder"
] | [((913, 1153), 'org.springframework.ai.operator.AiOperator.builder'), ((913, 1128), 'org.springframework.ai.operator.AiOperator.builder'), ((913, 1086), 'org.springframework.ai.operator.AiOperator.builder'), ((913, 1042), 'org.springframework.ai.operator.AiOperator.builder'), ((913, 969), 'org.springframework.ai.operator.AiOperator.builder')] |
package com.example.springai.aoai.service;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import com.example.springai.aoai.dto.ChatMessageDto;
import com.example.springai.aoai.exception.TooManyRequestsException;
import com.example.springai.aoai.mapper.ChatMessageMapper;
import com.knuddels.jtokkit.Encodings;
import com.knuddels.jtokkit.api.Encoding;
import com.knuddels.jtokkit.api.ModelType;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.azure.openai.AzureOpenAiChatClient;
import org.springframework.ai.azure.openai.AzureOpenAiChatOptions;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import reactor.core.publisher.Flux;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Chatbot service
*/
@Service
@Slf4j
public class ChatbotService {
@Autowired
private final ChatClient chatClient;
@Autowired
private final SystemMessage systemMessage;
@Autowired
private final ChatMessageMapper chatMessageMapper;
@Value("${spring.ai.azure.openai.endpoint}")
private String azureOpenAiEndpoint;
@Value("${spring.ai.azure.openai.api-key}")
private String azureOpenAiApiKey;
@Value("${spring.ai.azure.openai.chat.options.model}")
private String model;
@Value("${spring.ai.azure.openai.chat.options.max-tokens}")
private Integer maxTokens;
@Value("${spring.ai.azure.openai.chat.options.temperature}")
private Float temperature;
private Encoding encoding;
private Optional<ModelType> modelType;
/**
* Constructor
*
* @param chatClient the chatClient
* @param systemMessage the system message
* @param chatMessageMapper the ChatMessage Mapper
*/
public ChatbotService(ChatClient chatClient, SystemMessage systemMessage, ChatMessageMapper chatMessageMapper) {
this.chatClient = chatClient;
this.systemMessage = systemMessage;
this.chatMessageMapper = chatMessageMapper;
}
/**
* Calls OpenAI chat completion API and returns a Generation object
* Retry with exponential backoff on 429 Too Many Requests status code
*
* @param chatMessageDtos list of all user and assistant messages
* @return a Generation object
*/
@Retryable(
retryFor = {TooManyRequestsException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 1000, maxDelay = 5000, multiplier = 2))
public Optional<Generation> completion(List<ChatMessageDto> chatMessageDtos) {
List<Message> messages = new ArrayList<>(chatMessageMapper.toMessage(chatMessageDtos));
messages.add(0, systemMessage);
Prompt prompt = new Prompt(messages);
Generation gen = null;
try {
gen = chatClient.call(prompt).getResults().get(0);
} catch (RuntimeException e) {
log.error("Caught a RuntimeException: " + e.getMessage());
if (e instanceof HttpClientErrorException) {
if (((HttpClientErrorException) e).getStatusCode().equals(HttpStatus.TOO_MANY_REQUESTS)) {
throw new TooManyRequestsException(e.getMessage());
}
}
}
return Optional.ofNullable(gen);
}
/**
* Calls OpenAI chat completion API in Stream mode and returns a Flux object
*
* @param chatMessageDtos list of all user and assistant messages
* @return a Generation object
*/
@Retryable(
retryFor = {TooManyRequestsException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 1000, maxDelay = 5000, multiplier = 2))
public Flux<Generation> completionWithStream(List<ChatMessageDto> chatMessageDtos) {
List<Message> messages = new ArrayList<>(chatMessageMapper.toMessage(chatMessageDtos));
messages.add(0, systemMessage);
Prompt prompt = new Prompt(messages);
OpenAIClientBuilder openAIClientBuilder = new OpenAIClientBuilder();
OpenAIClient openAIClient = openAIClientBuilder.credential(new AzureKeyCredential(azureOpenAiApiKey)).endpoint(azureOpenAiEndpoint).buildClient();
var azureOpenAiChatClient = new AzureOpenAiChatClient(openAIClient).withDefaultOptions(AzureOpenAiChatOptions.builder().withModel(model).withTemperature(temperature).withMaxTokens(maxTokens).build());
return azureOpenAiChatClient.stream(prompt)
.onErrorResume(e -> {
log.error("Caught a RuntimeException: " + e.getMessage());
if (e instanceof HttpClientErrorException) {
if (((HttpClientErrorException) e).getStatusCode().equals(HttpStatus.TOO_MANY_REQUESTS)) {
throw new TooManyRequestsException(e.getMessage());
}
}
return Flux.empty();
})
.flatMap(s -> Flux.fromIterable(s.getResults()));
}
/**
* Initializing encoding and model type after bean creation
*/
@PostConstruct
public void postConstructInit() {
//Hack because jtokkit's model name has a dot
this.modelType = ModelType.fromName(model.replace("35", "3.5"));
if (this.modelType.isEmpty()) {
log.error("Could not get model from name");
throw new IllegalStateException();
}
this.encoding = Encodings.newDefaultEncodingRegistry().getEncodingForModel(this.modelType.get());
}
/**
* Checking if the context window of the model is big enough
*
* @param chatMessageDtos list of all user and assistant messages
* @return true if the context window of the model is big enough, false if not
*/
public boolean isContextLengthValid(List<ChatMessageDto> chatMessageDtos) {
String contextWindow = systemMessage.getContent() + chatMessageDtos.stream()
.map(ChatMessageDto::getContent)
.collect(Collectors.joining());
int currentContextLength = this.encoding.countTokens(contextWindow);
if (this.modelType.isPresent()) {
return (this.modelType.get().getMaxContextLength() > (currentContextLength + maxTokens));
}
return false;
}
/**
* Adjusting the number of messages in the context window to fit the model's max context length
*
* @param chatMessageDtos list of all user and assistant messages
* @return same list if model's max context length has not been reached, smaller list if it has
*/
public List<ChatMessageDto> adjustContextWindow(List<ChatMessageDto> chatMessageDtos) {
List<ChatMessageDto> chatMessagesDtosAdjusted = new ArrayList<>(chatMessageDtos);
for (int i = 0; i < chatMessageDtos.size(); i++) {
if (!isContextLengthValid(chatMessagesDtosAdjusted)) {
chatMessagesDtosAdjusted.remove(0);
} else {
break;
}
}
return chatMessagesDtosAdjusted;
}
} | [
"org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder"
] | [((4999, 5110), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((4999, 5102), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((4999, 5077), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((4999, 5048), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((6165, 6245), 'com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry')] |
package br.com.valdemarjr.ai.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
/**
* Service responsible for deleting an existing database and initializing a new one with the data
* from the PDF file medicaid-wa-faqs.pdf.
*/
@Service
public class SetupService {
private static final Logger log = LoggerFactory.getLogger(SetupService.class);
@Value("classpath:medicaid-wa-faqs.pdf")
private Resource pdf;
private final JdbcTemplate jdbcTemplate;
private final VectorStore vectorStore;
public SetupService(JdbcTemplate jdbcTemplate, VectorStore vectorStore) {
this.jdbcTemplate = jdbcTemplate;
this.vectorStore = vectorStore;
}
public void init() {
// delete an existent database
jdbcTemplate.update("delete from vector_store");
// initialize a new database with the data from the PDF file
var config =
PdfDocumentReaderConfig.builder()
.withPageExtractedTextFormatter(
new ExtractedTextFormatter.Builder().withNumberOfBottomTextLinesToDelete(3).build())
.build();
var pdfReader = new PagePdfDocumentReader(pdf, config);
var textSplitter = new TokenTextSplitter();
var docs = textSplitter.apply(pdfReader.get());
// store the data in the vector store
vectorStore.accept(docs);
log.info("Vector store finished");
}
}
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder"
] | [((1398, 1598), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1398, 1577), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')] |
/*
* 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.bedrock.titan;
import java.util.List;
import reactor.core.publisher.Flux;
import org.springframework.ai.bedrock.MessageToPromptConverter;
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;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.Assert;
/**
* @author Christian Tzolov
* @since 0.8.0
*/
public class BedrockTitanChatClient implements ChatClient, StreamingChatClient {
private final TitanChatBedrockApi chatApi;
private final BedrockTitanChatOptions defaultOptions;
public BedrockTitanChatClient(TitanChatBedrockApi chatApi) {
this(chatApi, BedrockTitanChatOptions.builder().withTemperature(0.8f).build());
}
public BedrockTitanChatClient(TitanChatBedrockApi chatApi, BedrockTitanChatOptions defaultOptions) {
Assert.notNull(chatApi, "ChatApi must not be null");
Assert.notNull(defaultOptions, "DefaultOptions must not be null");
this.chatApi = chatApi;
this.defaultOptions = defaultOptions;
}
@Override
public ChatResponse call(Prompt prompt) {
TitanChatResponse response = this.chatApi.chatCompletion(this.createRequest(prompt));
List<Generation> generations = response.results().stream().map(result -> {
return new Generation(result.outputText());
}).toList();
return new ChatResponse(generations);
}
@Override
public Flux<ChatResponse> stream(Prompt prompt) {
return this.chatApi.chatCompletionStream(this.createRequest(prompt)).map(chunk -> {
Generation generation = new Generation(chunk.outputText());
if (chunk.amazonBedrockInvocationMetrics() != null) {
String completionReason = chunk.completionReason().name();
generation = generation.withGenerationMetadata(
ChatGenerationMetadata.from(completionReason, chunk.amazonBedrockInvocationMetrics()));
}
else if (chunk.inputTextTokenCount() != null && chunk.totalOutputTextTokenCount() != null) {
String completionReason = chunk.completionReason().name();
generation = generation
.withGenerationMetadata(ChatGenerationMetadata.from(completionReason, extractUsage(chunk)));
}
return new ChatResponse(List.of(generation));
});
}
/**
* Test access.
*/
TitanChatRequest createRequest(Prompt prompt) {
final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions());
var requestBuilder = TitanChatRequest.builder(promptValue);
if (this.defaultOptions != null) {
requestBuilder = update(requestBuilder, this.defaultOptions);
}
if (prompt.getOptions() != null) {
if (prompt.getOptions() instanceof ChatOptions runtimeOptions) {
BedrockTitanChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions,
ChatOptions.class, BedrockTitanChatOptions.class);
requestBuilder = update(requestBuilder, updatedRuntimeOptions);
}
else {
throw new IllegalArgumentException("Prompt options are not of type ChatOptions: "
+ prompt.getOptions().getClass().getSimpleName());
}
}
return requestBuilder.build();
}
private TitanChatRequest.Builder update(TitanChatRequest.Builder builder, BedrockTitanChatOptions options) {
if (options.getTemperature() != null) {
builder.withTemperature(options.getTemperature());
}
if (options.getTopP() != null) {
builder.withTopP(options.getTopP());
}
if (options.getMaxTokenCount() != null) {
builder.withMaxTokenCount(options.getMaxTokenCount());
}
if (options.getStopSequences() != null) {
builder.withStopSequences(options.getStopSequences());
}
return builder;
}
private Usage extractUsage(TitanChatResponseChunk response) {
return new Usage() {
@Override
public Long getPromptTokens() {
return response.inputTextTokenCount().longValue();
}
@Override
public Long getGenerationTokens() {
return response.totalOutputTextTokenCount().longValue();
}
};
}
}
| [
"org.springframework.ai.bedrock.MessageToPromptConverter.create"
] | [((3588, 3656), 'org.springframework.ai.bedrock.MessageToPromptConverter.create')] |
/*
* 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.
*/
/*
* Copyright 2024-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.metadata.RateLimit;
import org.springframework.ai.model.ModelClient;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.api.OpenAiAudioApi.StructuredResponse;
import org.springframework.ai.openai.audio.transcription.AudioTranscription;
import org.springframework.ai.openai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.openai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata;
import org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
/**
* OpenAI audio transcription client implementation for backed by {@link OpenAiAudioApi}.
* You provide as input the audio file you want to transcribe and the desired output file
* format of the transcription of the audio.
*
* @author Michael Lavelle
* @author Christian Tzolov
* @see OpenAiAudioApi
* @since 0.8.1
*/
public class OpenAiAudioTranscriptionClient
implements ModelClient<AudioTranscriptionPrompt, AudioTranscriptionResponse> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final OpenAiAudioTranscriptionOptions defaultOptions;
public final RetryTemplate retryTemplate;
private final OpenAiAudioApi audioApi;
/**
* OpenAiAudioTranscriptionClient is a client class used to interact with the OpenAI
* Audio Transcription API.
* @param audioApi The OpenAiAudioApi instance to be used for making API calls.
*/
public OpenAiAudioTranscriptionClient(OpenAiAudioApi audioApi) {
this(audioApi,
OpenAiAudioTranscriptionOptions.builder()
.withModel(OpenAiAudioApi.WhisperModel.WHISPER_1.getValue())
.withResponseFormat(OpenAiAudioApi.TranscriptResponseFormat.JSON)
.withTemperature(0.7f)
.build(),
RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
/**
* OpenAiAudioTranscriptionClient is a client class used to interact with the OpenAI
* Audio Transcription API.
* @param audioApi The OpenAiAudioApi instance to be used for making API calls.
* @param options The OpenAiAudioTranscriptionOptions instance for configuring the
* audio transcription.
*/
public OpenAiAudioTranscriptionClient(OpenAiAudioApi audioApi, OpenAiAudioTranscriptionOptions options) {
this(audioApi, options, RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
/**
* OpenAiAudioTranscriptionClient is a client class used to interact with the OpenAI
* Audio Transcription API.
* @param audioApi The OpenAiAudioApi instance to be used for making API calls.
* @param options The OpenAiAudioTranscriptionOptions instance for configuring the
* audio transcription.
* @param retryTemplate The RetryTemplate instance for retrying failed API calls.
*/
public OpenAiAudioTranscriptionClient(OpenAiAudioApi audioApi, OpenAiAudioTranscriptionOptions options,
RetryTemplate retryTemplate) {
Assert.notNull(audioApi, "OpenAiAudioApi must not be null");
Assert.notNull(options, "OpenAiTranscriptionOptions must not be null");
Assert.notNull(retryTemplate, "RetryTemplate must not be null");
this.audioApi = audioApi;
this.defaultOptions = options;
this.retryTemplate = retryTemplate;
}
public String call(Resource audioResource) {
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioResource);
return call(transcriptionRequest).getResult().getOutput();
}
@Override
public AudioTranscriptionResponse call(AudioTranscriptionPrompt request) {
return this.retryTemplate.execute(ctx -> {
Resource audioResource = request.getInstructions();
OpenAiAudioApi.TranscriptionRequest requestBody = createRequestBody(request);
if (requestBody.responseFormat().isJsonType()) {
ResponseEntity<StructuredResponse> transcriptionEntity = this.audioApi.createTranscription(requestBody,
StructuredResponse.class);
var transcription = transcriptionEntity.getBody();
if (transcription == null) {
logger.warn("No transcription returned for request: {}", audioResource);
return new AudioTranscriptionResponse(null);
}
AudioTranscription transcript = new AudioTranscription(transcription.text());
RateLimit rateLimits = OpenAiResponseHeaderExtractor.extractAiResponseHeaders(transcriptionEntity);
return new AudioTranscriptionResponse(transcript,
OpenAiAudioTranscriptionResponseMetadata.from(transcriptionEntity.getBody())
.withRateLimit(rateLimits));
}
else {
ResponseEntity<String> transcriptionEntity = this.audioApi.createTranscription(requestBody,
String.class);
var transcription = transcriptionEntity.getBody();
if (transcription == null) {
logger.warn("No transcription returned for request: {}", audioResource);
return new AudioTranscriptionResponse(null);
}
AudioTranscription transcript = new AudioTranscription(transcription);
RateLimit rateLimits = OpenAiResponseHeaderExtractor.extractAiResponseHeaders(transcriptionEntity);
return new AudioTranscriptionResponse(transcript,
OpenAiAudioTranscriptionResponseMetadata.from(transcriptionEntity.getBody())
.withRateLimit(rateLimits));
}
});
}
OpenAiAudioApi.TranscriptionRequest createRequestBody(AudioTranscriptionPrompt request) {
OpenAiAudioTranscriptionOptions options = this.defaultOptions;
if (request.getOptions() != null) {
if (request.getOptions() instanceof OpenAiAudioTranscriptionOptions runtimeOptions) {
options = this.merge(options, runtimeOptions);
}
else {
throw new IllegalArgumentException("Prompt options are not of type TranscriptionOptions: "
+ request.getOptions().getClass().getSimpleName());
}
}
OpenAiAudioApi.TranscriptionRequest audioTranscriptionRequest = OpenAiAudioApi.TranscriptionRequest.builder()
.withFile(toBytes(request.getInstructions()))
.withResponseFormat(options.getResponseFormat())
.withPrompt(options.getPrompt())
.withTemperature(options.getTemperature())
.withLanguage(options.getLanguage())
.withModel(options.getModel())
.build();
return audioTranscriptionRequest;
}
private byte[] toBytes(Resource resource) {
try {
return resource.getInputStream().readAllBytes();
}
catch (Exception e) {
throw new IllegalArgumentException("Failed to read resource: " + resource, e);
}
}
private OpenAiAudioTranscriptionOptions merge(OpenAiAudioTranscriptionOptions source,
OpenAiAudioTranscriptionOptions target) {
if (source == null) {
source = new OpenAiAudioTranscriptionOptions();
}
OpenAiAudioTranscriptionOptions merged = new OpenAiAudioTranscriptionOptions();
merged.setLanguage(source.getLanguage() != null ? source.getLanguage() : target.getLanguage());
merged.setModel(source.getModel() != null ? source.getModel() : target.getModel());
merged.setPrompt(source.getPrompt() != null ? source.getPrompt() : target.getPrompt());
merged.setResponseFormat(
source.getResponseFormat() != null ? source.getResponseFormat() : target.getResponseFormat());
merged.setTemperature(source.getTemperature() != null ? source.getTemperature() : target.getTemperature());
return merged;
}
}
| [
"org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder",
"org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata.from",
"org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel.WHISPER_1.getValue"
] | [((3250, 3298), 'org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel.WHISPER_1.getValue'), ((5935, 6045), 'org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata.from'), ((6648, 6758), 'org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata.from'), ((7356, 7670), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((7356, 7658), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((7356, 7624), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((7356, 7584), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((7356, 7538), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((7356, 7502), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((7356, 7450), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((7356, 7401), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder')] |
package org.springframework.ai.autoconfigure.dashscope.qwen;
import org.springframework.ai.dashscope.metadata.support.ChatModel;
import org.springframework.ai.dashscope.qwen.QWenChatOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@ConfigurationProperties(DashsCopeQwenChatProperties.CONFIG_PREFIX)
public class DashsCopeQwenChatProperties {
public static final String CONFIG_PREFIX = "spring.ai.dashscope.qwen.chat";
private String model = ChatModel.QWen_72B_CHAT.getModelValue();
@NestedConfigurationProperty
private QWenChatOptions options = QWenChatOptions.builder().build();
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public QWenChatOptions getOptions() {
return options;
}
public void setOptions(QWenChatOptions options) {
this.options = options;
}
}
| [
"org.springframework.ai.dashscope.metadata.support.ChatModel.QWen_72B_CHAT.getModelValue",
"org.springframework.ai.dashscope.qwen.QWenChatOptions.builder"
] | [((569, 608), 'org.springframework.ai.dashscope.metadata.support.ChatModel.QWen_72B_CHAT.getModelValue'), ((682, 715), 'org.springframework.ai.dashscope.qwen.QWenChatOptions.builder')] |
/*
* 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.postgresml;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.MetadataMode;
import org.springframework.ai.embedding.AbstractEmbeddingClient;
import org.springframework.ai.embedding.Embedding;
import org.springframework.ai.embedding.EmbeddingOptions;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.embedding.EmbeddingResponseMetadata;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* <a href="https://postgresml.org">PostgresML</a> EmbeddingClient
*
* @author Toshiaki Maki
* @author Christian Tzolov
*/
public class PostgresMlEmbeddingClient extends AbstractEmbeddingClient implements InitializingBean {
public static final String DEFAULT_TRANSFORMER_MODEL = "distilbert-base-uncased";
private final PostgresMlEmbeddingOptions defaultOptions;
private final JdbcTemplate jdbcTemplate;
public enum VectorType {
PG_ARRAY("", null, (rs, i) -> {
Array embedding = rs.getArray("embedding");
return Arrays.stream((Float[]) embedding.getArray()).map(Float::doubleValue).toList();
}),
PG_VECTOR("::vector", "vector", (rs, i) -> {
String embedding = rs.getString("embedding");
return Arrays.stream((embedding.substring(1, embedding.length() - 1)
/* remove leading '[' and trailing ']' */.split(","))).map(Double::parseDouble).toList();
});
private final String cast;
private final String extensionName;
private final RowMapper<List<Double>> rowMapper;
VectorType(String cast, String extensionName, RowMapper<List<Double>> rowMapper) {
this.cast = cast;
this.extensionName = extensionName;
this.rowMapper = rowMapper;
}
}
/**
* a constructor
* @param jdbcTemplate JdbcTemplate
*/
public PostgresMlEmbeddingClient(JdbcTemplate jdbcTemplate) {
this(jdbcTemplate, PostgresMlEmbeddingOptions.builder().build());
}
/**
* a PostgresMlEmbeddingClient constructor
* @param jdbcTemplate JdbcTemplate to use to interact with the database.
* @param options PostgresMlEmbeddingOptions to configure the client.
*/
public PostgresMlEmbeddingClient(JdbcTemplate jdbcTemplate, PostgresMlEmbeddingOptions options) {
Assert.notNull(jdbcTemplate, "jdbc template must not be null.");
Assert.notNull(options, "options must not be null.");
Assert.notNull(options.getTransformer(), "transformer must not be null.");
Assert.notNull(options.getVectorType(), "vectorType must not be null.");
Assert.notNull(options.getKwargs(), "kwargs must not be null.");
Assert.notNull(options.getMetadataMode(), "metadataMode must not be null.");
this.jdbcTemplate = jdbcTemplate;
this.defaultOptions = options;
}
/**
* a constructor
* @param jdbcTemplate JdbcTemplate
* @param transformer huggingface sentence-transformer name
*/
@Deprecated(since = "0.8.0", forRemoval = true)
public PostgresMlEmbeddingClient(JdbcTemplate jdbcTemplate, String transformer) {
this(jdbcTemplate, transformer, VectorType.PG_ARRAY);
}
/**
* a constructor
* @deprecated Use the constructor with {@link PostgresMlEmbeddingOptions} instead.
* @param jdbcTemplate JdbcTemplate
* @param transformer huggingface sentence-transformer name
* @param vectorType vector type in PostgreSQL
*/
@Deprecated(since = "0.8.0", forRemoval = true)
public PostgresMlEmbeddingClient(JdbcTemplate jdbcTemplate, String transformer, VectorType vectorType) {
this(jdbcTemplate, transformer, vectorType, Map.of(), MetadataMode.EMBED);
}
/**
* a constructor * @deprecated Use the constructor with
* {@link PostgresMlEmbeddingOptions} instead.
* @param jdbcTemplate JdbcTemplate
* @param transformer huggingface sentence-transformer name
* @param vectorType vector type in PostgreSQL
* @param kwargs optional arguments
*/
@Deprecated(since = "0.8.0", forRemoval = true)
public PostgresMlEmbeddingClient(JdbcTemplate jdbcTemplate, String transformer, VectorType vectorType,
Map<String, Object> kwargs, MetadataMode metadataMode) {
Assert.notNull(jdbcTemplate, "jdbc template must not be null.");
Assert.notNull(transformer, "transformer must not be null.");
Assert.notNull(vectorType, "vectorType must not be null.");
Assert.notNull(kwargs, "kwargs must not be null.");
Assert.notNull(metadataMode, "metadataMode must not be null.");
this.jdbcTemplate = jdbcTemplate;
this.defaultOptions = PostgresMlEmbeddingOptions.builder()
.withTransformer(transformer)
.withVectorType(vectorType)
.withMetadataMode(metadataMode)
.withKwargs(ModelOptionsUtils.toJsonString(kwargs))
.build();
}
@SuppressWarnings("null")
@Override
public List<Double> embed(String text) {
return this.jdbcTemplate.queryForObject(
"SELECT pgml.embed(?, ?, ?::JSONB)" + this.defaultOptions.getVectorType().cast + " AS embedding",
this.defaultOptions.getVectorType().rowMapper, this.defaultOptions.getTransformer(), text,
this.defaultOptions.getKwargs());
}
@Override
public List<Double> embed(Document document) {
return this.embed(document.getFormattedContent(this.defaultOptions.getMetadataMode()));
}
@SuppressWarnings("null")
@Override
public EmbeddingResponse call(EmbeddingRequest request) {
final PostgresMlEmbeddingOptions optionsToUse = this.mergeOptions(request.getOptions());
List<Embedding> data = new ArrayList<>();
List<List<Double>> embed = List.of();
List<String> texts = request.getInstructions();
if (!CollectionUtils.isEmpty(texts)) {
embed = this.jdbcTemplate.query(connection -> {
PreparedStatement preparedStatement = connection.prepareStatement("SELECT pgml.embed(?, text, ?::JSONB)"
+ optionsToUse.getVectorType().cast + " AS embedding FROM (SELECT unnest(?) AS text) AS texts");
preparedStatement.setString(1, optionsToUse.getTransformer());
preparedStatement.setString(2, ModelOptionsUtils.toJsonString(optionsToUse.getKwargs()));
preparedStatement.setArray(3, connection.createArrayOf("TEXT", texts.toArray(Object[]::new)));
return preparedStatement;
}, rs -> {
List<List<Double>> result = new ArrayList<>();
while (rs.next()) {
result.add(optionsToUse.getVectorType().rowMapper.mapRow(rs, -1));
}
return result;
});
}
if (!CollectionUtils.isEmpty(embed)) {
for (int i = 0; i < embed.size(); i++) {
data.add(new Embedding(embed.get(i), i));
}
}
var metadata = new EmbeddingResponseMetadata(
Map.of("transformer", optionsToUse.getTransformer(), "vector-type", optionsToUse.getVectorType().name(),
"kwargs", ModelOptionsUtils.toJsonString(optionsToUse.getKwargs())));
return new EmbeddingResponse(data, metadata);
}
/**
* Merge the default and request options.
* @param requestOptions request options to merge.
* @return the merged options.
*/
PostgresMlEmbeddingOptions mergeOptions(EmbeddingOptions requestOptions) {
PostgresMlEmbeddingOptions options = (this.defaultOptions != null) ? this.defaultOptions
: PostgresMlEmbeddingOptions.builder().build();
if (requestOptions != null && !EmbeddingOptions.EMPTY.equals(requestOptions)) {
options = ModelOptionsUtils.merge(requestOptions, options, PostgresMlEmbeddingOptions.class);
}
return options;
}
@Override
public void afterPropertiesSet() {
this.jdbcTemplate.execute("CREATE EXTENSION IF NOT EXISTS pgml");
this.jdbcTemplate.execute("CREATE EXTENSION IF NOT EXISTS hstore");
if (StringUtils.hasText(this.defaultOptions.getVectorType().extensionName)) {
this.jdbcTemplate
.execute("CREATE EXTENSION IF NOT EXISTS " + this.defaultOptions.getVectorType().extensionName);
}
}
}
| [
"org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals"
] | [((2165, 2243), 'java.util.Arrays.stream'), ((2165, 2234), 'java.util.Arrays.stream'), ((2358, 2512), 'java.util.Arrays.stream'), ((2358, 2503), 'java.util.Arrays.stream'), ((8178, 8223), 'org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals')] |
/*
* 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.bedrock.cohere;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi;
import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingRequest;
import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingResponse;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.AbstractEmbeddingClient;
import org.springframework.ai.embedding.Embedding;
import org.springframework.ai.embedding.EmbeddingOptions;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.Assert;
/**
* {@link org.springframework.ai.embedding.EmbeddingClient} implementation that uses the
* Bedrock Cohere Embedding API. Note: The invocation metrics are not exposed by AWS for
* this API. If this change in the future we will add it as metadata.
*
* @author Christian Tzolov
* @since 0.8.0
*/
public class BedrockCohereEmbeddingClient extends AbstractEmbeddingClient {
private final CohereEmbeddingBedrockApi embeddingApi;
private final BedrockCohereEmbeddingOptions defaultOptions;
// private CohereEmbeddingRequest.InputType inputType =
// CohereEmbeddingRequest.InputType.SEARCH_DOCUMENT;
// private CohereEmbeddingRequest.Truncate truncate =
// CohereEmbeddingRequest.Truncate.NONE;
public BedrockCohereEmbeddingClient(CohereEmbeddingBedrockApi cohereEmbeddingBedrockApi) {
this(cohereEmbeddingBedrockApi,
BedrockCohereEmbeddingOptions.builder()
.withInputType(CohereEmbeddingRequest.InputType.SEARCH_DOCUMENT)
.withTruncate(CohereEmbeddingRequest.Truncate.NONE)
.build());
}
public BedrockCohereEmbeddingClient(CohereEmbeddingBedrockApi cohereEmbeddingBedrockApi,
BedrockCohereEmbeddingOptions options) {
Assert.notNull(cohereEmbeddingBedrockApi, "CohereEmbeddingBedrockApi must not be null");
Assert.notNull(options, "BedrockCohereEmbeddingOptions must not be null");
this.embeddingApi = cohereEmbeddingBedrockApi;
this.defaultOptions = options;
}
// /**
// * Cohere Embedding API input types.
// * @param inputType the input type to use.
// * @return this client.
// */
// public BedrockCohereEmbeddingClient withInputType(CohereEmbeddingRequest.InputType
// inputType) {
// this.inputType = inputType;
// return this;
// }
// /**
// * Specifies how the API handles inputs longer than the maximum token length. If you
// specify LEFT or RIGHT, the
// * model discards the input until the remaining input is exactly the maximum input
// token length for the model.
// * @param truncate the truncate option to use.
// * @return this client.
// */
// public BedrockCohereEmbeddingClient withTruncate(CohereEmbeddingRequest.Truncate
// truncate) {
// this.truncate = truncate;
// return this;
// }
@Override
public List<Double> embed(Document document) {
return embed(document.getContent());
}
@Override
public EmbeddingResponse call(EmbeddingRequest request) {
Assert.notEmpty(request.getInstructions(), "At least one text is required!");
final BedrockCohereEmbeddingOptions optionsToUse = this.mergeOptions(request.getOptions());
var apiRequest = new CohereEmbeddingRequest(request.getInstructions(), optionsToUse.getInputType(),
optionsToUse.getTruncate());
CohereEmbeddingResponse apiResponse = this.embeddingApi.embedding(apiRequest);
var indexCounter = new AtomicInteger(0);
List<Embedding> embeddings = apiResponse.embeddings()
.stream()
.map(e -> new Embedding(e, indexCounter.getAndIncrement()))
.toList();
return new EmbeddingResponse(embeddings);
}
/**
* Merge the default and request options.
* @param requestOptions request options to merge.
* @return the merged options.
*/
BedrockCohereEmbeddingOptions mergeOptions(EmbeddingOptions requestOptions) {
BedrockCohereEmbeddingOptions options = (this.defaultOptions != null) ? this.defaultOptions
: BedrockCohereEmbeddingOptions.builder()
.withInputType(CohereEmbeddingRequest.InputType.SEARCH_DOCUMENT)
.withTruncate(CohereEmbeddingRequest.Truncate.NONE)
.build();
if (requestOptions != null && !EmbeddingOptions.EMPTY.equals(requestOptions)) {
options = ModelOptionsUtils.merge(requestOptions, options, BedrockCohereEmbeddingOptions.class);
}
return options;
}
}
| [
"org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals"
] | [((4971, 5016), 'org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals')] |
/*
* 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.azure.openai;
import java.util.ArrayList;
import java.util.List;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.models.EmbeddingItem;
import com.azure.ai.openai.models.Embeddings;
import com.azure.ai.openai.models.EmbeddingsOptions;
import com.azure.ai.openai.models.EmbeddingsUsage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.MetadataMode;
import org.springframework.ai.embedding.AbstractEmbeddingClient;
import org.springframework.ai.embedding.Embedding;
import org.springframework.ai.embedding.EmbeddingOptions;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.embedding.EmbeddingResponseMetadata;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.Assert;
public class AzureOpenAiEmbeddingClient extends AbstractEmbeddingClient {
private static final Logger logger = LoggerFactory.getLogger(AzureOpenAiEmbeddingClient.class);
private final OpenAIClient azureOpenAiClient;
private final AzureOpenAiEmbeddingOptions defaultOptions;
private final MetadataMode metadataMode;
public AzureOpenAiEmbeddingClient(OpenAIClient azureOpenAiClient) {
this(azureOpenAiClient, MetadataMode.EMBED);
}
public AzureOpenAiEmbeddingClient(OpenAIClient azureOpenAiClient, MetadataMode metadataMode) {
this(azureOpenAiClient, metadataMode,
AzureOpenAiEmbeddingOptions.builder().withDeploymentName("text-embedding-ada-002").build());
}
public AzureOpenAiEmbeddingClient(OpenAIClient azureOpenAiClient, MetadataMode metadataMode,
AzureOpenAiEmbeddingOptions options) {
Assert.notNull(azureOpenAiClient, "com.azure.ai.openai.OpenAIClient must not be null");
Assert.notNull(metadataMode, "Metadata mode must not be null");
Assert.notNull(options, "Options must not be null");
this.azureOpenAiClient = azureOpenAiClient;
this.metadataMode = metadataMode;
this.defaultOptions = options;
}
@Override
public List<Double> embed(Document document) {
logger.debug("Retrieving embeddings");
EmbeddingResponse response = this
.call(new EmbeddingRequest(List.of(document.getFormattedContent(this.metadataMode)), null));
logger.debug("Embeddings retrieved");
return response.getResults().stream().map(embedding -> embedding.getOutput()).flatMap(List::stream).toList();
}
@Override
public EmbeddingResponse call(EmbeddingRequest embeddingRequest) {
logger.debug("Retrieving embeddings");
EmbeddingsOptions azureOptions = toEmbeddingOptions(embeddingRequest);
Embeddings embeddings = this.azureOpenAiClient.getEmbeddings(azureOptions.getModel(), azureOptions);
logger.debug("Embeddings retrieved");
return generateEmbeddingResponse(embeddings);
}
/**
* Test access
*/
EmbeddingsOptions toEmbeddingOptions(EmbeddingRequest embeddingRequest) {
var azureOptions = new EmbeddingsOptions(embeddingRequest.getInstructions());
if (this.defaultOptions != null) {
azureOptions.setModel(this.defaultOptions.getDeploymentName());
azureOptions.setUser(this.defaultOptions.getUser());
}
if (embeddingRequest.getOptions() != null && !EmbeddingOptions.EMPTY.equals(embeddingRequest.getOptions())) {
azureOptions = ModelOptionsUtils.merge(embeddingRequest.getOptions(), azureOptions,
EmbeddingsOptions.class);
}
return azureOptions;
}
private EmbeddingResponse generateEmbeddingResponse(Embeddings embeddings) {
List<Embedding> data = generateEmbeddingList(embeddings.getData());
EmbeddingResponseMetadata metadata = generateMetadata(embeddings.getUsage());
return new EmbeddingResponse(data, metadata);
}
private List<Embedding> generateEmbeddingList(List<EmbeddingItem> nativeData) {
List<Embedding> data = new ArrayList<>();
for (EmbeddingItem nativeDatum : nativeData) {
List<Double> nativeDatumEmbedding = nativeDatum.getEmbedding();
int nativeIndex = nativeDatum.getPromptIndex();
Embedding embedding = new Embedding(nativeDatumEmbedding, nativeIndex);
data.add(embedding);
}
return data;
}
private EmbeddingResponseMetadata generateMetadata(EmbeddingsUsage embeddingsUsage) {
EmbeddingResponseMetadata metadata = new EmbeddingResponseMetadata();
// metadata.put("model", model);
metadata.put("prompt-tokens", embeddingsUsage.getPromptTokens());
metadata.put("total-tokens", embeddingsUsage.getTotalTokens());
return metadata;
}
public AzureOpenAiEmbeddingOptions getDefaultOptions() {
return this.defaultOptions;
}
}
| [
"org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals"
] | [((3890, 3950), 'org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals')] |
/*
* 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.bedrock.anthropic;
import java.util.List;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import reactor.core.publisher.Flux;
import org.springframework.ai.bedrock.MessageToPromptConverter;
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi;
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatRequest;
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatResponse;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.ModelOptionsUtils;
/**
* Java {@link ChatClient} and {@link StreamingChatClient} for the Bedrock Anthropic chat
* generative.
*
* @author Christian Tzolov
* @since 0.8.0
*/
public class BedrockAnthropicChatClient implements ChatClient, StreamingChatClient {
private final AnthropicChatBedrockApi anthropicChatApi;
private final AnthropicChatOptions defaultOptions;
public BedrockAnthropicChatClient(AnthropicChatBedrockApi chatApi) {
this(chatApi,
AnthropicChatOptions.builder()
.withTemperature(0.8f)
.withMaxTokensToSample(500)
.withTopK(10)
.withAnthropicVersion(AnthropicChatBedrockApi.DEFAULT_ANTHROPIC_VERSION)
.build());
}
public BedrockAnthropicChatClient(AnthropicChatBedrockApi chatApi, AnthropicChatOptions options) {
this.anthropicChatApi = chatApi;
this.defaultOptions = options;
}
@Override
public ChatResponse call(Prompt prompt) {
AnthropicChatRequest request = createRequest(prompt);
AnthropicChatResponse response = this.anthropicChatApi.chatCompletion(request);
return new ChatResponse(List.of(new Generation(response.completion())));
}
@Override
public Flux<ChatResponse> stream(Prompt prompt) {
AnthropicChatRequest request = createRequest(prompt);
Flux<AnthropicChatResponse> fluxResponse = this.anthropicChatApi.chatCompletionStream(request);
return fluxResponse.map(response -> {
String stopReason = response.stopReason() != null ? response.stopReason() : null;
var generation = new Generation(response.completion());
if (response.amazonBedrockInvocationMetrics() != null) {
generation = generation.withGenerationMetadata(
ChatGenerationMetadata.from(stopReason, response.amazonBedrockInvocationMetrics()));
}
return new ChatResponse(List.of(generation));
});
}
/**
* Accessible for testing.
*/
AnthropicChatRequest createRequest(Prompt prompt) {
// Related to: https://github.com/spring-projects/spring-ai/issues/404
final String promptValue = MessageToPromptConverter.create("\n").toPrompt(prompt.getInstructions());
AnthropicChatRequest request = AnthropicChatRequest.builder(promptValue).build();
if (this.defaultOptions != null) {
request = ModelOptionsUtils.merge(request, this.defaultOptions, AnthropicChatRequest.class);
}
if (prompt.getOptions() != null) {
if (prompt.getOptions() instanceof ChatOptions runtimeOptions) {
AnthropicChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions,
ChatOptions.class, AnthropicChatOptions.class);
request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, AnthropicChatRequest.class);
}
else {
throw new IllegalArgumentException("Prompt options are not of type ChatOptions: "
+ prompt.getOptions().getClass().getSimpleName());
}
}
return request;
}
}
| [
"org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatRequest.builder",
"org.springframework.ai.bedrock.MessageToPromptConverter.create"
] | [((3463, 3535), 'org.springframework.ai.bedrock.MessageToPromptConverter.create'), ((3571, 3620), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatRequest.builder')] |
/*
* 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.bedrock.anthropic3;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatResponse;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatStreamingResponse.StreamingType;
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.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Flux;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
* Java {@link ChatClient} 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 {
private final Anthropic3ChatBedrockApi anthropicChatApi;
private final Anthropic3ChatOptions defaultOptions;
public BedrockAnthropic3ChatClient(Anthropic3ChatBedrockApi chatApi) {
this(chatApi,
Anthropic3ChatOptions.builder()
.withTemperature(0.8f)
.withMaxTokens(500)
.withTopK(10)
.withAnthropicVersion(Anthropic3ChatBedrockApi.DEFAULT_ANTHROPIC_VERSION)
.build());
}
public BedrockAnthropic3ChatClient(Anthropic3ChatBedrockApi chatApi, Anthropic3ChatOptions options) {
this.anthropicChatApi = chatApi;
this.defaultOptions = options;
}
@Override
public ChatResponse call(Prompt prompt) {
AnthropicChatRequest request = createRequest(prompt);
AnthropicChatResponse response = this.anthropicChatApi.chatCompletion(request);
return new ChatResponse(List.of(new Generation(response.content().get(0).text())));
}
@Override
public Flux<ChatResponse> stream(Prompt prompt) {
AnthropicChatRequest request = createRequest(prompt);
Flux<Anthropic3ChatBedrockApi.AnthropicChatStreamingResponse> fluxResponse = this.anthropicChatApi
.chatCompletionStream(request);
AtomicReference<Integer> inputTokens = new AtomicReference<>(0);
return fluxResponse.map(response -> {
if (response.type() == StreamingType.MESSAGE_START) {
inputTokens.set(response.message().usage().inputTokens());
}
String content = response.type() == StreamingType.CONTENT_BLOCK_DELTA ? response.delta().text() : "";
var generation = new Generation(content);
if (response.type() == StreamingType.MESSAGE_DELTA) {
generation = generation.withGenerationMetadata(ChatGenerationMetadata
.from(response.delta().stopReason(), new Anthropic3ChatBedrockApi.AnthropicUsage(inputTokens.get(),
response.usage().outputTokens())));
}
return new ChatResponse(List.of(generation));
});
}
/**
* Accessible for testing.
*/
AnthropicChatRequest createRequest(Prompt prompt) {
AnthropicChatRequest request = AnthropicChatRequest.builder(toAnthropicMessages(prompt))
.withSystem(toAnthropicSystemContext(prompt))
.build();
if (this.defaultOptions != null) {
request = ModelOptionsUtils.merge(request, this.defaultOptions, AnthropicChatRequest.class);
}
if (prompt.getOptions() != null) {
if (prompt.getOptions() instanceof ChatOptions runtimeOptions) {
Anthropic3ChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions,
ChatOptions.class, Anthropic3ChatOptions.class);
request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, AnthropicChatRequest.class);
}
else {
throw new IllegalArgumentException("Prompt options are not of type ChatOptions: "
+ prompt.getOptions().getClass().getSimpleName());
}
}
return request;
}
/**
* Extracts system context from prompt.
* @param prompt The prompt.
* @return The system context.
*/
private String toAnthropicSystemContext(Prompt prompt) {
return prompt.getInstructions()
.stream()
.filter(m -> m.getMessageType() == MessageType.SYSTEM)
.map(Message::getContent)
.collect(Collectors.joining(System.lineSeparator()));
}
/**
* Extracts list of messages from prompt.
* @param prompt The prompt.
* @return The list of {@link ChatCompletionMessage}.
*/
private List<ChatCompletionMessage> toAnthropicMessages(Prompt prompt) {
return prompt.getInstructions()
.stream()
.filter(m -> m.getMessageType() == MessageType.USER || m.getMessageType() == MessageType.ASSISTANT)
.map(message -> {
List<MediaContent> contents = new ArrayList<>(List.of(new MediaContent(message.getContent())));
if (!CollectionUtils.isEmpty(message.getMedia())) {
List<MediaContent> mediaContent = message.getMedia()
.stream()
.map(media -> new MediaContent(media.getMimeType().toString(),
this.fromMediaData(media.getData())))
.toList();
contents.addAll(mediaContent);
}
return new ChatCompletionMessage(contents, Role.valueOf(message.getMessageType().name()));
})
.toList();
}
private String fromMediaData(Object mediaData) {
if (mediaData instanceof byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
else if (mediaData instanceof String text) {
return text;
}
else {
throw new IllegalArgumentException("Unsupported media data type: " + mediaData.getClass().getSimpleName());
}
}
}
| [
"org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder"
] | [((4413, 4531), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((4413, 4519), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((6595, 6636), 'java.util.Base64.getEncoder')] |
package com.mycompany.myapp.web.rest.chat;
import com.mycompany.myapp.service.llm.LlamaCppChatClient;
import com.mycompany.myapp.service.llm.LlamaPrompt;
import com.mycompany.myapp.service.llm.dto.*;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Generated;
import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2024-01-08T22:40:49.631444+09:00[Asia/Tokyo]")
@RestController
@RequestMapping("${openapi.my-llm-app.base-path:/v1}")
public class FluxChatApiController implements FluxChatApi {
private final LlamaCppChatClient chatClient;
private final VectorStore vectorStore;
@Autowired
public FluxChatApiController(LlamaCppChatClient chatClient, VectorStore vectorStore) {
this.chatClient = chatClient;
this.vectorStore = vectorStore;
}
@Override
public Flux<CreateChatCompletionStreamResponse> createChatCompletion(
@Parameter(name = "CreateChatCompletionRequest", description = "", required = true) @Valid @RequestBody Mono<
CreateChatCompletionRequest
> createChatCompletionRequestMono,
@Parameter(hidden = true) final ServerWebExchange exchange
) {
return createChatCompletionRequestMono.flatMapMany(createChatCompletionRequest -> {
var messages = createChatCompletionRequest.getMessages();
var prompt = new LlamaPrompt(
messages
.stream()
.map(message ->
(Message) switch (message) {
case ChatCompletionRequestSystemMessage systemMessage -> new SystemMessage(systemMessage.getContent());
case ChatCompletionRequestUserMessage userMessage -> new UserMessage(userMessage.getContent());
case ChatCompletionRequestAssistantMessage assistantMessage -> new AssistantMessage(
assistantMessage.getContent()
);
case null, default -> throw new RuntimeException("Unknown message type");
}
)
.toList()
);
// search related contents from vector store
// Here, as a provisional behavior, RAG works when the "gpt-4k" model is used.
if (createChatCompletionRequest.getModel().equals(CreateChatCompletionRequest.ModelEnum._4)) {
// Find the last UserMessage in the prompt's messages
var instructions = prompt.getInstructions();
UserMessage lastUserMessage = null;
for (int i = instructions.size() - 1; i >= 0; i--) {
if (instructions.get(i) instanceof UserMessage) {
lastUserMessage = (UserMessage) instructions.get(i);
List<Document> results = vectorStore.similaritySearch(
SearchRequest.query(lastUserMessage.getContent()).withTopK(5)
);
String references = results.stream().map(Document::getContent).collect(Collectors.joining("\n"));
// replace last UserMessage in prompt's messages with template message with the result and UserMessage
var newInstructions = new ArrayList<>(instructions); // Mutable copy of instructions
String newMessage =
"Please answer the questions in the 'UserMessage'. Find the information you need to answer in the 'References' section. If you do not have the information, please answer with 'I don't know'.\n" +
"UserMessage: " +
lastUserMessage.getContent() +
"\n" +
"References: " +
references;
System.out.println("newMessage: " + newMessage);
newInstructions.set(i, new UserMessage(newMessage)); // Replace last UserMessage
// Create a new LlamaPrompt with the updated instructions
prompt = new LlamaPrompt(newInstructions);
break;
}
}
}
Flux<ChatResponse> chatResponseFlux = chatClient.stream(prompt);
var date = System.currentTimeMillis();
return chatResponseFlux
.map(chatResponse -> {
var responseDelta = new ChatCompletionStreamResponseDelta()
.content(chatResponse.getResult().getOutput().getContent())
.role(ChatCompletionStreamResponseDelta.RoleEnum.ASSISTANT);
var choices = new CreateChatCompletionStreamResponseChoicesInner().index(0L).finishReason(null).delta(responseDelta);
return new CreateChatCompletionStreamResponse(
"chatcmpl-123",
List.of(choices),
date,
"gpt-3.5-turbo",
CreateChatCompletionStreamResponse.ObjectEnum.CHAT_COMPLETION_CHUNK
);
})
.concatWithValues(
new CreateChatCompletionStreamResponse(
"chatcmpl-123",
List.of(
new CreateChatCompletionStreamResponseChoicesInner()
.index(0L)
.finishReason(CreateChatCompletionStreamResponseChoicesInner.FinishReasonEnum.STOP)
.delta(new ChatCompletionStreamResponseDelta())
),
date,
"gpt-3.5-turbo",
CreateChatCompletionStreamResponse.ObjectEnum.CHAT_COMPLETION_CHUNK
)
);
});
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((3900, 3961), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package dev.gababartnicka.springaidemo.ai;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
@Log4j2
@RequiredArgsConstructor
public class AiService {
@Value("${dev.gababartnicka.ask_ai.openai.api-key}")
private String apiKey;
private OpenAiChatClient chatClient;
@PostConstruct
public void init() {
log.info("AiService initialization started");
var openAiApi = new OpenAiApi(apiKey);
chatClient = new OpenAiChatClient(openAiApi)
.withDefaultOptions(OpenAiChatOptions.builder()
.withModel("gpt-4")
// .withTemperature(0.4)
// .withMaxTokens(200)
.build());
log.info("AiService initialized successfully");
}
public ReplyDto ask(QuestionDto questionDto) {
final var response = chatClient.call(
new Prompt(questionDto.question()));
log.info(response.getResult().toString());
return new ReplyDto(response.getResult().getOutput().getContent());
}
}
| [
"org.springframework.ai.openai.OpenAiChatOptions.builder"
] | [((909, 1107), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((909, 980), 'org.springframework.ai.openai.OpenAiChatOptions.builder')] |
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.ollama.rag;
import org.springframework.ai.document.MetadataMode;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.OpenAiEmbeddingOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
@Profile("ollama-rag")
@Configuration
public class OllamaRagEmbeddingClientConfig {
@Value("${ai-client.openai.api-key}")
private String openaiApiKey;
@Bean
@Primary
OpenAiEmbeddingClient openAiEmbeddingClient() {
var openAiApi = new OpenAiApi(openaiApiKey);
return new OpenAiEmbeddingClient(
openAiApi,
MetadataMode.EMBED,
OpenAiEmbeddingOptions.builder().withModel(OpenAiApi.DEFAULT_EMBEDDING_MODEL).build(),
RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
}
| [
"org.springframework.ai.openai.OpenAiEmbeddingOptions.builder"
] | [((1046, 1131), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((1046, 1123), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder')] |
package com.ai.springdemo.aispringdemo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.JsonReader;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
@Service
public class DataLoadingService {
private static final Logger logger = LoggerFactory.getLogger(DataLoadingService.class);
@Value("classpath:/data/tr_technology_radar_vol_29_en.pdf")
private Resource documentResource;
private final VectorStore vectorStore;
private final JdbcTemplate jdbcTemplate;
@Autowired
public DataLoadingService(VectorStore vectorStore,
JdbcTemplate jdbcTemplate) {
Assert.notNull(vectorStore, "VectorStore must not be null.");
this.vectorStore = vectorStore;
this.jdbcTemplate = jdbcTemplate;
}
public int count() {
String sql = "SELECT COUNT(*) FROM vector_store";
Integer i = jdbcTemplate.queryForObject(sql, Integer.class);
return i != null ? i : 0;
}
public void delete() {
String sql = "DELETE FROM vector_store";
jdbcTemplate.update(sql);
}
public void load() {
DocumentReader reader = null;
if (this.documentResource.getFilename() != null) {
if (this.documentResource.getFilename().endsWith(".pdf")) {
logger.info("Parsing PDF document");
reader = new PagePdfDocumentReader(
this.documentResource,
PdfDocumentReaderConfig.builder()
.withPageExtractedTextFormatter(ExtractedTextFormatter.builder()
.withNumberOfBottomTextLinesToDelete(3)
.withNumberOfTopPagesToSkipBeforeDelete(1)
.build())
.withPagesPerDocument(1)
.build());
} else if (this.documentResource.getFilename().endsWith(".txt")) {
reader = new TextReader(this.documentResource);
} else if (this.documentResource.getFilename().endsWith(".json")) {
reader = new JsonReader((org.springframework.core.io.Resource) this.documentResource);
}
}
if (reader != null) {
var textSplitter = new TokenTextSplitter();
logger.info("Parsing document, splitting, creating embeddings and storing in vector store... this will take a while.");
this.vectorStore.accept(
textSplitter.apply(
reader.get()));
logger.info("Done parsing document, splitting, creating embeddings and storing in vector store");
} else {
throw new RuntimeException("No reader found for document");
}
}
}
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder",
"org.springframework.ai.reader.ExtractedTextFormatter.builder"
] | [((2187, 2628), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2187, 2587), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2187, 2530), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2285, 2529), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((2285, 2480), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((2285, 2397), 'org.springframework.ai.reader.ExtractedTextFormatter.builder')] |
/*
* 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.autoconfigure.openai;
import org.springframework.ai.openai.OpenAiAudioSpeechOptions;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Configuration properties for OpenAI audio speech.
*
* Default values for required options are model = tts_1, response format = mp3, voice =
* alloy, and speed = 1.
*
* @author Ahmed Yousri
*/
@ConfigurationProperties(OpenAiAudioSpeechProperties.CONFIG_PREFIX)
public class OpenAiAudioSpeechProperties extends OpenAiParentProperties {
public static final String CONFIG_PREFIX = "spring.ai.openai.audio.speech";
public static final String DEFAULT_SPEECH_MODEL = OpenAiAudioApi.TtsModel.TTS_1.getValue();
private static final Float SPEED = 1.0f;
private static final OpenAiAudioApi.SpeechRequest.Voice VOICE = OpenAiAudioApi.SpeechRequest.Voice.ALLOY;
private static final OpenAiAudioApi.SpeechRequest.AudioResponseFormat DEFAULT_RESPONSE_FORMAT = OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3;
@NestedConfigurationProperty
private OpenAiAudioSpeechOptions options = OpenAiAudioSpeechOptions.builder()
.withModel(DEFAULT_SPEECH_MODEL)
.withResponseFormat(DEFAULT_RESPONSE_FORMAT)
.withVoice(VOICE)
.withSpeed(SPEED)
.build();
public OpenAiAudioSpeechOptions getOptions() {
return options;
}
public void setOptions(OpenAiAudioSpeechOptions options) {
this.options = options;
}
}
| [
"org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder",
"org.springframework.ai.openai.api.OpenAiAudioApi.TtsModel.TTS_1.getValue"
] | [((1428, 1468), 'org.springframework.ai.openai.api.OpenAiAudioApi.TtsModel.TTS_1.getValue'), ((1848, 2015), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((1848, 2004), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((1848, 1984), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((1848, 1964), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((1848, 1917), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder')] |
package com.example.fitness;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.modulith.Modulithic;
import java.util.Map;
@Slf4j
@SpringBootApplication
@RequiredArgsConstructor
@Modulithic(sharedModules = "commons")
public class FitnessApplication {
public static void main(String[] args) {
if (System.getenv("spring.ai.openai.api-key") != null) {
log.debug("Starting with AI support");
new SpringApplicationBuilder(FitnessApplication.class)
.profiles("ai")
.run(args);
} else {
log.debug("Starting without AI support");
new SpringApplicationBuilder(FitnessApplication.class)
.properties(Map.of("spring.autoconfigure.exclude", OpenAiAutoConfiguration.class.getName()))
.run(args);
}
}
}
| [
"org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration.class.getName"
] | [((1020, 1059), 'org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration.class.getName')] |
/*
* 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.autoconfigure.azure.openai;
import org.springframework.ai.azure.openai.AzureOpenAiChatOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@ConfigurationProperties(AzureOpenAiChatProperties.CONFIG_PREFIX)
public class AzureOpenAiChatProperties {
public static final String CONFIG_PREFIX = "spring.ai.azure.openai.chat";
public static final String DEFAULT_DEPLOYMENT_NAME = "gpt-35-turbo";
private static final Double DEFAULT_TEMPERATURE = 0.7;
/**
* Enable Azure OpenAI chat client.
*/
private boolean enabled = true;
@NestedConfigurationProperty
private AzureOpenAiChatOptions options = AzureOpenAiChatOptions.builder()
.withDeploymentName(DEFAULT_DEPLOYMENT_NAME)
.withTemperature(DEFAULT_TEMPERATURE.floatValue())
.build();
public AzureOpenAiChatOptions getOptions() {
return this.options;
}
public void setOptions(AzureOpenAiChatOptions options) {
this.options = options;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| [
"org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder"
] | [((1368, 1511), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((1368, 1500), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((1368, 1447), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder')] |
/*
* 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.autoconfigure.stabilityai;
import org.springframework.ai.stabilityai.api.StabilityAiImageOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* @author Mark Pollack
* @author Christian Tzolov
* @since 0.8.0
*/
@ConfigurationProperties(StabilityAiImageProperties.CONFIG_PREFIX)
public class StabilityAiImageProperties extends StabilityAiParentProperties {
public static final String CONFIG_PREFIX = "spring.ai.stabilityai.image";
/**
* Enable Stability Image client.
*/
private boolean enabled = true;
@NestedConfigurationProperty
private StabilityAiImageOptions options = StabilityAiImageOptions.builder().build(); // stable-diffusion-v1-6
// is
// default
// model
public StabilityAiImageOptions getOptions() {
return this.options;
}
public void setOptions(StabilityAiImageOptions options) {
this.options = options;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| [
"org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder"
] | [((1356, 1397), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder')] |
/*
* 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.autoconfigure.bedrock.titan;
import org.springframework.ai.bedrock.titan.BedrockTitanChatOptions;
import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Bedrock Titan Chat autoconfiguration properties.
*
* @author Christian Tzolov
* @since 0.8.0
*/
@ConfigurationProperties(BedrockTitanChatProperties.CONFIG_PREFIX)
public class BedrockTitanChatProperties {
public static final String CONFIG_PREFIX = "spring.ai.bedrock.titan.chat";
/**
* Enable Bedrock Titan Chat Client. False by default.
*/
private boolean enabled = false;
/**
* Bedrock Titan Chat generative name. Defaults to 'amazon.titan-text-express-v1'.
*/
private String model = TitanChatModel.TITAN_TEXT_EXPRESS_V1.id();
@NestedConfigurationProperty
private BedrockTitanChatOptions options = BedrockTitanChatOptions.builder().withTemperature(0.7f).build();
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public BedrockTitanChatOptions getOptions() {
return options;
}
public void setOptions(BedrockTitanChatOptions options) {
this.options = options;
}
}
| [
"org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id",
"org.springframework.ai.bedrock.titan.BedrockTitanChatOptions.builder"
] | [((1503, 1544), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id'), ((1620, 1683), 'org.springframework.ai.bedrock.titan.BedrockTitanChatOptions.builder'), ((1620, 1675), 'org.springframework.ai.bedrock.titan.BedrockTitanChatOptions.builder')] |
package delhijug.jugdemo;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.transformer.splitter.TextSplitter;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.PgVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@SpringBootApplication
public class JugdemoApplication {
public static void main(String[] args) {
SpringApplication.run(JugdemoApplication.class, args);
}
@Bean
VectorStore vectorStore(EmbeddingClient ec, JdbcTemplate jt){
return new PgVectorStore(jt, ec);
}
static void init(VectorStore vectorStore, JdbcTemplate jdbcTemplate, Resource pdf){
var config = PdfDocumentReaderConfig.builder().
withPageExtractedTextFormatter(new ExtractedTextFormatter.Builder()
.withNumberOfBottomTextLinesToDelete(3)
.withNumberOfTopPagesToSkipBeforeDelete(1)
.build()
)
.withPagesPerDocument(1)
.build();
var pdfReader = new PagePdfDocumentReader(pdf, config);
TextSplitter textSplitter = new TokenTextSplitter();
vectorStore.accept(textSplitter.apply(pdfReader.get()));
}
@Bean
ApplicationRunner demo (
ChatBot chatBot,
VectorStore vectorStore,
JdbcTemplate template,
@Value("file:///Users/vikmalik/Downloads/bin/jugdemo/medicaid-wa-faqs.pdf") Resource pdf
){
return new ApplicationRunner() {
@Override
public void run(ApplicationArguments args) throws Exception {
init(vectorStore, template, pdf);
var aiResponse = chatBot.basicChat("Hello, Who are you?");
System.out.println(aiResponse);
aiResponse = chatBot.animalChat("Cat");
System.out.println(aiResponse);
aiResponse = chatBot.chat("Who’s who on Carina?");
System.out.println(aiResponse);
}
};
}
}
@Component
class ChatBot {
private final ChatClient aiChatClient;
private final VectorStore vectorStore;
ChatBot(ChatClient aiChatClient, VectorStore vectorStore){
this.aiChatClient = aiChatClient;
this.vectorStore = vectorStore;
}
private final String animalTemplate = """
You are assistant expert in animals. You give facts about the animals.
Tell me more about {animal_name}
Give response in json
""";
private final String template = """
You're assisting with questions about services offered by Carina.
Carina is a two-sided healthcare marketplace focusing on home care aides (caregivers)
and their Medicaid in-home care clients (adults and children with developmental disabilities and low income elderly population).
Carina's mission is to build online tools to bring good jobs to care workers, so care workers can provide the
best possible care for those who need it.
Use the information from the DOCUMENTS section to provide accurate answers but act as if you knew this information innately.
If unsure, simply state that you don't know.
DOCUMENTS:
{documents}
""";
public String chat(String message){
var listOfDocuments = this.vectorStore.similaritySearch(message);
var documents = listOfDocuments.stream()
.map(Document::getContent)
.collect(Collectors.joining(System.lineSeparator()));
var systemMessage = new SystemPromptTemplate(this.template)
.createMessage(Map.of("documents", documents));
var userMessage = new UserMessage(message);
var prompt = new Prompt(List.of(systemMessage, userMessage));
var aiResponse = aiChatClient.call(prompt);
return aiResponse.getResult().getOutput().getContent();
}
public String animalChat(String message){
var systemMessage = new SystemPromptTemplate(this.animalTemplate)
.createMessage(Map.of("animal_name", message));
var prompt = new Prompt(List.of(systemMessage));
var aiResponse = aiChatClient.call(prompt);
return aiResponse.getResult().getOutput().getContent();
}
public String basicChat(String message){
return aiChatClient.call(message);
}
}
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder"
] | [((1732, 1996), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1732, 1983), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1732, 1954), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')] |
package habuma.springaifunctions;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Description;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;
import java.util.List;
import java.util.function.Function;
@SpringBootApplication
public class SpringAiFunctionsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAiFunctionsApplication.class, args);
}
@Bean
@Description("Get the wait time for a Disneyland attraction in minutes")
public Function<WaitTimeService.Request, WaitTimeService.Response> getWaitTime() {
return new WaitTimeService();
}
@Bean
RouterFunction<ServerResponse> routes(ChatClient chatClient) {
return RouterFunctions.route()
.GET("/waitTime", req -> {
String ride = req.param("ride").orElse("Space Mountain");
UserMessage userMessage =
new UserMessage("What's the wait time for " + ride + "?");
ChatResponse response = chatClient.call(new Prompt(
List.of(userMessage),
OpenAiChatOptions.builder()
.withFunction("getWaitTime")
.build()));
return ServerResponse
.ok()
.body(response.getResult().getOutput().getContent());
})
.build();
}
}
| [
"org.springframework.ai.openai.OpenAiChatOptions.builder"
] | [((1336, 2053), 'org.springframework.web.servlet.function.RouterFunctions.route'), ((1336, 2032), 'org.springframework.web.servlet.function.RouterFunctions.route'), ((1738, 1867), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1738, 1826), 'org.springframework.ai.openai.OpenAiChatOptions.builder')] |
package com.redis.demo.spring.ai;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
public class RagService {
@Value("classpath:/prompts/system-qa.st")
private Resource systemBeerPrompt;
@Value("${topk:10}")
private int topK;
private final ChatClient client;
private final VectorStore store;
public RagService(ChatClient client, VectorStore store) {
this.client = client;
this.store = store;
}
// tag::retrieve[]
public Generation retrieve(String message) {
SearchRequest request = SearchRequest.query(message).withTopK(topK);
// Query Redis for the top K documents most relevant to the input message
List<Document> docs = store.similaritySearch(request);
Message systemMessage = getSystemMessage(docs);
UserMessage userMessage = new UserMessage(message);
// Assemble the complete prompt using a template
Prompt prompt = new Prompt(List.of(systemMessage, userMessage));
// Call the autowired chat client with the prompt
ChatResponse response = client.call(prompt);
return response.getResult();
}
// end::retrieve[]
private Message getSystemMessage(List<Document> similarDocuments) {
String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining("\n"));
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemBeerPrompt);
return systemPromptTemplate.createMessage(Map.of("documents", documents));
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1170, 1213), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package com.brianeno.springai.rag.dataloader;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.JsonReader;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
@Service
public class DataLoadingService {
private static final Logger logger = LoggerFactory.getLogger(DataLoadingService.class);
@Value("classpath:/data/2023-infoq-trends-reports-emag-1703183112474.pdf")
private Resource documentResource;
private final VectorStore vectorStore;
private final JdbcTemplate jdbcTemplate;
@Autowired
public DataLoadingService(VectorStore vectorStore,
JdbcTemplate jdbcTemplate) {
Assert.notNull(vectorStore, "VectorStore must not be null.");
this.vectorStore = vectorStore;
this.jdbcTemplate = jdbcTemplate;
}
public int count() {
String sql = "SELECT COUNT(*) FROM vector_store";
return jdbcTemplate.queryForObject(sql, Integer.class);
}
public void delete() {
String sql = "DELETE FROM vector_store";
jdbcTemplate.update(sql);
}
public void load() {
DocumentReader reader = null;
if (this.documentResource.getFilename() != null) {
if (this.documentResource.getFilename().endsWith(".pdf")) {
logger.info("Parsing PDF document");
reader = new PagePdfDocumentReader(
this.documentResource,
PdfDocumentReaderConfig.builder()
.withPageExtractedTextFormatter(ExtractedTextFormatter.builder()
.withNumberOfBottomTextLinesToDelete(3)
.withNumberOfTopPagesToSkipBeforeDelete(1)
.build())
.withPagesPerDocument(1)
.build());
} else if (this.documentResource.getFilename().endsWith(".txt")) {
reader = new TextReader(this.documentResource);
} else if (this.documentResource.getFilename().endsWith(".json")) {
reader = new JsonReader(this.documentResource);
}
}
if (reader != null) {
var textSplitter = new TokenTextSplitter();
logger.info("Parsing document, splitting, creating embeddings and storing in vector store... this will take a while.");
this.vectorStore.accept(
textSplitter.apply(
reader.get()));
logger.info("Done parsing document, splitting, creating embeddings and storing in vector store");
} else {
throw new RuntimeException("No reader found for document");
}
}
}
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder",
"org.springframework.ai.reader.ExtractedTextFormatter.builder"
] | [((2186, 2567), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2186, 2534), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2186, 2485), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2276, 2484), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((2276, 2447), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((2276, 2376), 'org.springframework.ai.reader.ExtractedTextFormatter.builder')] |
package com.example.springbootaiintegration.services;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class OpenApiService extends AbstractApiService{
private Integer TOKENS = 250;
private final OpenAiApi aiApi = new OpenAiApi(System.getenv("OPENAI_API_KEY"));
@Autowired
OpenApiService(SessionService sessionService) {
this.sessionService = sessionService;
this.model = "gpt-3.5-turbo";
makeClient();
}
@Override
void initializeClient(Map<String, Object> request) {
var makeNew = false;
String requestModel = (String) request.get("model");
Integer requestTokens = (Integer) request.get("tokens");
if (requestModel != null && !requestModel.trim().isEmpty() && !this.model.equals(requestModel)) {
this.model = requestModel.trim();
makeNew = true;
}
if (requestTokens != null && !this.TOKENS.equals(requestTokens)) {
this.TOKENS = requestTokens;
makeNew = true;
}
if (makeNew) {
makeClient();
}
}
@Override
void makeClient() {
this.client = new OpenAiChatClient(aiApi)
.withDefaultOptions(OpenAiChatOptions.builder()
.withModel(this.model)
.withTemperature(0.4F)
.withMaxTokens(TOKENS)
.withN(1)
.build());
}
}
| [
"org.springframework.ai.openai.OpenAiChatOptions.builder"
] | [((1482, 1862), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1482, 1800), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1482, 1737), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1482, 1661), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1482, 1585), 'org.springframework.ai.openai.OpenAiChatOptions.builder')] |
package com.example.springairag;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/ask")
public class AskController {
private final ChatClient aiClient;
private final VectorStore vectorStore;
@Value("classpath:/rag-prompt-template.st")
private Resource ragPromptTemplate;
public AskController(ChatClient aiClient, VectorStore vectorStore) {
this.aiClient = aiClient;
this.vectorStore = vectorStore;
}
@PostMapping
public Answer ask(@RequestBody Question question) {
List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(question.question()).withTopK(2));
List<String> contentList = similarDocuments.stream().map(Document::getContent).toList();
PromptTemplate promptTemplate = new PromptTemplate(ragPromptTemplate);
Map<String, Object> promptParameters = new HashMap<>();
promptParameters.put("input", question.question());
promptParameters.put("documents", String.join("\n", contentList));
Prompt prompt = promptTemplate.create(promptParameters);
ChatResponse response = aiClient.call(prompt);
return new Answer(response.getResult().getOutput().getContent());
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1363, 1415), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package com.surl.studyurl.domain.home.controller;
import org.springframework.ai.image.Image;
import org.springframework.ai.image.ImageClient;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.openai.OpenAiImageOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ImageGeneratorController {
@Autowired
private ImageClient openAiImageClient;
@GetMapping("/image")
public Image getImage(@RequestParam String imagePrompt){
ImageResponse response = openAiImageClient.call(
new ImagePrompt(imagePrompt,
OpenAiImageOptions.builder()
.withQuality("hd")
.withN(4)
.withHeight(1024)
.withWidth(1024).build())
);
return response.getResult().getOutput();
}
} | [
"org.springframework.ai.openai.OpenAiImageOptions.builder"
] | [((877, 1105), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((877, 1097), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((877, 1048), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((877, 998), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((877, 956), 'org.springframework.ai.openai.OpenAiImageOptions.builder')] |
package com.watsonx.ai;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.watsonx.WatsonxAiChatClient;
import org.springframework.ai.watsonx.WatsonxAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RestController
public class WatsonxController {
private final WatsonxAiChatClient chat;
@Autowired
public WatsonxController(WatsonxAiChatClient chat) {
this.chat = chat;
}
@GetMapping("/hi")
public String sayHi() {
var options = WatsonxAiChatOptions.builder().withRandomSeed(1).withModel("google/flan-ul2").withDecodingMethod("sample").build();
var prompt = new Prompt(new SystemMessage("say hi"), options);
var results = this.chat.call(prompt);
return results.getResult().getOutput().getContent();
}
@GetMapping(path = "/hi/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public ResponseEntity<SseEmitter> sayHiStream() {
var options = WatsonxAiChatOptions.builder().withRandomSeed(1).withModel("google/flan-ul2").withDecodingMethod("sample").build();
var prompt = new Prompt(new SystemMessage("say hi"), options);
var results = this.chat.stream(prompt);
SseEmitter emitter = new SseEmitter();
results.subscribe(
data -> {
try {
emitter.send(data.getResult().getOutput().getContent(), MediaType.TEXT_PLAIN);
} catch (Exception e) {
emitter.completeWithError(e);
}
},
emitter::completeWithError,
emitter::complete
);
return new ResponseEntity<>(emitter, HttpStatus.OK);
}
}
| [
"org.springframework.ai.watsonx.WatsonxAiChatOptions.builder"
] | [((921, 1035), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((921, 1027), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((921, 998), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((921, 969), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1381, 1495), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1381, 1487), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1381, 1458), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1381, 1429), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder')] |
/*
* 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.vectorstore.azure;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.azure.core.util.Context;
import com.azure.search.documents.SearchClient;
import com.azure.search.documents.SearchDocument;
import com.azure.search.documents.indexes.SearchIndexClient;
import com.azure.search.documents.indexes.models.HnswAlgorithmConfiguration;
import com.azure.search.documents.indexes.models.HnswParameters;
import com.azure.search.documents.indexes.models.SearchField;
import com.azure.search.documents.indexes.models.SearchFieldDataType;
import com.azure.search.documents.indexes.models.SearchIndex;
import com.azure.search.documents.indexes.models.VectorSearch;
import com.azure.search.documents.indexes.models.VectorSearchAlgorithmMetric;
import com.azure.search.documents.indexes.models.VectorSearchProfile;
import com.azure.search.documents.models.IndexDocumentsResult;
import com.azure.search.documents.models.IndexingResult;
import com.azure.search.documents.models.SearchOptions;
import com.azure.search.documents.models.VectorSearchOptions;
import com.azure.search.documents.models.VectorizedQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.filter.FilterExpressionConverter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* Uses Azure Cognitive Search as a backing vector store. Documents can be preloaded into
* a Cognitive Search index and managed via Azure tools or added and managed through this
* VectorStore. The underlying index is configured in the provided Azure
* SearchIndexClient.
*
* @author Greg Meyer
* @author Xiangyang Yu
* @author Christian Tzolov
*/
public class AzureVectorStore implements VectorStore, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(AzureVectorStore.class);
private static final String SPRING_AI_VECTOR_CONFIG = "spring-ai-vector-config";
private static final String SPRING_AI_VECTOR_PROFILE = "spring-ai-vector-profile";
public static final String DEFAULT_INDEX_NAME = "spring_ai_azure_vector_store";
private static final String ID_FIELD_NAME = "id";
private static final String CONTENT_FIELD_NAME = "content";
private static final String EMBEDDING_FIELD_NAME = "embedding";
private static final String METADATA_FIELD_NAME = "metadata";
private static final String DISTANCE_METADATA_FIELD_NAME = "distance";
private static final int DEFAULT_TOP_K = 4;
private static final Double DEFAULT_SIMILARITY_THRESHOLD = 0.0;
private static final String METADATA_FIELD_PREFIX = "meta_";
private final SearchIndexClient searchIndexClient;
private final EmbeddingClient embeddingClient;
private SearchClient searchClient;
private final FilterExpressionConverter filterExpressionConverter;
private int defaultTopK = DEFAULT_TOP_K;
private Double defaultSimilarityThreshold = DEFAULT_SIMILARITY_THRESHOLD;
private String indexName = DEFAULT_INDEX_NAME;
/**
* List of metadata fields (as field name and type) that can be used in similarity
* search query filter expressions. The {@link Document#getMetadata()} can contain
* arbitrary number of metadata entries, but only the fields listed here can be used
* in the search filter expressions.
*
* If new entries are added ot the filterMetadataFields the affected documents must be
* (re)updated.
*/
private final List<MetadataField> filterMetadataFields;
public record MetadataField(String name, SearchFieldDataType fieldType) {
public static MetadataField text(String name) {
return new MetadataField(name, SearchFieldDataType.STRING);
}
public static MetadataField int32(String name) {
return new MetadataField(name, SearchFieldDataType.INT32);
}
public static MetadataField int64(String name) {
return new MetadataField(name, SearchFieldDataType.INT64);
}
public static MetadataField decimal(String name) {
return new MetadataField(name, SearchFieldDataType.DOUBLE);
}
public static MetadataField bool(String name) {
return new MetadataField(name, SearchFieldDataType.BOOLEAN);
}
public static MetadataField date(String name) {
return new MetadataField(name, SearchFieldDataType.DATE_TIME_OFFSET);
}
}
/**
* Constructs a new AzureCognitiveSearchVectorStore.
* @param searchIndexClient A pre-configured Azure {@link SearchIndexClient} that CRUD
* for Azure search indexes and factory for {@link SearchClient}.
* @param embeddingClient The client for embedding operations.
*/
public AzureVectorStore(SearchIndexClient searchIndexClient, EmbeddingClient embeddingClient) {
this(searchIndexClient, embeddingClient, List.of());
}
/**
* Constructs a new AzureCognitiveSearchVectorStore.
* @param searchIndexClient A pre-configured Azure {@link SearchIndexClient} that CRUD
* for Azure search indexes and factory for {@link SearchClient}.
* @param embeddingClient The client for embedding operations.
* @param filterMetadataFields List of metadata fields (as field name and type) that
* can be used in similarity search query filter expressions.
*/
public AzureVectorStore(SearchIndexClient searchIndexClient, EmbeddingClient embeddingClient,
List<MetadataField> filterMetadataFields) {
Assert.notNull(embeddingClient, "The embedding client can not be null.");
Assert.notNull(searchIndexClient, "The search index client can not be null.");
Assert.notNull(filterMetadataFields, "The filterMetadataFields can not be null.");
this.searchIndexClient = searchIndexClient;
this.embeddingClient = embeddingClient;
this.filterMetadataFields = filterMetadataFields;
this.filterExpressionConverter = new AzureAiSearchFilterExpressionConverter(filterMetadataFields);
}
/**
* Change the Index Name.
* @param indexName The Azure VectorStore index name to use.
*/
public void setIndexName(String indexName) {
Assert.hasText(indexName, "The index name can not be empty.");
this.indexName = indexName;
}
/**
* Sets the a default maximum number of similar documents returned.
* @param topK The default maximum number of similar documents returned.
*/
public void setDefaultTopK(int topK) {
Assert.isTrue(topK >= 0, "The topK should be positive value.");
this.defaultTopK = topK;
}
/**
* Sets the a default similarity threshold for returned documents.
* @param similarityThreshold The a default similarity threshold for returned
* documents.
*/
public void setDefaultSimilarityThreshold(Double similarityThreshold) {
Assert.isTrue(similarityThreshold >= 0.0 && similarityThreshold <= 1.0,
"The similarity threshold must be in range [0.0:1.00].");
this.defaultSimilarityThreshold = similarityThreshold;
}
@Override
public void add(List<Document> documents) {
Assert.notNull(documents, "The document list should not be null.");
if (CollectionUtils.isEmpty(documents)) {
return; // nothing to do;
}
final var searchDocuments = documents.stream().map(document -> {
final var embeddings = this.embeddingClient.embed(document);
SearchDocument searchDocument = new SearchDocument();
searchDocument.put(ID_FIELD_NAME, document.getId());
searchDocument.put(EMBEDDING_FIELD_NAME, embeddings);
searchDocument.put(CONTENT_FIELD_NAME, document.getContent());
searchDocument.put(METADATA_FIELD_NAME, new JSONObject(document.getMetadata()).toJSONString());
// Add the filterable metadata fields as top level fields, allowing filler
// expressions on them.
for (MetadataField mf : this.filterMetadataFields) {
if (document.getMetadata().containsKey(mf.name())) {
searchDocument.put(METADATA_FIELD_PREFIX + mf.name(), document.getMetadata().get(mf.name()));
}
}
return searchDocument;
}).toList();
IndexDocumentsResult result = this.searchClient.uploadDocuments(searchDocuments);
for (IndexingResult indexingResult : result.getResults()) {
Assert.isTrue(indexingResult.isSucceeded(),
String.format("Document with key %s upload is not successfully", indexingResult.getKey()));
}
}
@Override
public Optional<Boolean> delete(List<String> documentIds) {
Assert.notNull(documentIds, "The document ID list should not be null.");
if (CollectionUtils.isEmpty(documentIds)) {
return Optional.of(true); // nothing to do;
}
final var searchDocumentIds = documentIds.stream().map(documentId -> {
SearchDocument searchDocument = new SearchDocument();
searchDocument.put(ID_FIELD_NAME, documentId);
return searchDocument;
}).toList();
var results = this.searchClient.deleteDocuments(searchDocumentIds);
boolean resSuccess = true;
for (IndexingResult result : results.getResults()) {
if (!result.isSucceeded()) {
resSuccess = false;
break;
}
}
return Optional.of(resSuccess);
}
@Override
public List<Document> similaritySearch(String query) {
return this.similaritySearch(SearchRequest.query(query)
.withTopK(this.defaultTopK)
.withSimilarityThreshold(this.defaultSimilarityThreshold));
}
@Override
public List<Document> similaritySearch(SearchRequest request) {
Assert.notNull(request, "The search request must not be null.");
var searchEmbedding = toFloatList(embeddingClient.embed(request.getQuery()));
final var vectorQuery = new VectorizedQuery(searchEmbedding).setKNearestNeighborsCount(request.getTopK())
// Set the fields to compare the vector against. This is a comma-delimited
// list of field names.
.setFields(EMBEDDING_FIELD_NAME);
var searchOptions = new SearchOptions()
.setVectorSearchOptions(new VectorSearchOptions().setQueries(vectorQuery));
if (request.hasFilterExpression()) {
String oDataFilter = this.filterExpressionConverter.convertExpression(request.getFilterExpression());
searchOptions.setFilter(oDataFilter);
}
final var searchResults = searchClient.search(null, searchOptions, Context.NONE);
return searchResults.stream()
.filter(result -> result.getScore() >= request.getSimilarityThreshold())
.map(result -> {
final AzureSearchDocument entry = result.getDocument(AzureSearchDocument.class);
Map<String, Object> metadata = (StringUtils.hasText(entry.metadata()))
? JSONObject.parseObject(entry.metadata(), new TypeReference<Map<String, Object>>() {
}) : Map.of();
metadata.put(DISTANCE_METADATA_FIELD_NAME, 1 - (float) result.getScore());
final Document doc = new Document(entry.id(), entry.content(), metadata);
doc.setEmbedding(entry.embedding());
return doc;
})
.collect(Collectors.toList());
}
private List<Float> toFloatList(List<Double> doubleList) {
return doubleList.stream().map(Double::floatValue).toList();
}
/**
* Internal data structure for retrieving and and storing documents.
*/
private record AzureSearchDocument(String id, String content, List<Double> embedding, String metadata) {
}
@Override
public void afterPropertiesSet() throws Exception {
int dimensions = this.embeddingClient.dimensions();
List<SearchField> fields = new ArrayList<>();
fields.add(new SearchField(ID_FIELD_NAME, SearchFieldDataType.STRING).setKey(true)
.setFilterable(true)
.setSortable(true));
fields.add(new SearchField(EMBEDDING_FIELD_NAME, SearchFieldDataType.collection(SearchFieldDataType.SINGLE))
.setSearchable(true)
.setVectorSearchDimensions(dimensions)
// This must match a vector search configuration name.
.setVectorSearchProfileName(SPRING_AI_VECTOR_PROFILE));
fields.add(new SearchField(CONTENT_FIELD_NAME, SearchFieldDataType.STRING).setSearchable(true)
.setFilterable(true));
fields.add(new SearchField(METADATA_FIELD_NAME, SearchFieldDataType.STRING).setSearchable(true)
.setFilterable(true));
for (MetadataField filterableMetadataField : this.filterMetadataFields) {
fields.add(new SearchField(METADATA_FIELD_PREFIX + filterableMetadataField.name(),
filterableMetadataField.fieldType())
.setSearchable(false)
.setFacetable(true));
}
SearchIndex searchIndex = new SearchIndex(this.indexName).setFields(fields)
// VectorSearch configuration is required for a vector field. The name used
// for the vector search algorithm configuration must match the configuration
// used by the search field used for vector search.
.setVectorSearch(new VectorSearch()
.setProfiles(Collections
.singletonList(new VectorSearchProfile(SPRING_AI_VECTOR_PROFILE, SPRING_AI_VECTOR_CONFIG)))
.setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration(SPRING_AI_VECTOR_CONFIG)
.setParameters(new HnswParameters().setM(4)
.setEfConstruction(400)
.setEfSearch(1000)
.setMetric(VectorSearchAlgorithmMetric.COSINE)))));
SearchIndex index = this.searchIndexClient.createOrUpdateIndex(searchIndex);
logger.info("Created search index: " + index.getName());
this.searchClient = this.searchIndexClient.getSearchClient(this.indexName);
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((10073, 10191), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((10073, 10130), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
/*
* 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.autoconfigure.bedrock.jurrasic2;
import org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions;
import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Configuration properties for Bedrock Ai21Jurassic2.
*
* @author Ahmed Yousri
* @since 1.0.0
*/
@ConfigurationProperties(BedrockAi21Jurassic2ChatProperties.CONFIG_PREFIX)
public class BedrockAi21Jurassic2ChatProperties {
public static final String CONFIG_PREFIX = "spring.ai.bedrock.jurassic2.chat";
/**
* Enable Bedrock Ai21Jurassic2 chat client. Disabled by default.
*/
private boolean enabled = false;
/**
* The generative id to use. See the {@link Ai21Jurassic2ChatModel} for the supported
* models.
*/
private String model = Ai21Jurassic2ChatModel.AI21_J2_MID_V1.id();
@NestedConfigurationProperty
private BedrockAi21Jurassic2ChatOptions options = BedrockAi21Jurassic2ChatOptions.builder()
.withTemperature(0.7f)
.withMaxTokens(500)
.build();
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public BedrockAi21Jurassic2ChatOptions getOptions() {
return this.options;
}
public void setOptions(BedrockAi21Jurassic2ChatOptions options) {
this.options = options;
}
}
| [
"org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_MID_V1.id",
"org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder"
] | [((1585, 1627), 'org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_MID_V1.id'), ((1711, 1810), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder'), ((1711, 1799), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder'), ((1711, 1777), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder')] |
/*
* 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.autoconfigure.vectorstore.mongo;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.MongoDBAtlasVectorStore;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.StringUtils;
/**
* @author Eddú Meléndez
* @author Christian Tzolov
* @since 1.0.0
*/
@AutoConfiguration(after = MongoDataAutoConfiguration.class)
@ConditionalOnClass({ MongoDBAtlasVectorStore.class, EmbeddingClient.class, MongoTemplate.class })
@EnableConfigurationProperties(MongoDBAtlasVectorStoreProperties.class)
public class MongoDBAtlasVectorStoreAutoConfiguration {
@Bean
@ConditionalOnMissingBean
MongoDBAtlasVectorStore vectorStore(MongoTemplate mongoTemplate, EmbeddingClient embeddingClient,
MongoDBAtlasVectorStoreProperties properties) {
var builder = MongoDBAtlasVectorStore.MongoDBVectorStoreConfig.builder();
if (StringUtils.hasText(properties.getCollectionName())) {
builder.withCollectionName(properties.getCollectionName());
}
if (StringUtils.hasText(properties.getPathName())) {
builder.withPathName(properties.getPathName());
}
if (StringUtils.hasText(properties.getIndexName())) {
builder.withVectorIndexName(properties.getIndexName());
}
MongoDBAtlasVectorStore.MongoDBVectorStoreConfig config = builder.build();
return new MongoDBAtlasVectorStore(mongoTemplate, embeddingClient, config);
}
}
| [
"org.springframework.ai.vectorstore.MongoDBAtlasVectorStore.MongoDBVectorStoreConfig.builder"
] | [((1925, 1983), 'org.springframework.ai.vectorstore.MongoDBAtlasVectorStore.MongoDBVectorStoreConfig.builder')] |
/*
* 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.autoconfigure.bedrock.cohere;
import org.springframework.ai.bedrock.cohere.BedrockCohereChatOptions;
import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Bedrock Cohere Chat autoconfiguration properties.
*
* @author Christian Tzolov
* @since 0.8.0
*/
@ConfigurationProperties(BedrockCohereChatProperties.CONFIG_PREFIX)
public class BedrockCohereChatProperties {
public static final String CONFIG_PREFIX = "spring.ai.bedrock.cohere.chat";
/**
* Enable Bedrock Cohere Chat Client. False by default.
*/
private boolean enabled = false;
/**
* Bedrock Cohere Chat generative name. Defaults to 'cohere-command-v14'.
*/
private String model = CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id();
@NestedConfigurationProperty
private BedrockCohereChatOptions options = BedrockCohereChatOptions.builder().build();
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public BedrockCohereChatOptions getOptions() {
return this.options;
}
public void setOptions(BedrockCohereChatOptions options) {
this.options = options;
}
}
| [
"org.springframework.ai.bedrock.cohere.BedrockCohereChatOptions.builder",
"org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id"
] | [((1489, 1549), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id'), ((1626, 1668), 'org.springframework.ai.bedrock.cohere.BedrockCohereChatOptions.builder')] |
/*
* 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.bedrock.jurassic2.api;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatClient;
import org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.parser.MapOutputParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
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 {
@Autowired
private BedrockAi21Jurassic2ChatClient client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@Test
void roleTest() {
UserMessage userMessage = new UserMessage(
"Tell me about 3 famous pirates from the Golden Age of Piracy and why they did.");
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 = client.call(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@Test
void testEmojiPenaltyFalse() {
BedrockAi21Jurassic2ChatOptions.Penalty penalty = new BedrockAi21Jurassic2ChatOptions.Penalty.Builder()
.applyToEmojis(false)
.build();
BedrockAi21Jurassic2ChatOptions options = new BedrockAi21Jurassic2ChatOptions.Builder()
.withPresencePenalty(penalty)
.build();
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);
assertThat(response.getResult().getOutput().getContent()).matches(content -> content.contains("😄"));
}
@Test
@Disabled("This test is failing when run in combination with the other tests")
void emojiPenaltyWhenTrueByDefaultApplyPenaltyTest() {
// applyToEmojis is by default true
BedrockAi21Jurassic2ChatOptions.Penalty penalty = new BedrockAi21Jurassic2ChatOptions.Penalty.Builder().build();
BedrockAi21Jurassic2ChatOptions options = new BedrockAi21Jurassic2ChatOptions.Builder()
.withPresencePenalty(penalty)
.build();
UserMessage userMessage = new UserMessage("Can you express happiness using an emoji like 😄?");
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Bob", "voice", "pirate"));
Prompt prompt = new Prompt(List.of(userMessage, systemMessage), options);
ChatResponse response = client.call(prompt);
assertThat(response.getResult().getOutput().getContent()).doesNotContain("😄");
}
@Test
void mapOutputParser() {
MapOutputParser outputParser = new MapOutputParser();
String format = outputParser.getFormat();
String template = """
Provide me a List of {subject}
{format}
""";
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();
Map<String, Object> result = outputParser.parse(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
}
@Test
void simpleChatResponse() {
UserMessage userMessage = new UserMessage("Tell me a joke about AI.");
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 = client.call(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("AI");
}
@SpringBootConfiguration
public static class TestConfiguration {
@Bean
public Ai21Jurassic2ChatBedrockApi jurassic2ChatBedrockApi() {
return new Ai21Jurassic2ChatBedrockApi(
Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_MID_V1.id(),
EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper());
}
@Bean
public BedrockAi21Jurassic2ChatClient bedrockAi21Jurassic2ChatClient(
Ai21Jurassic2ChatBedrockApi jurassic2ChatBedrockApi) {
return new BedrockAi21Jurassic2ChatClient(jurassic2ChatBedrockApi,
BedrockAi21Jurassic2ChatOptions.builder()
.withTemperature(0.5f)
.withMaxTokens(100)
.withTopP(0.9f)
.build());
}
}
}
| [
"org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder"
] | [((6057, 6078), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((6320, 6453), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder'), ((6320, 6438), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder'), ((6320, 6416), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder'), ((6320, 6390), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatOptions.builder')] |
/*
* 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 static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.ChatOptionsBuilder;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.function.FunctionCallback;
import org.springframework.ai.model.function.FunctionCallbackWrapper;
import org.springframework.ai.model.function.FunctionCallingOptions;
/**
* Unit Tests for {@link Prompt}.
*
* @author youngmon
* @since 0.8.1
*/
public class ChatBuilderTests {
@Test
void createNewChatOptionsTest() {
Float temperature = 1.1f;
Float topP = 2.2f;
Integer topK = 111;
ChatOptions options = ChatOptionsBuilder.builder()
.withTemperature(temperature)
.withTopK(topK)
.withTopP(topP)
.build();
assertThat(options.getTemperature()).isEqualTo(temperature);
assertThat(options.getTopP()).isEqualTo(topP);
assertThat(options.getTopK()).isEqualTo(topK);
}
@Test
void duplicateChatOptionsTest() {
Float initTemperature = 1.1f;
Float initTopP = 2.2f;
Integer initTopK = 111;
ChatOptions options = ChatOptionsBuilder.builder()
.withTemperature(initTemperature)
.withTopP(initTopP)
.withTopK(initTopK)
.build();
}
@Test
void createFunctionCallingOptionTest() {
Float temperature = 1.1f;
Float topP = 2.2f;
Integer topK = 111;
List<FunctionCallback> functionCallbacks = new ArrayList<>();
Set<String> functions = new HashSet<>();
String func = "func";
FunctionCallback cb = FunctionCallbackWrapper.<Integer, Integer>builder(i -> i)
.withName("cb")
.withDescription("cb")
.build();
functions.add(func);
functionCallbacks.add(cb);
FunctionCallingOptions options = FunctionCallingOptions.builder()
.withFunctionCallbacks(functionCallbacks)
.withFunctions(functions)
.withTopK(topK)
.withTopP(topP)
.withTemperature(temperature)
.build();
// Callback Functions
assertThat(options.getFunctionCallbacks()).isNotNull();
assertThat(options.getFunctionCallbacks().size()).isEqualTo(1);
assertThat(options.getFunctionCallbacks().contains(cb));
// Functions
assertThat(options.getFunctions()).isNotNull();
assertThat(options.getFunctions().size()).isEqualTo(1);
assertThat(options.getFunctions().contains(func));
}
}
| [
"org.springframework.ai.model.function.FunctionCallbackWrapper.<Integer, Integer>builder",
"org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder",
"org.springframework.ai.model.function.FunctionCallingOptions.builder"
] | [((1473, 1584), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1473, 1572), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1473, 1553), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1473, 1534), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1902, 2025), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1902, 2013), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1902, 1990), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1902, 1967), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2308, 2422), 'org.springframework.ai.model.function.FunctionCallbackWrapper.<Integer, Integer>builder'), ((2308, 2410), 'org.springframework.ai.model.function.FunctionCallbackWrapper.<Integer, Integer>builder'), ((2308, 2384), 'org.springframework.ai.model.function.FunctionCallbackWrapper.<Integer, Integer>builder'), ((2513, 2702), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((2513, 2690), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((2513, 2657), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((2513, 2638), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((2513, 2619), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((2513, 2590), 'org.springframework.ai.model.function.FunctionCallingOptions.builder')] |
/*
* 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.stabilityai;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.image.*;
import org.springframework.ai.stabilityai.api.StabilityAiImageOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = StabilityAiImageTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "STABILITYAI_API_KEY", matches = ".*")
public class StabilityAiImageClientIT {
@Autowired
protected ImageClient stabilityAiImageClient;
@Test
void imageAsBase64Test() throws IOException {
StabilityAiImageOptions imageOptions = StabilityAiImageOptions.builder()
.withStylePreset(StyleEnum.PHOTOGRAPHIC)
.build();
var instructions = """
A light cream colored mini golden doodle.
""";
ImagePrompt imagePrompt = new ImagePrompt(instructions, imageOptions);
ImageResponse imageResponse = this.stabilityAiImageClient.call(imagePrompt);
ImageGeneration imageGeneration = imageResponse.getResult();
Image image = imageGeneration.getOutput();
assertThat(image.getB64Json()).isNotEmpty();
writeFile(image);
}
private static void writeFile(Image image) throws IOException {
byte[] imageBytes = Base64.getDecoder().decode(image.getB64Json());
String systemTempDir = System.getProperty("java.io.tmpdir");
String filePath = systemTempDir + File.separator + "dog.png";
File file = new File(filePath);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(imageBytes);
}
}
}
| [
"org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder"
] | [((1511, 1600), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder'), ((1511, 1588), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder'), ((2106, 2152), 'java.util.Base64.getDecoder')] |
/*
* 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.mistralai;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.mistralai.api.MistralAiApi;
import org.springframework.ai.model.function.FunctionCallbackWrapper;
import org.springframework.ai.parser.BeanOutputParser;
import org.springframework.ai.parser.ListOutputParser;
import org.springframework.ai.parser.MapOutputParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
* @since 0.8.1
*/
@SpringBootTest(classes = MistralAiTestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".+")
class MistralAiChatClientIT {
private static final Logger logger = LoggerFactory.getLogger(MistralAiChatClientIT.class);
@Autowired
protected ChatClient chatClient;
@Autowired
protected StreamingChatClient streamingChatClient;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@Value("classpath:/prompts/eval/qa-evaluator-accurate-answer.st")
protected Resource qaEvaluatorAccurateAnswerResource;
@Value("classpath:/prompts/eval/qa-evaluator-not-related-message.st")
protected Resource qaEvaluatorNotRelatedResource;
@Value("classpath:/prompts/eval/qa-evaluator-fact-based-answer.st")
protected Resource qaEvalutaorFactBasedAnswerResource;
@Value("classpath:/prompts/eval/user-evaluator-message.st")
protected Resource userEvaluatorResource;
@Test
void roleTest() {
UserMessage userMessage = new UserMessage(
"Tell me about 3 famous pirates from the Golden Age of Piracy and why they did.");
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Bob", "voice", "pirate"));
// 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);
assertThat(response.getResults()).hasSize(1);
assertThat(response.getResults().get(0).getOutput().getContent()).contains("Blackbeard");
}
@Test
void outputParser() {
DefaultConversionService conversionService = new DefaultConversionService();
ListOutputParser outputParser = new ListOutputParser(conversionService);
String format = outputParser.getFormat();
String template = """
List five {subject}
{format}
""";
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();
List<String> list = outputParser.parse(generation.getOutput().getContent());
assertThat(list).hasSize(5);
}
@Test
void mapOutputParser() {
MapOutputParser outputParser = new MapOutputParser();
String format = outputParser.getFormat();
String template = """
Provide me a List of {subject}
{format}
""";
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();
Map<String, Object> result = outputParser.parse(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
}
record ActorsFilmsRecord(String actor, List<String> movies) {
}
@Test
void beanOutputParserRecords() {
BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class);
String format = outputParser.getFormat();
String template = """
Generate the filmography of 5 movies for Tom Hanks.
{format}
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = chatClient.call(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent());
logger.info("" + actorsFilms);
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
assertThat(actorsFilms.movies()).hasSize(5);
}
@Test
void beanStreamOutputParserRecords() {
BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class);
String format = outputParser.getFormat();
String template = """
Generate the filmography of 5 movies for Tom Hanks.
{format}
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
String generationTextFromStream = streamingChatClient.stream(prompt)
.collectList()
.block()
.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.joining());
ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream);
logger.info("" + actorsFilms);
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
assertThat(actorsFilms.movies()).hasSize(5);
}
@Test
void functionCallTest() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco?");
List<Message> messages = new ArrayList<>(List.of(userMessage));
var promptOptions = MistralAiChatOptions.builder()
.withModel(MistralAiApi.ChatModel.SMALL.getValue())
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withName("getCurrentWeather")
.withDescription("Get the weather in location")
.withResponseConverter((response) -> "" + response.temp() + response.unit())
.build()))
.build();
ChatResponse response = chatClient.call(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);
assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30");
}
@Test
void streamFunctionCallTest() {
UserMessage userMessage = new UserMessage("What's the weather like in Tokyo, Japan?");
List<Message> messages = new ArrayList<>(List.of(userMessage));
var promptOptions = MistralAiChatOptions.builder()
.withModel(MistralAiApi.ChatModel.SMALL.getValue())
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withName("getCurrentWeather")
.withDescription("Get the weather in location")
.withResponseConverter((response) -> "" + response.temp() + response.unit())
.build()))
.build();
Flux<ChatResponse> response = streamingChatClient.stream(new Prompt(messages, promptOptions));
String content = response.collectList()
.block()
.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.joining());
logger.info("Response: {}", content);
assertThat(content).containsAnyOf("10.0", "10");
}
}
| [
"org.springframework.ai.model.function.FunctionCallbackWrapper.builder",
"org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue"
] | [((7279, 7318), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue'), ((7354, 7592), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7354, 7579), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7354, 7498), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7354, 7446), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8090, 8129), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue'), ((8165, 8403), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8165, 8390), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8165, 8309), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8165, 8257), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')] |
/*
* 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.bedrock.llama2.api;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.regions.Region;
import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel;
import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest;
import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
*/
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
public class Llama2ChatBedrockApiIT {
private Llama2ChatBedrockApi llama2ChatApi = new Llama2ChatBedrockApi(Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(),
Region.US_EAST_1.id());
@Test
public void chatCompletion() {
Llama2ChatRequest request = Llama2ChatRequest.builder("Hello, my name is")
.withTemperature(0.9f)
.withTopP(0.9f)
.withMaxGenLen(20)
.build();
Llama2ChatResponse response = llama2ChatApi.chatCompletion(request);
System.out.println(response.generation());
assertThat(response).isNotNull();
assertThat(response.generation()).isNotEmpty();
assertThat(response.promptTokenCount()).isEqualTo(6);
assertThat(response.generationTokenCount()).isGreaterThan(10);
assertThat(response.generationTokenCount()).isLessThanOrEqualTo(20);
assertThat(response.stopReason()).isNotNull();
assertThat(response.amazonBedrockInvocationMetrics()).isNull();
}
@Test
public void chatCompletionStream() {
Llama2ChatRequest request = new Llama2ChatRequest("Hello, my name is", 0.9f, 0.9f, 20);
Flux<Llama2ChatResponse> responseStream = llama2ChatApi.chatCompletionStream(request);
List<Llama2ChatResponse> responses = responseStream.collectList().block();
assertThat(responses).isNotNull();
assertThat(responses).hasSizeGreaterThan(10);
assertThat(responses.get(0).generation()).isNotEmpty();
Llama2ChatResponse lastResponse = responses.get(responses.size() - 1);
assertThat(lastResponse.stopReason()).isNotNull();
assertThat(lastResponse.amazonBedrockInvocationMetrics()).isNotNull();
}
}
| [
"org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest.builder",
"org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id"
] | [((1508, 1547), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id'), ((1552, 1573), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((1647, 1772), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest.builder'), ((1647, 1760), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest.builder'), ((1647, 1738), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest.builder'), ((1647, 1719), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest.builder')] |
/*
* 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.bedrock.anthropic;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.AssistantMessage;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.parser.BeanOutputParser;
import org.springframework.ai.parser.ListOutputParser;
import org.springframework.ai.parser.MapOutputParser;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.io.Resource;
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 {
private static final Logger logger = LoggerFactory.getLogger(BedrockAnthropicChatClientIT.class);
@Autowired
private BedrockAnthropicChatClient client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@Test
void roleTest() {
UserMessage userMessage = new UserMessage(
"Tell me about 3 famous pirates from the Golden Age of Piracy and why they did.");
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 = client.call(prompt);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@Test
void outputParser() {
DefaultConversionService conversionService = new DefaultConversionService();
ListOutputParser outputParser = new ListOutputParser(conversionService);
String format = outputParser.getFormat();
String template = """
List five {subject}
{format}
""";
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();
List<String> list = outputParser.parse(generation.getOutput().getContent());
assertThat(list).hasSize(5);
}
@Test
void mapOutputParser() {
MapOutputParser outputParser = new MapOutputParser();
String format = outputParser.getFormat();
String template = """
Provide me a List of {subject}
{format}
""";
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();
Map<String, Object> result = outputParser.parse(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
}
record ActorsFilmsRecord(String actor, List<String> movies) {
}
@Test
void beanOutputParserRecords() {
BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class);
String format = outputParser.getFormat();
String template = """
Generate the filmography of 5 movies for Tom Hanks.
Remove non JSON tex blocks from the output.
{format}
Provide your answer in the JSON format with the feature names as the keys.
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
assertThat(actorsFilms.movies()).hasSize(5);
}
@Test
void beanStreamOutputParserRecords() {
BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class);
String format = outputParser.getFormat();
String template = """
Generate the filmography of 5 movies for Tom Hanks.
{format}
Remove Markdown code blocks from the output.
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
String generationTextFromStream = client.stream(prompt)
.collectList()
.block()
.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.joining());
ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream);
logger.info("" + actorsFilms);
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
assertThat(actorsFilms.movies()).hasSize(5);
}
@SpringBootConfiguration
public static class TestConfiguration {
@Bean
public AnthropicChatBedrockApi anthropicApi() {
return new AnthropicChatBedrockApi(AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id(),
EnvironmentVariableCredentialsProvider.create(), Region.EU_CENTRAL_1.id(), new ObjectMapper());
}
@Bean
public BedrockAnthropicChatClient anthropicChatClient(AnthropicChatBedrockApi anthropicApi) {
return new BedrockAnthropicChatClient(anthropicApi);
}
}
}
| [
"org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id"
] | [((6684, 6741), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((6797, 6821), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')] |
/*
* 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.bedrock.cohere;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.chat.messages.AssistantMessage;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi;
import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.parser.BeanOutputParser;
import org.springframework.ai.parser.ListOutputParser;
import org.springframework.ai.parser.MapOutputParser;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.io.Resource;
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 {
@Autowired
private BedrockCohereChatClient client;
@Value("classpath:/prompts/system-message.st")
private Resource systemResource;
@Test
void roleTest() {
String request = "Tell me about 3 famous pirates from the Golden Age of Piracy and why they did.";
String name = "Bob";
String voice = "pirate";
UserMessage userMessage = new UserMessage(request);
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);
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
}
@Test
void outputParser() {
DefaultConversionService conversionService = new DefaultConversionService();
ListOutputParser outputParser = new ListOutputParser(conversionService);
String format = outputParser.getFormat();
String template = """
List five {subject}
{format}
""";
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();
List<String> list = outputParser.parse(generation.getOutput().getContent());
assertThat(list).hasSize(5);
}
@Test
void mapOutputParser() {
MapOutputParser outputParser = new MapOutputParser();
String format = outputParser.getFormat();
String template = """
Remove Markdown code blocks from the output.
Provide me a List of {subject}
{format}
""";
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();
Map<String, Object> result = outputParser.parse(generation.getOutput().getContent());
assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
}
record ActorsFilmsRecord(String actor, List<String> movies) {
}
@Test
void beanOutputParserRecords() {
BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class);
String format = outputParser.getFormat();
String template = """
Generate the filmography of 5 movies for Tom Hanks.
{format}
Remove Markdown code blocks from the output.
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
Generation generation = client.call(prompt).getResult();
ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent());
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
assertThat(actorsFilms.movies()).hasSize(5);
}
@Test
void beanStreamOutputParserRecords() {
BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class);
String format = outputParser.getFormat();
String template = """
Generate the filmography of 5 movies for Tom Hanks.
{format}
Remove Markdown code blocks from the output.
""";
PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format));
Prompt prompt = new Prompt(promptTemplate.createMessage());
String generationTextFromStream = client.stream(prompt)
.collectList()
.block()
.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.joining());
ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream);
System.out.println(actorsFilms);
assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
assertThat(actorsFilms.movies()).hasSize(5);
}
@SpringBootConfiguration
public static class TestConfiguration {
@Bean
public CohereChatBedrockApi cohereApi() {
return new CohereChatBedrockApi(CohereChatModel.COHERE_COMMAND_V14.id(),
EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper());
}
@Bean
public BedrockCohereChatClient cohereChatClient(CohereChatBedrockApi cohereApi) {
return new BedrockCohereChatClient(cohereApi);
}
}
}
| [
"org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id"
] | [((6628, 6667), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id'), ((6723, 6744), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')] |
/*
* 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.testcontainers.service.connection.qdrant;
import org.junit.jupiter.api.Test;
import org.springframework.ai.autoconfigure.vectorstore.qdrant.QdrantVectorStoreAutoConfiguration;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.transformers.TransformersEmbeddingClient;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.qdrant.QdrantContainer;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@SpringJUnitConfig
@Testcontainers
@TestPropertySource(properties = "spring.ai.vectorstore.qdrant.collectionName=test_collection")
public class QdrantContainerConnectionDetailsFactoryTest {
@Container
@ServiceConnection
static QdrantContainer qdrantContainer = new QdrantContainer("qdrant/qdrant:v1.7.4");
List<Document> documents = List.of(
new Document(getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")),
new Document(getText("classpath:/test/data/time.shelter.txt")),
new Document(getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad")));
@Autowired
private VectorStore vectorStore;
@Test
public void addAndSearch() {
vectorStore.add(documents);
List<Document> results = vectorStore
.similaritySearch(SearchRequest.query("What is Great Depression?").withTopK(1));
assertThat(results).hasSize(1);
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId());
assertThat(resultDoc.getMetadata()).containsKeys("depression", "distance");
// Remove all documents from the store
vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList());
results = vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1));
assertThat(results).hasSize(0);
}
public static String getText(String uri) {
var resource = new DefaultResourceLoader().getResource(uri);
try {
return resource.getContentAsString(StandardCharsets.UTF_8);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@Configuration(proxyBeanMethods = false)
@ImportAutoConfiguration(QdrantVectorStoreAutoConfiguration.class)
static class Config {
@Bean
public EmbeddingClient embeddingClient() {
return new TransformersEmbeddingClient();
}
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((2756, 2816), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3198, 3249), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai.metadata.support;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor.DurationFormatter;
/**
* Unit Tests for {@link OpenAiHttpResponseHeadersInterceptor}.
*
* @author John Blum
* @author Christian Tzolov
* @since 0.7.0
*/
public class OpenAiResponseHeaderExtractorTests {
@Test
void parseTimeAsDurationWithDaysHoursMinutesSeconds() {
Duration actual = DurationFormatter.TIME_UNIT.parse("6d18h22m45s");
Duration expected = Duration.ofDays(6L)
.plus(Duration.ofHours(18L))
.plus(Duration.ofMinutes(22))
.plus(Duration.ofSeconds(45L));
assertThat(actual).isEqualTo(expected);
}
@Test
void parseTimeAsDurationWithMinutesSecondsMicrosecondsAndMicroseconds() {
Duration actual = DurationFormatter.TIME_UNIT.parse("42m18s451ms21541ns");
Duration expected = Duration.ofMinutes(42L)
.plus(Duration.ofSeconds(18L))
.plus(Duration.ofMillis(451))
.plus(Duration.ofNanos(21541L));
assertThat(actual).isEqualTo(expected);
}
@Test
void parseTimeAsDurationWithDaysMinutesAndMilliseconds() {
Duration actual = DurationFormatter.TIME_UNIT.parse("2d15m981ms");
Duration expected = Duration.ofDays(2L).plus(Duration.ofMinutes(15L)).plus(Duration.ofMillis(981L));
assertThat(actual).isEqualTo(expected);
}
}
| [
"org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor.DurationFormatter.TIME_UNIT.parse"
] | [((1179, 1227), 'org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor.DurationFormatter.TIME_UNIT.parse'), ((1251, 1369), 'java.time.Duration.ofDays'), ((1251, 1335), 'java.time.Duration.ofDays'), ((1251, 1302), 'java.time.Duration.ofDays'), ((1521, 1576), 'org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor.DurationFormatter.TIME_UNIT.parse'), ((1600, 1725), 'java.time.Duration.ofMinutes'), ((1600, 1690), 'java.time.Duration.ofMinutes'), ((1600, 1657), 'java.time.Duration.ofMinutes'), ((1862, 1909), 'org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor.DurationFormatter.TIME_UNIT.parse'), ((1933, 2012), 'java.time.Duration.ofDays'), ((1933, 1982), 'java.time.Duration.ofDays')] |
/*
* 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.autoconfigure.bedrock.cohere;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties;
import org.springframework.ai.bedrock.cohere.BedrockCohereEmbeddingClient;
import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel;
import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingRequest;
import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingRequest.InputType;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import software.amazon.awssdk.regions.Region;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
* @since 0.8.0
*/
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
public class BedrockCohereEmbeddingAutoConfigurationIT {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.cohere.embedding.enabled=true",
"spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"),
"spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"),
"spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(),
"spring.ai.bedrock.cohere.embedding.model=" + CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id(),
"spring.ai.bedrock.cohere.embedding.options.inputType=SEARCH_DOCUMENT",
"spring.ai.bedrock.cohere.embedding.options.truncate=NONE")
.withConfiguration(AutoConfigurations.of(BedrockCohereEmbeddingAutoConfiguration.class));
@Test
public void singleEmbedding() {
contextRunner.run(context -> {
BedrockCohereEmbeddingClient embeddingClient = context.getBean(BedrockCohereEmbeddingClient.class);
assertThat(embeddingClient).isNotNull();
EmbeddingResponse embeddingResponse = embeddingClient.embedForResponse(List.of("Hello World"));
assertThat(embeddingResponse.getResults()).hasSize(1);
assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty();
assertThat(embeddingClient.dimensions()).isEqualTo(1024);
});
}
@Test
public void batchEmbedding() {
contextRunner.run(context -> {
BedrockCohereEmbeddingClient embeddingClient = context.getBean(BedrockCohereEmbeddingClient.class);
assertThat(embeddingClient).isNotNull();
EmbeddingResponse embeddingResponse = embeddingClient
.embedForResponse(List.of("Hello World", "World is big and salvation is near"));
assertThat(embeddingResponse.getResults()).hasSize(2);
assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty();
assertThat(embeddingResponse.getResults().get(0).getIndex()).isEqualTo(0);
assertThat(embeddingResponse.getResults().get(1).getOutput()).isNotEmpty();
assertThat(embeddingResponse.getResults().get(1).getIndex()).isEqualTo(1);
assertThat(embeddingClient.dimensions()).isEqualTo(1024);
});
}
@Test
public void propertiesTest() {
new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.cohere.embedding.enabled=true",
"spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY",
"spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(),
"spring.ai.bedrock.cohere.embedding.model=MODEL_XYZ",
"spring.ai.bedrock.cohere.embedding.options.inputType=CLASSIFICATION",
"spring.ai.bedrock.cohere.embedding.options.truncate=RIGHT")
.withConfiguration(AutoConfigurations.of(BedrockCohereEmbeddingAutoConfiguration.class))
.run(context -> {
var properties = context.getBean(BedrockCohereEmbeddingProperties.class);
var awsProperties = context.getBean(BedrockAwsConnectionProperties.class);
assertThat(properties.isEnabled()).isTrue();
assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id());
assertThat(properties.getModel()).isEqualTo("MODEL_XYZ");
assertThat(properties.getOptions().getInputType()).isEqualTo(InputType.CLASSIFICATION);
assertThat(properties.getOptions().getTruncate()).isEqualTo(CohereEmbeddingRequest.Truncate.RIGHT);
assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY");
assertThat(awsProperties.getSecretKey()).isEqualTo("SECRET_KEY");
});
}
@Test
public void embeddingDisabled() {
// It is disabled by default
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(BedrockCohereEmbeddingAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockCohereEmbeddingProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockCohereEmbeddingClient.class)).isEmpty();
});
// Explicitly enable the embedding auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.cohere.embedding.enabled=true")
.withConfiguration(AutoConfigurations.of(BedrockCohereEmbeddingAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockCohereEmbeddingProperties.class)).isNotEmpty();
assertThat(context.getBeansOfType(BedrockCohereEmbeddingClient.class)).isNotEmpty();
});
// Explicitly disable the embedding auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.cohere.embedding.enabled=false")
.withConfiguration(AutoConfigurations.of(BedrockCohereEmbeddingAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockCohereEmbeddingProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockCohereEmbeddingClient.class)).isEmpty();
});
}
}
| [
"org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id"
] | [((2204, 2225), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2277, 2331), 'org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id'), ((4186, 4210), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((4785, 4809), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')] |
/*
* 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.ollama;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.ChatOptionsBuilder;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
*/
public class OllamaChatRequestTests {
OllamaChatClient client = new OllamaChatClient(new OllamaApi()).withDefaultOptions(
new OllamaOptions().withModel("MODEL_NAME").withTopK(99).withTemperature(66.6f).withNumGPU(1));
@Test
public void createRequestWithDefaultOptions() {
var request = client.ollamaChatRequest(new Prompt("Test message content"), false);
assertThat(request.messages()).hasSize(1);
assertThat(request.stream()).isFalse();
assertThat(request.model()).isEqualTo("MODEL_NAME");
assertThat(request.options().get("temperature")).isEqualTo(66.6);
assertThat(request.options().get("top_k")).isEqualTo(99);
assertThat(request.options().get("num_gpu")).isEqualTo(1);
assertThat(request.options().get("top_p")).isNull();
}
@Test
public void createRequestWithPromptOllamaOptions() {
// Runtime options should override the default options.
OllamaOptions promptOptions = new OllamaOptions().withTemperature(0.8f).withTopP(0.5f).withNumGPU(2);
var request = client.ollamaChatRequest(new Prompt("Test message content", promptOptions), true);
assertThat(request.messages()).hasSize(1);
assertThat(request.stream()).isTrue();
assertThat(request.model()).isEqualTo("MODEL_NAME");
assertThat(request.options().get("temperature")).isEqualTo(0.8);
assertThat(request.options().get("top_k")).isEqualTo(99); // still the default
// value.
assertThat(request.options().get("num_gpu")).isEqualTo(2);
assertThat(request.options().get("top_p")).isEqualTo(0.5); // new field introduced
// by the
// promptOptions.
}
@Test
public void createRequestWithPromptPortableChatOptions() {
// Ollama runtime options.
ChatOptions portablePromptOptions = ChatOptionsBuilder.builder()
.withTemperature(0.9f)
.withTopK(100)
.withTopP(0.6f)
.build();
var request = client.ollamaChatRequest(new Prompt("Test message content", portablePromptOptions), true);
assertThat(request.messages()).hasSize(1);
assertThat(request.stream()).isTrue();
assertThat(request.model()).isEqualTo("MODEL_NAME");
assertThat(request.options().get("temperature")).isEqualTo(0.9);
assertThat(request.options().get("top_k")).isEqualTo(100);
assertThat(request.options().get("num_gpu")).isEqualTo(1); // default value.
assertThat(request.options().get("top_p")).isEqualTo(0.6);
}
@Test
public void createRequestWithPromptOptionsModelOverride() {
// Ollama runtime options.
OllamaOptions promptOptions = new OllamaOptions().withModel("PROMPT_MODEL");
var request = client.ollamaChatRequest(new Prompt("Test message content", promptOptions), true);
assertThat(request.model()).isEqualTo("PROMPT_MODEL");
}
@Test
public void createRequestWithDefaultOptionsModelOverride() {
OllamaChatClient client2 = new OllamaChatClient(new OllamaApi())
.withDefaultOptions(new OllamaOptions().withModel("DEFAULT_OPTIONS_MODEL"));
var request = client2.ollamaChatRequest(new Prompt("Test message content"), true);
assertThat(request.model()).isEqualTo("DEFAULT_OPTIONS_MODEL");
// Prompt options should override the default options.
OllamaOptions promptOptions = new OllamaOptions().withModel("PROMPT_MODEL");
request = client2.ollamaChatRequest(new Prompt("Test message content", promptOptions), true);
assertThat(request.model()).isEqualTo("PROMPT_MODEL");
}
}
| [
"org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder"
] | [((2813, 2916), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2813, 2904), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2813, 2885), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2813, 2867), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder')] |
/*
* 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.testcontainers.service.connection.chroma;
import org.junit.jupiter.api.Test;
import org.springframework.ai.autoconfigure.vectorstore.chroma.ChromaVectorStoreAutoConfiguration;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.transformers.TransformersEmbeddingClient;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.testcontainers.chromadb.ChromaDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@SpringJUnitConfig
@Testcontainers
@TestPropertySource(properties = "spring.ai.vectorstore.chroma.store.collectionName=TestCollection")
class ChromaContainerConnectionDetailsFactoryTest {
@Container
@ServiceConnection
static ChromaDBContainer chroma = new ChromaDBContainer("ghcr.io/chroma-core/chroma:0.4.15");
@Autowired
private VectorStore vectorStore;
@Test
public void addAndSearchWithFilters() {
var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner",
Map.of("country", "Bulgaria"));
var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner",
Map.of("country", "Netherlands"));
vectorStore.add(List.of(bgDocument, nlDocument));
var request = SearchRequest.query("The World").withTopK(5);
List<Document> results = vectorStore.similaritySearch(request);
assertThat(results).hasSize(2);
results = vectorStore
.similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("country == 'Bulgaria'"));
assertThat(results).hasSize(1);
assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId());
results = vectorStore
.similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("country == 'Netherlands'"));
assertThat(results).hasSize(1);
assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId());
// Remove all documents from the store
vectorStore.delete(List.of(bgDocument, nlDocument).stream().map(doc -> doc.getId()).toList());
}
@Configuration(proxyBeanMethods = false)
@ImportAutoConfiguration(ChromaVectorStoreAutoConfiguration.class)
static class Config {
@Bean
public EmbeddingClient embeddingClient() {
return new TransformersEmbeddingClient();
}
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((2586, 2630), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3265, 3338), 'java.util.List.of'), ((3265, 3329), 'java.util.List.of'), ((3265, 3305), 'java.util.List.of')] |
/*
* 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.stabilityai;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.stabilityai.api.StabilityAiApi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@EnabledIfEnvironmentVariable(named = "STABILITYAI_API_KEY", matches = ".*")
public class StabilityAiApiIT {
StabilityAiApi stabilityAiApi = new StabilityAiApi(System.getenv("STABILITYAI_API_KEY"));
@Test
void generateImage() throws IOException {
List<StabilityAiApi.GenerateImageRequest.TextPrompts> textPrompts = List
.of(new StabilityAiApi.GenerateImageRequest.TextPrompts(
"A light cream colored mini golden doodle holding a sign that says 'Heading to BARCADE !'", 0.5f));
var builder = StabilityAiApi.GenerateImageRequest.builder()
.withTextPrompts(textPrompts)
.withHeight(1024)
.withWidth(1024)
.withCfgScale(7f)
.withSamples(1)
.withSeed(123L)
.withSteps(30)
.withStylePreset("photographic");
StabilityAiApi.GenerateImageRequest request = builder.build();
StabilityAiApi.GenerateImageResponse response = stabilityAiApi.generateImage(request);
assertThat(response).isNotNull();
List<StabilityAiApi.GenerateImageResponse.Artifacts> artifacts = response.artifacts();
writeToFile(artifacts);
assertThat(artifacts).hasSize(1);
var firstArtifact = artifacts.get(0);
assertThat(firstArtifact.base64()).isNotEmpty();
assertThat(firstArtifact.seed()).isPositive();
assertThat(firstArtifact.finishReason()).isEqualTo("SUCCESS");
}
private static void writeToFile(List<StabilityAiApi.GenerateImageResponse.Artifacts> artifacts) throws IOException {
int counter = 0;
String systemTempDir = System.getProperty("java.io.tmpdir");
for (StabilityAiApi.GenerateImageResponse.Artifacts artifact : artifacts) {
counter++;
byte[] imageBytes = Base64.getDecoder().decode(artifact.base64());
String fileName = String.format("dog%d.png", counter);
String filePath = systemTempDir + File.separator + fileName;
File file = new File(filePath);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(imageBytes);
}
}
}
}
| [
"org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder"
] | [((1530, 1762), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1726), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1708), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1689), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1670), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1649), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1629), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1608), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((1530, 1575), 'org.springframework.ai.stabilityai.api.StabilityAiApi.GenerateImageRequest.builder'), ((2631, 2676), 'java.util.Base64.getDecoder')] |
/*
* 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.bedrock.anthropic.api;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatRequest;
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatResponse;
import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel;
import static org.assertj.core.api.Assertions.assertThat;;
/**
* @author Christian Tzolov
*/
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
public class AnthropicChatBedrockApiIT {
private final Logger logger = LoggerFactory.getLogger(AnthropicChatBedrockApiIT.class);
private AnthropicChatBedrockApi anthropicChatApi = new AnthropicChatBedrockApi(AnthropicChatModel.CLAUDE_V2.id(),
EnvironmentVariableCredentialsProvider.create(), Region.US_WEST_2.id(), new ObjectMapper());
@Test
public void chatCompletion() {
AnthropicChatRequest request = AnthropicChatRequest
.builder(String.format(AnthropicChatBedrockApi.PROMPT_TEMPLATE, "Name 3 famous pirates"))
.withTemperature(0.8f)
.withMaxTokensToSample(300)
.withTopK(10)
.build();
AnthropicChatResponse response = anthropicChatApi.chatCompletion(request);
System.out.println(response.completion());
assertThat(response).isNotNull();
assertThat(response.completion()).isNotEmpty();
assertThat(response.completion()).contains("Blackbeard");
assertThat(response.stopReason()).isEqualTo("stop_sequence");
assertThat(response.stop()).isEqualTo("\n\nHuman:");
assertThat(response.amazonBedrockInvocationMetrics()).isNull();
logger.info("" + response);
}
@Test
public void chatCompletionStream() {
AnthropicChatRequest request = AnthropicChatRequest
.builder(String.format(AnthropicChatBedrockApi.PROMPT_TEMPLATE, "Name 3 famous pirates"))
.withTemperature(0.8f)
.withMaxTokensToSample(300)
.withTopK(10)
.withStopSequences(List.of("\n\nHuman:"))
.build();
Flux<AnthropicChatResponse> responseStream = anthropicChatApi.chatCompletionStream(request);
List<AnthropicChatResponse> responses = responseStream.collectList().block();
assertThat(responses).isNotNull();
assertThat(responses).hasSizeGreaterThan(10);
assertThat(responses.stream().map(AnthropicChatResponse::completion).collect(Collectors.joining()))
.contains("Blackbeard");
}
}
| [
"org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id"
] | [((1873, 1906), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((1960, 1981), 'software.amazon.awssdk.regions.Region.US_WEST_2.id')] |
package org.springframework.ai.aot.test.milvus;
import java.util.List;
import java.util.Map;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MilvusVectorStoreApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MilvusVectorStoreApplication.class)
.web(WebApplicationType.NONE)
.run(args);
}
@Bean
ApplicationRunner applicationRunner(VectorStore vectorStore, EmbeddingClient embeddingClient) {
return args -> {
List<Document> documents = List.of(
new Document(
"Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!",
Map.of("meta1", "meta1")),
new Document("The World is Big and Salvation Lurks Around the Corner"),
new Document("You walk forward facing the past and you turn back toward the future.",
Map.of("meta2", "meta2")));
// Add the documents to PGVector
vectorStore.add(documents);
Thread.sleep(5000);
// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5));
System.out.println("RESULTS: " + results);};
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1547, 1588), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
/*
* 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.autoconfigure.bedrock.jurassic2;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties;
import org.springframework.ai.autoconfigure.bedrock.jurrasic2.BedrockAi21Jurassic2ChatAutoConfiguration;
import org.springframework.ai.autoconfigure.bedrock.jurrasic2.BedrockAi21Jurassic2ChatProperties;
import org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatClient;
import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import software.amazon.awssdk.regions.Region;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Ahmed Yousri
* @since 1.0.0
*/
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
public class BedrockAi21Jurassic2ChatAutoConfigurationIT {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.jurassic2.chat.enabled=true",
"spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"),
"spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"),
"spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(),
"spring.ai.bedrock.jurassic2.chat.model="
+ Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id(),
"spring.ai.bedrock.jurassic2.chat.options.temperature=0.5",
"spring.ai.bedrock.jurassic2.chat.options.maxGenLen=500")
.withConfiguration(AutoConfigurations.of(BedrockAi21Jurassic2ChatAutoConfiguration.class));
private final Message systemMessage = new SystemPromptTemplate("""
You are a helpful AI assistant. Your name is {name}.
You are an AI assistant that helps people find information.
Your name is {name}
You should reply to the user's request with your name and also in the style of a {voice}.
""").createMessage(Map.of("name", "Bob", "voice", "pirate"));
private final UserMessage userMessage = new UserMessage(
"Tell me about 3 famous pirates from the Golden Age of Piracy and why they did.");
@Test
public void chatCompletion() {
contextRunner.run(context -> {
BedrockAi21Jurassic2ChatClient ai21Jurassic2ChatClient = context
.getBean(BedrockAi21Jurassic2ChatClient.class);
ChatResponse response = ai21Jurassic2ChatClient.call(new Prompt(List.of(userMessage, systemMessage)));
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
});
}
@Test
public void propertiesTest() {
new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.jurassic2.chat.enabled=true",
"spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY",
"spring.ai.bedrock.jurassic2.chat.model=MODEL_XYZ",
"spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(),
"spring.ai.bedrock.jurassic2.chat.options.temperature=0.55",
"spring.ai.bedrock.jurassic2.chat.options.maxTokens=123")
.withConfiguration(AutoConfigurations.of(BedrockAi21Jurassic2ChatAutoConfiguration.class))
.run(context -> {
var chatProperties = context.getBean(BedrockAi21Jurassic2ChatProperties.class);
var awsProperties = context.getBean(BedrockAwsConnectionProperties.class);
assertThat(chatProperties.isEnabled()).isTrue();
assertThat(awsProperties.getRegion()).isEqualTo(Region.US_EAST_1.id());
assertThat(chatProperties.getOptions().getTemperature()).isEqualTo(0.55f);
assertThat(chatProperties.getOptions().getMaxTokens()).isEqualTo(123);
assertThat(chatProperties.getModel()).isEqualTo("MODEL_XYZ");
assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY");
assertThat(awsProperties.getSecretKey()).isEqualTo("SECRET_KEY");
});
}
@Test
public void chatCompletionDisabled() {
// It is disabled by default
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(BedrockAi21Jurassic2ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockAi21Jurassic2ChatProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockAi21Jurassic2ChatClient.class)).isEmpty();
});
// Explicitly enable the chat auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.jurassic2.chat.enabled=true")
.withConfiguration(AutoConfigurations.of(BedrockAi21Jurassic2ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockAi21Jurassic2ChatProperties.class)).isNotEmpty();
assertThat(context.getBeansOfType(BedrockAi21Jurassic2ChatClient.class)).isNotEmpty();
});
// Explicitly disable the chat auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.jurassic2.chat.enabled=false")
.withConfiguration(AutoConfigurations.of(BedrockAi21Jurassic2ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockAi21Jurassic2ChatProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockAi21Jurassic2ChatClient.class)).isEmpty();
});
}
}
| [
"org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id"
] | [((2424, 2445), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2501, 2573), 'org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id'), ((4043, 4064), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((4579, 4600), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')] |
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai.chat;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.metadata.*;
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;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/**
* @author John Blum
* @author Christian Tzolov
* @since 0.7.0
*/
@RestClientTest(OpenAiChatClientWithChatResponseMetadataTests.Config.class)
public class OpenAiChatClientWithChatResponseMetadataTests {
private static String TEST_API_KEY = "sk-1234567890";
@Autowired
private OpenAiChatClient openAiChatClient;
@Autowired
private MockRestServiceServer server;
@AfterEach
void resetMockServer() {
server.reset();
}
@Test
void aiResponseContainsAiMetadata() {
prepareMock();
Prompt prompt = new Prompt("Reach for the sky.");
ChatResponse response = this.openAiChatClient.call(prompt);
assertThat(response).isNotNull();
ChatResponseMetadata chatResponseMetadata = response.getMetadata();
assertThat(chatResponseMetadata).isNotNull();
Usage usage = chatResponseMetadata.getUsage();
assertThat(usage).isNotNull();
assertThat(usage.getPromptTokens()).isEqualTo(9L);
assertThat(usage.getGenerationTokens()).isEqualTo(12L);
assertThat(usage.getTotalTokens()).isEqualTo(21L);
RateLimit rateLimit = chatResponseMetadata.getRateLimit();
Duration expectedRequestsReset = Duration.ofDays(2L)
.plus(Duration.ofHours(16L))
.plus(Duration.ofMinutes(15))
.plus(Duration.ofSeconds(29L));
Duration expectedTokensReset = Duration.ofHours(27L)
.plus(Duration.ofSeconds(55L))
.plus(Duration.ofMillis(451L));
assertThat(rateLimit).isNotNull();
assertThat(rateLimit.getRequestsLimit()).isEqualTo(4000L);
assertThat(rateLimit.getRequestsRemaining()).isEqualTo(999);
assertThat(rateLimit.getRequestsReset()).isEqualTo(expectedRequestsReset);
assertThat(rateLimit.getTokensLimit()).isEqualTo(725_000L);
assertThat(rateLimit.getTokensRemaining()).isEqualTo(112_358L);
assertThat(rateLimit.getTokensReset()).isEqualTo(expectedTokensReset);
PromptMetadata promptMetadata = response.getMetadata().getPromptMetadata();
assertThat(promptMetadata).isNotNull();
assertThat(promptMetadata).isEmpty();
response.getResults().forEach(generation -> {
ChatGenerationMetadata chatGenerationMetadata = generation.getMetadata();
assertThat(chatGenerationMetadata).isNotNull();
assertThat(chatGenerationMetadata.getFinishReason()).isEqualTo("STOP");
assertThat(chatGenerationMetadata.<Object>getContentFilterMetadata()).isNull();
});
}
private void prepareMock() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName(), "4000");
httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName(), "999");
httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName(), "2d16h15m29s");
httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName(), "725000");
httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName(), "112358");
httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName(), "27h55s451ms");
server.expect(requestTo("/v1/chat/completions"))
.andExpect(method(HttpMethod.POST))
.andExpect(header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_API_KEY))
.andRespond(withSuccess(getJson(), MediaType.APPLICATION_JSON).headers(httpHeaders));
}
private String getJson() {
return """
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"model": "gpt-3.5-turbo-0613",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "I surrender!"
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}
""";
}
@SpringBootConfiguration
static class Config {
@Bean
public OpenAiApi chatCompletionApi(RestClient.Builder builder) {
return new OpenAiApi("", TEST_API_KEY, builder);
}
@Bean
public OpenAiChatClient openAiClient(OpenAiApi openAiApi) {
return new OpenAiChatClient(openAiApi);
}
}
}
| [
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName"
] | [((3142, 3260), 'java.time.Duration.ofDays'), ((3142, 3226), 'java.time.Duration.ofDays'), ((3142, 3193), 'java.time.Duration.ofDays'), ((3296, 3385), 'java.time.Duration.ofHours'), ((3296, 3351), 'java.time.Duration.ofHours'), ((4430, 4486), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName'), ((4515, 4575), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName'), ((4603, 4659), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName'), ((4695, 4749), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName'), ((4780, 4838), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName'), ((4869, 4923), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName')] |
/*
* 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.autoconfigure.mistralai.tool;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonProperty;
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.autoconfigure.openai.OpenAiAutoConfiguration;
import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.mistralai.api.MistralAiApi;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Same test as {@link PaymentStatusBeanIT.java} but using {@link OpenAiChatClient} for
* Mistral AI Function Calling implementation.
*
* @author Christian Tzolov
*/
@EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".*")
class PaymentStatusBeanOpenAiIT {
private final Logger logger = LoggerFactory.getLogger(PaymentStatusBeanIT.class);
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.ai.openai.apiKey=" + System.getenv("MISTRAL_AI_API_KEY"),
"spring.ai.openai.chat.base-url=https://api.mistral.ai")
.withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class,
RestClientAutoConfiguration.class, OpenAiAutoConfiguration.class))
.withUserConfiguration(Config.class);
@Test
void functionCallTest() {
contextRunner
.withPropertyValues("spring.ai.openai.chat.options.model=" + MistralAiApi.ChatModel.SMALL.getValue())
.run(context -> {
OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class);
ChatResponse response = chatClient
.call(new Prompt(List.of(new UserMessage("What's the status of my transaction with id T1001?")),
OpenAiChatOptions.builder()
.withFunction("retrievePaymentStatus")
.withFunction("retrievePaymentDate")
.build()));
logger.info("Response: {}", response);
assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("T1001");
assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("paid");
});
}
// Assuming we have the following data
public static final Map<String, StatusDate> DATA = Map.of("T1001", new StatusDate("Paid", "2021-10-05"), "T1002",
new StatusDate("Unpaid", "2021-10-06"), "T1003", new StatusDate("Paid", "2021-10-07"), "T1004",
new StatusDate("Paid", "2021-10-05"), "T1005", new StatusDate("Pending", "2021-10-08"));
record StatusDate(String status, String date) {
}
@Configuration
static class Config {
public record Transaction(@JsonProperty(required = true, value = "transaction_id") String transactionId) {
}
public record Status(@JsonProperty(required = true, value = "status") String status) {
}
public record Date(@JsonProperty(required = true, value = "date") String date) {
}
@Bean
@Description("Get payment status of a transaction")
public Function<Transaction, Status> retrievePaymentStatus() {
return (transaction) -> new Status(DATA.get(transaction.transactionId).status());
}
@Bean
@Description("Get payment date of a transaction")
public Function<Transaction, Date> retrievePaymentDate() {
return (transaction) -> new Date(DATA.get(transaction.transactionId).date());
}
}
} | [
"org.springframework.ai.openai.OpenAiChatOptions.builder",
"org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue"
] | [((2837, 2876), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue'), ((3124, 3260), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3124, 3243), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3124, 3198), 'org.springframework.ai.openai.OpenAiChatOptions.builder')] |
/*
* 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.autoconfigure.vectorstore.azure;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.transformers.TransformersEmbeddingClient;
import org.springframework.ai.vectorstore.azure.AzureVectorStore;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
/**
* @author Christian Tzolov
*/
@EnabledIfEnvironmentVariable(named = "AZURE_AI_SEARCH_API_KEY", matches = ".+")
@EnabledIfEnvironmentVariable(named = "AZURE_AI_SEARCH_ENDPOINT", matches = ".+")
public class AzureVectorStoreAutoConfigurationIT {
List<Document> documents = List.of(
new Document("1", getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")),
new Document("2", getText("classpath:/test/data/time.shelter.txt"), Map.of()),
new Document("3", getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad")));
public static String getText(String uri) {
var resource = new DefaultResourceLoader().getResource(uri);
try {
return resource.getContentAsString(StandardCharsets.UTF_8);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AzureVectorStoreAutoConfiguration.class))
.withUserConfiguration(Config.class)
.withPropertyValues("spring.ai.vectorstore.azure.apiKey=" + System.getenv("AZURE_AI_SEARCH_API_KEY"),
"spring.ai.vectorstore.azure.url=" + System.getenv("AZURE_AI_SEARCH_ENDPOINT"));
@BeforeAll
public static void beforeAll() {
Awaitility.setDefaultPollInterval(2, TimeUnit.SECONDS);
Awaitility.setDefaultPollDelay(Duration.ZERO);
Awaitility.setDefaultTimeout(Duration.ofMinutes(1));
}
@Test
public void addAndSearchTest() {
contextRunner
.withPropertyValues("spring.ai.vectorstore.azure.indexName=my_test_index",
"spring.ai.vectorstore.azure.defaultTopK=6",
"spring.ai.vectorstore.azure.defaultSimilarityThreshold=0.75")
.run(context -> {
var properties = context.getBean(AzureVectorStoreProperties.class);
assertThat(properties.getUrl()).isEqualTo(System.getenv("AZURE_AI_SEARCH_ENDPOINT"));
assertThat(properties.getApiKey()).isEqualTo(System.getenv("AZURE_AI_SEARCH_API_KEY"));
assertThat(properties.getDefaultTopK()).isEqualTo(6);
assertThat(properties.getDefaultSimilarityThreshold()).isEqualTo(0.75);
assertThat(properties.getIndexName()).isEqualTo("my_test_index");
VectorStore vectorStore = context.getBean(VectorStore.class);
assertThat(vectorStore).isInstanceOf(AzureVectorStore.class);
vectorStore.add(documents);
Awaitility.await().until(() -> {
return vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1));
}, hasSize(1));
List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1));
assertThat(results).hasSize(1);
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId());
assertThat(resultDoc.getContent()).contains(
"Spring AI provides abstractions that serve as the foundation for developing AI applications.");
assertThat(resultDoc.getMetadata()).hasSize(2);
assertThat(resultDoc.getMetadata()).containsKeys("spring", "distance");
// Remove all documents from the store
vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList());
Awaitility.await().until(() -> {
return vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1));
}, hasSize(0));
});
}
@Configuration(proxyBeanMethods = false)
static class Config {
@Bean
public EmbeddingClient embeddingClient() {
return new TransformersEmbeddingClient();
}
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((4163, 4299), 'org.awaitility.Awaitility.await'), ((4237, 4278), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4360, 4401), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4959, 5095), 'org.awaitility.Awaitility.await'), ((5033, 5074), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package org.springframework.ai.aot.test.milvus;
import java.util.List;
import java.util.Map;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MilvusVectorStoreApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(MilvusVectorStoreApplication.class)
.web(WebApplicationType.NONE)
.run(args);
}
@Bean
ApplicationRunner applicationRunner(VectorStore vectorStore, EmbeddingClient embeddingClient) {
return args -> {
List<Document> documents = List.of(
new Document(
"Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!",
Map.of("meta1", "meta1")),
new Document("The World is Big and Salvation Lurks Around the Corner"),
new Document("You walk forward facing the past and you turn back toward the future.",
Map.of("meta2", "meta2")));
// Add the documents to PGVector
vectorStore.add(documents);
Thread.sleep(5000);
// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5));
System.out.println("RESULTS: " + results);};
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1547, 1588), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package com.thomasvitale.ai.spring;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
class ChatService {
private final ChatClient chatClient;
private final SimpleVectorStore vectorStore;
ChatService(ChatClient chatClient, SimpleVectorStore vectorStore) {
this.chatClient = chatClient;
this.vectorStore = vectorStore;
}
AssistantMessage chatWithDocument(String message) {
var systemPromptTemplate = new SystemPromptTemplate("""
Answer questions given the context information below (DOCUMENTS section) and no prior knowledge,
but act as if you knew this information innately. If the answer is not found in the DOCUMENTS section,
simply state that you don't know the answer. In the answer, include the source file name from which
the context information is extracted from.
DOCUMENTS:
{documents}
""");
List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2));
String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator()));
Map<String,Object> model = Map.of("documents", documents);
var systemMessage = systemPromptTemplate.createMessage(model);
var userMessage = new UserMessage(message);
var prompt = new Prompt(List.of(systemMessage, userMessage));
var chatResponse = chatClient.call(prompt);
return chatResponse.getResult().getOutput();
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1601, 1641), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package com.example.springai.aoai.mapper;
import com.example.springai.aoai.config.SpringMapperConfig;
import com.example.springai.aoai.dto.ChatMessageDto;
import org.mapstruct.Mapper;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import java.util.List;
import java.util.stream.Collectors;
/**
* Mapper for {@link org.springframework.ai.chat.messages.Message}
*/
@Mapper(config = SpringMapperConfig.class)
public abstract class ChatMessageMapper {
/**
* Convert {@link com.example.springai.aoai.dto.ChatMessageDto} to {@link org.springframework.ai.chat.messages.Message}
*
* @param chatMessageDto chatMessageDto to convert
* @return Message instance of AssistantMessage or UserMessage
*/
public Message toMessage(ChatMessageDto chatMessageDto) {
if (MessageType.ASSISTANT.getValue().equalsIgnoreCase(chatMessageDto.getRole())) {
return new AssistantMessage(chatMessageDto.getContent());
} else if (MessageType.USER.getValue().equalsIgnoreCase(chatMessageDto.getRole())) {
return new UserMessage(chatMessageDto.getContent());
} else {
throw new RuntimeException("Invalid message type");
}
}
/**
* Convert list of {@link com.example.springai.aoai.dto.ChatMessageDto} to list of {@link org.springframework.ai.chat.messages.Message}
*
* @param chatMessageDtos list of chatMessageDto to convert
* @return list of {@link org.springframework.ai.chat.messages.Message}
*/
public List<Message> toMessage(List<ChatMessageDto> chatMessageDtos) {
return chatMessageDtos.stream()
.map(chatMessageDto -> {
return toMessage(chatMessageDto);
})
.collect(Collectors.toList());
}
}
| [
"org.springframework.ai.chat.messages.MessageType.USER.getValue",
"org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue"
] | [((978, 1053), 'org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue'), ((978, 1010), 'org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue'), ((1146, 1216), 'org.springframework.ai.chat.messages.MessageType.USER.getValue'), ((1146, 1173), 'org.springframework.ai.chat.messages.MessageType.USER.getValue')] |
package nl.pieterse.ai;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.prompt.Prompt;
import org.springframework.ai.prompt.SystemPromptTemplate;
import org.springframework.ai.prompt.messages.UserMessage;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.retriever.VectorStoreRetriever;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.PgVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@SpringBootApplication
public class AiApplication {
public static void main(String[] args) {
SpringApplication.run(AiApplication.class, args);
}
@Bean
VectorStore vectorStore(EmbeddingClient ec,
JdbcTemplate t) {
return new PgVectorStore(t, ec);
}
@Bean
VectorStoreRetriever vectorStoreRetriever(VectorStore vs) {
return new VectorStoreRetriever(vs, 4, 0.75);
}
@Bean
TokenTextSplitter tokenTextSplitter() {
return new TokenTextSplitter();
}
static void init(VectorStore vectorStore, JdbcTemplate template, Resource pdfResource)
throws Exception {
System.out.println("Deleting all vectors from the vector store...");
template.update("delete from vector_store");
var config = PdfDocumentReaderConfig.builder()
.withPageExtractedTextFormatter(new ExtractedTextFormatter.Builder().withNumberOfBottomTextLinesToDelete(3)
.withNumberOfTopPagesToSkipBeforeDelete(1)
.build())
.withPagesPerDocument(1)
.build();
var pdfReader = new PagePdfDocumentReader(pdfResource, config);
var textSplitter = new TokenTextSplitter();
System.out.println("Storing vectors in the vector store...");
vectorStore.accept(textSplitter.apply(pdfReader.get()));
}
@Bean
ApplicationRunner applicationRunner(
ChatBot chatBot,
VectorStore vectorStore,
JdbcTemplate template,
@Value("file:///Users/susannepieterse/Downloads/Handreiking-2023+Bescherm+domeinnamen+tegen+phishing+2.0.pdf") Resource pdfResource) {
return args -> {
System.out.println("Beginning the chat with Ollama...");
init(vectorStore, template, pdfResource);
var response = chatBot.chat("Wat adviseert het NCSC om te doen tegen phishing?");
System.out.println(Map.of("response", response));
System.out.println("Chat with Ollama complete.");
};
}
}
@Component
class ChatBot {
private final String templatePrompt = """
Je assisteert met vragen over de bescherming tegen phishing.
Gebruik de informatie uit de sectie DOCUMENTS hieronder om te accurate antwoorden te geven.
Als je het niet zeker weet, geef dan aan dat je het niet weet.
Beantwoord de vragen in het Nederlands.
DOCUMENTS:
{documents}
""";
private final OllamaChatClient chatClient;
private final VectorStoreRetriever vsr;
ChatBot(OllamaChatClient chatClient, VectorStoreRetriever vsr) {
this.chatClient = chatClient;
this.vsr = vsr;
}
public String chat (String message) {
var listOfSimilarDocuments = vsr.retrieve(message);
var documents = listOfSimilarDocuments
.stream()
.map(Document::getContent)
.collect(Collectors.joining(System.lineSeparator()));
var systemMessage = new SystemPromptTemplate(this.templatePrompt)
.createMessage(Map.of("documents", documents));
var userMessage = new UserMessage(message);
var prompt = new Prompt(List.of(systemMessage, userMessage));
var aiResponse = chatClient.generate(prompt);
return aiResponse.getGeneration().getContent();
}
}
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder"
] | [((2127, 2451), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2127, 2426), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2127, 2385), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')] |
package net.youssfi.promptengineeringspringai.web;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.awt.*;
import java.util.Map;
@RestController
public class ChatGPTRestController {
private OpenAiChatClient openAiChatClient;
public ChatGPTRestController(OpenAiChatClient openAiChatClient) {
this.openAiChatClient = openAiChatClient;
}
@GetMapping("/open-ai/generate")
public Map generate(@RequestParam(name = "message", defaultValue = "tell me a joke") String message){
return Map.of("response",openAiChatClient.call(message));
}
@GetMapping("/open-ai/generate2")
public ChatResponse generate2(@RequestParam(name = "message", defaultValue = "tell me a joke") String message){
ChatResponse chatResponse = openAiChatClient.call(
new Prompt(message, OpenAiChatOptions.builder()
.withModel("gpt-4")
.withTemperature(Float.valueOf(0))
.withMaxTokens(400)
.build())
);
return chatResponse;
}
@GetMapping(path="/open-ai/generateStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return openAiChatClient.stream(prompt);
}
}
| [
"org.springframework.ai.openai.OpenAiChatOptions.builder"
] | [((1318, 1525), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1318, 1492), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1318, 1448), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1318, 1389), 'org.springframework.ai.openai.OpenAiChatOptions.builder')] |
package com.ea.ai.rag.dms.infrastructure.repository;
import com.ea.ai.rag.dms.domain.dto.Document;
import com.ea.ai.rag.dms.domain.vo.ai.Answer;
import com.ea.ai.rag.dms.domain.vo.ai.Question;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.transformer.splitter.TextSplitter;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class DocumentAiRepository {
private final VectorStore vectorStore;
private final PromptTemplate promptTemplate;
private final ChatClient aiChatClient;
public DocumentAiRepository(VectorStore vectorStore, PromptTemplate promptTemplate, ChatClient aiChatClient) {
this.vectorStore = vectorStore;
this.promptTemplate = promptTemplate;
this.aiChatClient = aiChatClient;
}
public void addDocumentToVectorStore(Document document) {
ByteArrayResource byteArrayResource = new ByteArrayResource(document.getFile(), document.getDocumentName());
TikaDocumentReader tikaDocumentReader = new TikaDocumentReader(byteArrayResource);
List<org.springframework.ai.document.Document> documents = tikaDocumentReader.get();
TextSplitter textSplitter = new TokenTextSplitter();
List<org.springframework.ai.document.Document> splitDocuments = textSplitter.apply(documents);
vectorStore.add(splitDocuments);
}
public Answer askQuestion(Question question) {
List<org.springframework.ai.document.Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(question.question()).withTopK(2));
if (similarDocuments != null && !similarDocuments.isEmpty()) {
List<String> contentList = similarDocuments.stream().map(org.springframework.ai.document.Document::getContent).toList();
Map<String, Object> promptParameters = new HashMap<>();
promptParameters.put("input", question.question());
promptParameters.put("documents", String.join("\n", contentList));
Prompt prompt = promptTemplate.create(promptParameters);
ChatResponse response = aiChatClient.call(prompt);
return new Answer(response.getResult().getOutput().getContent());
} else {
return new Answer("Sorry, I don't have an answer for that question");
}
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((2048, 2100), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package org.springframework.ai.operator;
import org.slf4j.Logger;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.memory.Memory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DefaultAiOperator implements AiOperator {
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultAiOperator.class);
private final ChatClient aiClient;
private PromptTemplate promptTemplate;
private VectorStore vectorStore;
private String vectorStoreKey;
private String inputParameterName = "input";
private String historyParameterName = "history";
private int k = 2;
private Memory memory;
protected DefaultAiOperator(ChatClient aiClient, PromptTemplate promptTemplate) {
this.aiClient = aiClient;
this.promptTemplate = promptTemplate;
}
public AiOperator promptTemplate(String promptTemplate) {
this.promptTemplate = new PromptTemplate(promptTemplate);
return this;
}
public AiOperator vectorStore(VectorStore vectorStore) {
this.vectorStore = vectorStore;
return this;
}
public AiOperator vectorStoreKey(String vectorStoreKey) {
this.vectorStoreKey = vectorStoreKey;
return this;
}
public AiOperator conversationMemory(Memory memory) {
this.memory = memory;
return this;
}
public AiOperator inputParameterName(String inputParameterName) {
this.inputParameterName = inputParameterName;
return this;
}
public AiOperator historyParameterName(String historyParameterName) {
this.historyParameterName = historyParameterName;
return this;
}
public AiOperator k(int k) {
this.k = k;
return this;
}
@Override
public String generate() {
return generate(Map.of());
}
@Override
public String generate(Map<String, Object> parameters) {
Map<String, Object> resolvedParameters = new HashMap<>(parameters);
if (vectorStore != null) {
String input = memory != null ? generateStandaloneQuestion(parameters)
: parameters.get(inputParameterName).toString();
LOG.info("input: {}", input);
List<Document> documents = vectorStore.similaritySearch(SearchRequest.query(input).withTopK(k));
List<String> contentList = documents.stream().map(doc -> {
return doc.getContent() + "\n";
}).toList();
resolvedParameters.put(inputParameterName, input);
resolvedParameters.put(vectorStoreKey, contentList);
}
else {
resolvedParameters = preProcess(resolvedParameters);
}
PromptTemplate promptTemplateCopy = new PromptTemplate(promptTemplate.getTemplate());
String prompt = promptTemplateCopy.render(resolvedParameters).trim();
LOG.debug("Submitting prompt: {}", prompt);
ChatResponse aiResponse = aiClient.call(new Prompt(prompt));
logUsage(aiResponse);
String generationResponse = aiResponse.getResult().getOutput().getContent();
// post-process memory
postProcess(parameters, aiResponse);
return generationResponse;
}
private void logUsage(ChatResponse aiResponse) {
Usage usage = aiResponse.getMetadata().getUsage();
LOG.info("Usage: Prompt Tokens: {}; Generation Tokens: {}; Total Tokens: {}", usage.getPromptTokens(), usage.getGenerationTokens(), usage.getTotalTokens());
}
private String generateStandaloneQuestion(Map<String, Object> parameters) {
Map<String, Object> resolvedParameters = new HashMap<>(parameters);
resolvedParameters = preProcess(resolvedParameters);
PromptTemplate standalonePromptTemplate = new PromptTemplate(
DefaultPromptTemplateStrings.STANDALONE_QUESTION_PROMPT);
String prompt = standalonePromptTemplate.render(resolvedParameters);
LOG.debug("Submitting standalone question prompt: {}", prompt);
ChatResponse aiResponse = aiClient.call(new Prompt(prompt));
logUsage(aiResponse);
return aiResponse.getResult().getOutput().getContent();
}
@Override
public void clear() {
if (memory != null) {
memory.clear();
}
}
private Map<String, Object> preProcess(Map<String, Object> parameters) {
Map<String, Object> combinedParameters = new HashMap<>(parameters);
if (memory != null) {
combinedParameters.putAll(memory.load(parameters));
}
return combinedParameters;
}
private void postProcess(Map<String, Object> parameters, ChatResponse aiResponse) {
if (memory != null) {
memory.save(parameters, Map.of(historyParameterName, aiResponse.getResult().getOutput().getContent()));
}
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((2464, 2502), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
/*
* 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.autoconfigure.watsonxai;
import org.springframework.ai.watsonx.WatsonxAiChatOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Chat properties for Watsonx.AI Chat.
*
* @author Christian Tzolov
* @since 1.0.0
*/
@ConfigurationProperties(WatsonxAiChatProperties.CONFIG_PREFIX)
public class WatsonxAiChatProperties {
public static final String CONFIG_PREFIX = "spring.ai.watsonx.ai.chat";
/**
* Enable Watsonx.AI chat client.
*/
private boolean enabled = true;
/**
* Watsonx AI generative options.
*/
@NestedConfigurationProperty
private WatsonxAiChatOptions options = WatsonxAiChatOptions.builder()
.withTemperature(0.7f)
.withTopP(1.0f)
.withTopK(50)
.withDecodingMethod("greedy")
.withMaxNewTokens(20)
.withMinNewTokens(0)
.withRepetitionPenalty(1.0f)
.build();
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public WatsonxAiChatOptions getOptions() {
return this.options;
}
public void setOptions(WatsonxAiChatOptions options) {
this.options = options;
}
}
| [
"org.springframework.ai.watsonx.WatsonxAiChatOptions.builder"
] | [((1360, 1570), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1360, 1559), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1360, 1528), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1360, 1505), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1360, 1481), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1360, 1449), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1360, 1433), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1360, 1415), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder')] |
/*
* Copyright 2023-2023 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 com.example.spring.ai.fintech;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.reader.pdf.layout.PageExtractedTextFormatter;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
*
* @author Christian Tzolov
*/
public class DataLoadingService implements InitializingBean {
private Resource pdfResource;
private VectorStore vectorStore;
@Value("${spring.ai.openai.test.skip-loading}")
private Boolean skipLoading = false;
public DataLoadingService(Resource pdfResource, VectorStore vectorStore) {
Assert.notNull(pdfResource, "PDF Resource must not be null.");
Assert.notNull(vectorStore, "VectorStore must not be null.");
this.pdfResource = pdfResource;
this.vectorStore = vectorStore;
}
@Override
public void afterPropertiesSet() throws Exception {
if (this.skipLoading) {
return;
}
PagePdfDocumentReader pdfReader = new PagePdfDocumentReader(
this.pdfResource,
PdfDocumentReaderConfig.builder()
.withPageExtractedTextFormatter(PageExtractedTextFormatter.builder()
.withNumberOfBottomTextLinesToDelete(3)
.withNumberOfTopPagesToSkipBeforeDelete(1)
// .withLeftAlignment(true)
.build())
.withPagesPerDocument(1)
.build());
var textSplitter = new TokenTextSplitter();
this.vectorStore.accept(
textSplitter.apply(
pdfReader.get()));
System.out.println("Exit loader");
}
}
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder",
"org.springframework.ai.reader.pdf.layout.PageExtractedTextFormatter.builder"
] | [((1936, 2243), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1936, 2228), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1936, 2197), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((2008, 2196), 'org.springframework.ai.reader.pdf.layout.PageExtractedTextFormatter.builder'), ((2008, 2143), 'org.springframework.ai.reader.pdf.layout.PageExtractedTextFormatter.builder'), ((2008, 2092), 'org.springframework.ai.reader.pdf.layout.PageExtractedTextFormatter.builder')] |
/*
* 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.autoconfigure.vectorstore.neo4j;
import org.neo4j.driver.Driver;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.Neo4jVectorStore;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* @author Jingzhou Ou
*/
@AutoConfiguration(after = Neo4jAutoConfiguration.class)
@ConditionalOnClass({ Neo4jVectorStore.class, EmbeddingClient.class, Driver.class })
@EnableConfigurationProperties({ Neo4jVectorStoreProperties.class })
public class Neo4jVectorStoreAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public Neo4jVectorStore vectorStore(Driver driver, EmbeddingClient embeddingClient,
Neo4jVectorStoreProperties properties) {
Neo4jVectorStore.Neo4jVectorStoreConfig config = Neo4jVectorStore.Neo4jVectorStoreConfig.builder()
.withDatabaseName(properties.getDatabaseName())
.withEmbeddingDimension(properties.getEmbeddingDimension())
.withDistanceType(properties.getDistanceType())
.withLabel(properties.getLabel())
.withEmbeddingProperty(properties.getEmbeddingProperty())
.withIndexName(properties.getIndexName())
.withIdProperty(properties.getIdProperty())
.withConstraintName(properties.getConstraintName())
.build();
return new Neo4jVectorStore(driver, embeddingClient, config);
}
}
| [
"org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder"
] | [((1774, 2245), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 2233), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 2178), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 2131), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 2086), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 2025), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 1988), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 1937), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 1874), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder'), ((1774, 1823), 'org.springframework.ai.vectorstore.Neo4jVectorStore.Neo4jVectorStoreConfig.builder')] |
/*
* 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.anthropic;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import org.springframework.ai.anthropic.api.AnthropicApi;
import org.springframework.ai.anthropic.api.AnthropicApi.ChatCompletion;
import org.springframework.ai.anthropic.api.AnthropicApi.RequestMessage;
import org.springframework.ai.anthropic.api.AnthropicApi.MediaContent;
import org.springframework.ai.anthropic.api.AnthropicApi.ChatCompletionRequest;
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;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* The {@link ChatClient} implementation for the Anthropic service.
*
* @author Christian Tzolov
* @since 1.0.0
*/
public class AnthropicChatClient implements ChatClient, StreamingChatClient {
private static final Logger logger = LoggerFactory.getLogger(AnthropicChatClient.class);
public static final String DEFAULT_MODEL_NAME = AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue();
public static final Integer DEFAULT_MAX_TOKENS = 500;
public static final Float DEFAULT_TEMPERATURE = 0.8f;
/**
* The lower-level API for the Anthropic service.
*/
public final AnthropicApi anthropicApi;
/**
* The default options used for the chat completion requests.
*/
private AnthropicChatOptions defaultOptions;
/**
* The retry template used to retry the OpenAI API calls.
*/
public final RetryTemplate retryTemplate;
/**
* Construct a new {@link AnthropicChatClient} instance.
* @param anthropicApi the lower-level API for the Anthropic service.
*/
public AnthropicChatClient(AnthropicApi anthropicApi) {
this(anthropicApi,
AnthropicChatOptions.builder()
.withModel(DEFAULT_MODEL_NAME)
.withMaxTokens(DEFAULT_MAX_TOKENS)
.withTemperature(DEFAULT_TEMPERATURE)
.build());
}
/**
* Construct a new {@link AnthropicChatClient} 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) {
this(anthropicApi, defaultOptions, RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
/**
* Construct a new {@link AnthropicChatClient} 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,
RetryTemplate retryTemplate) {
Assert.notNull(anthropicApi, "AnthropicApi must not be null");
Assert.notNull(defaultOptions, "DefaultOptions must not be null");
Assert.notNull(retryTemplate, "RetryTemplate must not be null");
this.anthropicApi = anthropicApi;
this.defaultOptions = defaultOptions;
this.retryTemplate = retryTemplate;
}
@Override
public ChatResponse call(Prompt prompt) {
ChatCompletionRequest request = createRequest(prompt, false);
return this.retryTemplate.execute(ctx -> {
ResponseEntity<ChatCompletion> completionEntity = this.anthropicApi.chatCompletionEntity(request);
return toChatResponse(completionEntity.getBody());
});
}
@Override
public Flux<ChatResponse> stream(Prompt prompt) {
ChatCompletionRequest request = createRequest(prompt, true);
Flux<StreamResponse> response = this.anthropicApi.chatCompletionStream(request);
AtomicReference<ChatCompletionBuilder> chatCompletionReference = new AtomicReference<>();
// https://docs.anthropic.com/claude/reference/messages-streaming
return response.map(chunk -> {
if (chunk.type().equals("message_start")) {
chatCompletionReference.set(new ChatCompletionBuilder());
chatCompletionReference.get()
.withType(chunk.type())
.withId(chunk.message().id())
.withRole(chunk.message().role())
.withModel(chunk.message().model())
.withUsage(chunk.message().usage())
.withContent(new ArrayList<>());
}
else if (chunk.type().equals("content_block_start")) {
var content = new MediaContent(chunk.contentBlock().type(), null, chunk.contentBlock().text(),
chunk.index());
chatCompletionReference.get().withType(chunk.type()).withContent(List.of(content));
}
else if (chunk.type().equals("content_block_delta")) {
var content = new MediaContent("text_delta", null, (String) chunk.delta().get("text"), chunk.index());
chatCompletionReference.get().withType(chunk.type()).withContent(List.of(content));
}
else if (chunk.type().equals("message_delta")) {
ChatCompletion delta = ModelOptionsUtils.mapToClass(chunk.delta(), ChatCompletion.class);
chatCompletionReference.get().withType(chunk.type());
if (delta.id() != null) {
chatCompletionReference.get().withId(delta.id());
}
if (delta.role() != null) {
chatCompletionReference.get().withRole(delta.role());
}
if (delta.model() != null) {
chatCompletionReference.get().withModel(delta.model());
}
if (delta.usage() != null) {
chatCompletionReference.get().withUsage(delta.usage());
}
if (delta.content() != null) {
chatCompletionReference.get().withContent(delta.content());
}
if (delta.stopReason() != null) {
chatCompletionReference.get().withStopReason(delta.stopReason());
}
if (delta.stopSequence() != null) {
chatCompletionReference.get().withStopSequence(delta.stopSequence());
}
}
else {
chatCompletionReference.get().withType(chunk.type()).withContent(List.of());
}
return chatCompletionReference.get().build();
}).map(this::toChatResponse);
}
private ChatResponse toChatResponse(ChatCompletion chatCompletion) {
if (chatCompletion == null) {
logger.warn("Null chat completion returned");
return new ChatResponse(List.of());
}
List<Generation> generations = chatCompletion.content().stream().map(content -> {
return new Generation(content.text(), Map.of())
.withGenerationMetadata(ChatGenerationMetadata.from(chatCompletion.stopReason(), null));
}).toList();
return new ChatResponse(generations, AnthropicChatResponseMetadata.from(chatCompletion));
}
private String fromMediaData(Object mediaData) {
if (mediaData instanceof byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
else if (mediaData instanceof String text) {
return text;
}
else {
throw new IllegalArgumentException("Unsupported media data type: " + mediaData.getClass().getSimpleName());
}
}
ChatCompletionRequest createRequest(Prompt prompt, boolean stream) {
List<RequestMessage> userMessages = prompt.getInstructions()
.stream()
.filter(m -> m.getMessageType() != MessageType.SYSTEM)
.map(m -> {
List<MediaContent> contents = new ArrayList<>(List.of(new MediaContent(m.getContent())));
if (!CollectionUtils.isEmpty(m.getMedia())) {
List<MediaContent> mediaContent = m.getMedia()
.stream()
.map(media -> new MediaContent(media.getMimeType().toString(),
this.fromMediaData(media.getData())))
.toList();
contents.addAll(mediaContent);
}
return new RequestMessage(contents, Role.valueOf(m.getMessageType().name()));
})
.toList();
String systemPrompt = prompt.getInstructions()
.stream()
.filter(m -> m.getMessageType() == MessageType.SYSTEM)
.map(m -> m.getContent())
.collect(Collectors.joining(System.lineSeparator()));
ChatCompletionRequest request = new ChatCompletionRequest(this.defaultOptions.getModel(), userMessages,
systemPrompt, this.defaultOptions.getMaxTokens(), this.defaultOptions.getTemperature(), stream);
if (prompt.getOptions() != null) {
if (prompt.getOptions() instanceof ChatOptions runtimeOptions) {
AnthropicChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions,
ChatOptions.class, AnthropicChatOptions.class);
request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, ChatCompletionRequest.class);
}
else {
throw new IllegalArgumentException("Prompt options are not of type ChatOptions: "
+ prompt.getOptions().getClass().getSimpleName());
}
}
if (this.defaultOptions != null) {
request = ModelOptionsUtils.merge(request, this.defaultOptions, ChatCompletionRequest.class);
}
return request;
}
private static class ChatCompletionBuilder {
private String type;
private String id;
private Role role;
private List<MediaContent> content;
private String model;
private String stopReason;
private String stopSequence;
private Usage usage;
public ChatCompletionBuilder() {
}
public ChatCompletionBuilder withType(String type) {
this.type = type;
return this;
}
public ChatCompletionBuilder withId(String id) {
this.id = id;
return this;
}
public ChatCompletionBuilder withRole(Role role) {
this.role = role;
return this;
}
public ChatCompletionBuilder withContent(List<MediaContent> content) {
this.content = content;
return this;
}
public ChatCompletionBuilder withModel(String model) {
this.model = model;
return this;
}
public ChatCompletionBuilder withStopReason(String stopReason) {
this.stopReason = stopReason;
return this;
}
public ChatCompletionBuilder withStopSequence(String stopSequence) {
this.stopSequence = stopSequence;
return this;
}
public ChatCompletionBuilder withUsage(Usage usage) {
this.usage = usage;
return this;
}
public ChatCompletion build() {
return new ChatCompletion(this.id, this.type, this.role, this.content, this.model, this.stopReason,
this.stopSequence, this.usage);
}
}
}
| [
"org.springframework.ai.anthropic.api.AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue"
] | [((2646, 2693), 'org.springframework.ai.anthropic.api.AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue'), ((8083, 8124), 'java.util.Base64.getEncoder')] |
/*
* 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.ollama;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.AbstractEmbeddingClient;
import org.springframework.ai.embedding.Embedding;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.embedding.EmbeddingOptions;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaApi.EmbeddingRequest;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* {@link EmbeddingClient} 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
* Library](https://ollama.ai/library).
*
* Examples of models supported: - Llama 2 (7B parameters, 3.8GB size) - Mistral (7B
* parameters, 4.1GB size)
*
* Please refer to the <a href="https://ollama.ai/">official Ollama website</a> for the
* most up-to-date information on available models.
*
* @author Christian Tzolov
* @since 0.8.0
*/
public class OllamaEmbeddingClient extends AbstractEmbeddingClient {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final OllamaApi ollamaApi;
/**
* Default options to be used for all chat requests.
*/
private OllamaOptions defaultOptions = OllamaOptions.create().withModel(OllamaOptions.DEFAULT_MODEL);
public OllamaEmbeddingClient(OllamaApi ollamaApi) {
this.ollamaApi = ollamaApi;
}
/**
* @deprecated Use {@link OllamaOptions#setModel} instead.
*/
@Deprecated
public OllamaEmbeddingClient withModel(String model) {
this.defaultOptions.setModel(model);
return this;
}
public OllamaEmbeddingClient withDefaultOptions(OllamaOptions options) {
this.defaultOptions = options;
return this;
}
@Override
public List<Double> embed(Document document) {
return embed(document.getContent());
}
@Override
public EmbeddingResponse call(org.springframework.ai.embedding.EmbeddingRequest request) {
Assert.notEmpty(request.getInstructions(), "At least one text is required!");
if (request.getInstructions().size() != 1) {
logger.warn(
"Ollama Embedding does not support batch embedding. Will make multiple API calls to embed(Document)");
}
List<List<Double>> embeddingList = new ArrayList<>();
for (String inputContent : request.getInstructions()) {
var ollamaEmbeddingRequest = ollamaEmbeddingRequest(inputContent, request.getOptions());
OllamaApi.EmbeddingResponse response = this.ollamaApi.embeddings(ollamaEmbeddingRequest);
embeddingList.add(response.embedding());
}
var indexCounter = new AtomicInteger(0);
List<Embedding> embeddings = embeddingList.stream()
.map(e -> new Embedding(e, indexCounter.getAndIncrement()))
.toList();
return new EmbeddingResponse(embeddings);
}
/**
* Package access for testing.
*/
OllamaApi.EmbeddingRequest ollamaEmbeddingRequest(String inputContent, EmbeddingOptions options) {
// runtime options
OllamaOptions runtimeOptions = null;
if (options != null) {
if (options instanceof OllamaOptions ollamaOptions) {
runtimeOptions = ollamaOptions;
}
else {
// currently EmbeddingOptions does not have any portable options to be
// merged.
runtimeOptions = null;
}
}
OllamaOptions mergedOptions = ModelOptionsUtils.merge(runtimeOptions, this.defaultOptions, OllamaOptions.class);
// Override the model.
if (!StringUtils.hasText(mergedOptions.getModel())) {
throw new IllegalArgumentException("Model is not set!");
}
String model = mergedOptions.getModel();
return new EmbeddingRequest(model, inputContent, OllamaOptions.filterNonSupportedFields(mergedOptions.toMap()));
}
} | [
"org.springframework.ai.ollama.api.OllamaOptions.create"
] | [((2325, 2386), 'org.springframework.ai.ollama.api.OllamaOptions.create')] |
/*
* 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.autoconfigure.vectorstore.weaviate;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.WeaviateVectorStore;
import org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig;
import org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* @author Christian Tzolov
* @author Eddú Meléndez
*/
@AutoConfiguration
@ConditionalOnClass({ EmbeddingClient.class, WeaviateVectorStore.class })
@EnableConfigurationProperties({ WeaviateVectorStoreProperties.class })
public class WeaviateVectorStoreAutoConfiguration {
@Bean
@ConditionalOnMissingBean(WeaviateConnectionDetails.class)
public PropertiesWeaviateConnectionDetails weaviateConnectionDetails(WeaviateVectorStoreProperties properties) {
return new PropertiesWeaviateConnectionDetails(properties);
}
@Bean
@ConditionalOnMissingBean
public WeaviateVectorStore vectorStore(EmbeddingClient embeddingClient, WeaviateVectorStoreProperties properties,
WeaviateConnectionDetails connectionDetails) {
WeaviateVectorStoreConfig.Builder configBuilder = WeaviateVectorStore.WeaviateVectorStoreConfig.builder()
.withScheme(properties.getScheme())
.withApiKey(properties.getApiKey())
.withHost(connectionDetails.getHost())
.withHeaders(properties.getHeaders())
.withObjectClass(properties.getObjectClass())
.withFilterableMetadataFields(properties.getFilterField()
.entrySet()
.stream()
.map(e -> new MetadataField(e.getKey(), e.getValue()))
.toList())
.withConsistencyLevel(properties.getConsistencyLevel());
return new WeaviateVectorStore(configBuilder.build(), embeddingClient);
}
private static class PropertiesWeaviateConnectionDetails implements WeaviateConnectionDetails {
private final WeaviateVectorStoreProperties properties;
PropertiesWeaviateConnectionDetails(WeaviateVectorStoreProperties properties) {
this.properties = properties;
}
@Override
public String getHost() {
return this.properties.getHost();
}
}
}
| [
"org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder"
] | [((2137, 2626), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder'), ((2137, 2567), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder'), ((2137, 2402), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder'), ((2137, 2353), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder'), ((2137, 2312), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder'), ((2137, 2270), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder'), ((2137, 2231), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder'), ((2137, 2192), 'org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.builder')] |
/*
* 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.autoconfigure.bedrock.titan;
import org.springframework.ai.bedrock.titan.BedrockTitanEmbeddingClient.InputType;
import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Bedrock Titan Embedding autoconfiguration properties.
*
* @author Christian Tzolov
* @since 0.8.0
*/
@ConfigurationProperties(BedrockTitanEmbeddingProperties.CONFIG_PREFIX)
public class BedrockTitanEmbeddingProperties {
public static final String CONFIG_PREFIX = "spring.ai.bedrock.titan.embedding";
/**
* Enable Bedrock Titan Embedding Client. False by default.
*/
private boolean enabled = false;
/**
* Bedrock Titan Embedding generative name. Defaults to 'amazon.titan-embed-image-v1'.
*/
private String model = TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id();
/**
* Titan Embedding API input types. Could be either text or image (encoded in base64).
* Defaults to {@link InputType#IMAGE}.
*/
private InputType inputType = InputType.IMAGE;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public static String getConfigPrefix() {
return CONFIG_PREFIX;
}
public void setInputType(InputType inputType) {
this.inputType = inputType;
}
public InputType getInputType() {
return inputType;
}
}
| [
"org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id"
] | [((1476, 1521), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id')] |
/*
* 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.bedrock.cohere;
import java.util.List;
import reactor.core.publisher.Flux;
import org.springframework.ai.bedrock.BedrockUsage;
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;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.Assert;
/**
* @author Christian Tzolov
* @since 0.8.0
*/
public class BedrockCohereChatClient implements ChatClient, StreamingChatClient {
private final CohereChatBedrockApi chatApi;
private final BedrockCohereChatOptions defaultOptions;
public BedrockCohereChatClient(CohereChatBedrockApi chatApi) {
this(chatApi, BedrockCohereChatOptions.builder().build());
}
public BedrockCohereChatClient(CohereChatBedrockApi chatApi, BedrockCohereChatOptions options) {
Assert.notNull(chatApi, "CohereChatBedrockApi must not be null");
Assert.notNull(options, "BedrockCohereChatOptions must not be null");
this.chatApi = chatApi;
this.defaultOptions = options;
}
@Override
public ChatResponse call(Prompt prompt) {
CohereChatResponse response = this.chatApi.chatCompletion(this.createRequest(prompt, false));
List<Generation> generations = response.generations().stream().map(g -> {
return new Generation(g.text());
}).toList();
return new ChatResponse(generations);
}
@Override
public Flux<ChatResponse> stream(Prompt prompt) {
return this.chatApi.chatCompletionStream(this.createRequest(prompt, true)).map(g -> {
if (g.isFinished()) {
String finishReason = g.finishReason().name();
Usage usage = BedrockUsage.from(g.amazonBedrockInvocationMetrics());
return new ChatResponse(List
.of(new Generation("").withGenerationMetadata(ChatGenerationMetadata.from(finishReason, usage))));
}
return new ChatResponse(List.of(new Generation(g.text())));
});
}
/**
* Test access.
*/
CohereChatRequest createRequest(Prompt prompt, boolean stream) {
final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions());
var request = CohereChatRequest.builder(promptValue)
.withTemperature(this.defaultOptions.getTemperature())
.withTopP(this.defaultOptions.getTopP())
.withTopK(this.defaultOptions.getTopK())
.withMaxTokens(this.defaultOptions.getMaxTokens())
.withStopSequences(this.defaultOptions.getStopSequences())
.withReturnLikelihoods(this.defaultOptions.getReturnLikelihoods())
.withStream(stream)
.withNumGenerations(this.defaultOptions.getNumGenerations())
.withLogitBias(this.defaultOptions.getLogitBias())
.withTruncate(this.defaultOptions.getTruncate())
.build();
if (prompt.getOptions() != null) {
if (prompt.getOptions() instanceof ChatOptions runtimeOptions) {
BedrockCohereChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions,
ChatOptions.class, BedrockCohereChatOptions.class);
request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, CohereChatRequest.class);
}
else {
throw new IllegalArgumentException("Prompt options are not of type ChatOptions: "
+ prompt.getOptions().getClass().getSimpleName());
}
}
return request;
}
}
| [
"org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder",
"org.springframework.ai.bedrock.MessageToPromptConverter.create"
] | [((3240, 3308), 'org.springframework.ai.bedrock.MessageToPromptConverter.create'), ((3327, 3902), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3890), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3838), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3784), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3720), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3697), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3627), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3565), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3511), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3467), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder'), ((3327, 3423), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.builder')] |
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.openai;
import org.springframework.ai.document.MetadataMode;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.OpenAiEmbeddingOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Profile("openai")
@Configuration
public class OpenAiEmbeddingClientConfig {
@Value("${ai-client.openai.api-key}")
private String openaiApiKey;
@Bean
OpenAiEmbeddingClient openAiEmbeddingClient() {
var openAiApi = new OpenAiApi(openaiApiKey);
return new OpenAiEmbeddingClient(
openAiApi,
MetadataMode.EMBED,
OpenAiEmbeddingOptions.builder().withModel(OpenAiApi.DEFAULT_EMBEDDING_MODEL).build(),
RetryUtils.DEFAULT_RETRY_TEMPLATE);
}
}
| [
"org.springframework.ai.openai.OpenAiEmbeddingOptions.builder"
] | [((968, 1053), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((968, 1045), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder')] |
/*
* 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.vectorstore;
import io.milvus.client.MilvusServiceClient;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Christian Tzolov
*/
@ExtendWith(MockitoExtension.class)
public class MilvusEmbeddingDimensionsTests {
@Mock
private EmbeddingClient embeddingClient;
@Mock
private MilvusServiceClient milvusClient;
@Test
public void explicitlySetDimensions() {
final int explicitDimensions = 696;
MilvusVectorStoreConfig config = MilvusVectorStoreConfig.builder()
.withEmbeddingDimension(explicitDimensions)
.build();
var dim = new MilvusVectorStore(milvusClient, embeddingClient, config).embeddingDimensions();
assertThat(dim).isEqualTo(explicitDimensions);
verify(embeddingClient, never()).dimensions();
}
@Test
public void embeddingClientDimensions() {
when(embeddingClient.dimensions()).thenReturn(969);
MilvusVectorStoreConfig config = MilvusVectorStoreConfig.builder().build();
var dim = new MilvusVectorStore(milvusClient, embeddingClient, config).embeddingDimensions();
assertThat(dim).isEqualTo(969);
verify(embeddingClient, only()).dimensions();
}
@Test
public void fallBackToDefaultDimensions() {
when(embeddingClient.dimensions()).thenThrow(new RuntimeException());
var dim = new MilvusVectorStore(milvusClient, embeddingClient,
MilvusVectorStoreConfig.builder().build())
.embeddingDimensions();
assertThat(dim).isEqualTo(MilvusVectorStore.OPENAI_EMBEDDING_DIMENSION_SIZE);
verify(embeddingClient, only()).dimensions();
}
}
| [
"org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder"
] | [((1580, 1672), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((1580, 1660), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2014, 2055), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2437, 2478), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder')] |
/*
* 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.vectorstore;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.transformers.TransformersEmbeddingClient;
import org.springframework.ai.vectorstore.GemFireVectorStore.GemFireVectorStoreConfig;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.DefaultResourceLoader;
/**
* @author Geet Rawat
* @since 1.0.0
*/
@EnabledIfEnvironmentVariable(named = "GEMFIRE_HOST", matches = ".+")
public class GemFireVectorStoreIT {
public static final String INDEX_NAME = "spring-ai-index1";
List<Document> documents = List.of(
new Document("1", getText("classpath:/test/data/spring.ai.txt"), Map.of("meta1", "meta1")),
new Document("2", getText("classpath:/test/data/time.shelter.txt"), Map.of()),
new Document("3", getText("classpath:/test/data/great.depression.txt"), Map.of("meta2", "meta2")));
public static String getText(String uri) {
var resource = new DefaultResourceLoader().getResource(uri);
try {
return resource.getContentAsString(StandardCharsets.UTF_8);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withUserConfiguration(TestApplication.class);
@BeforeEach
public void createIndex() {
contextRunner.run(c -> c.getBean(GemFireVectorStore.class).createIndex(INDEX_NAME));
}
@AfterEach
public void deleteIndex() {
contextRunner.run(c -> c.getBean(GemFireVectorStore.class).deleteIndex(INDEX_NAME));
}
@Test
public void addAndDeleteEmbeddingTest() {
contextRunner.run(context -> {
VectorStore vectorStore = context.getBean(VectorStore.class);
vectorStore.add(documents);
vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList());
Awaitility.await().atMost(1, MINUTES).until(() -> {
return vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(3));
}, hasSize(0));
});
}
@Test
public void addAndSearchTest() {
contextRunner.run(context -> {
VectorStore vectorStore = context.getBean(VectorStore.class);
vectorStore.add(documents);
Awaitility.await().atMost(1, MINUTES).until(() -> {
return vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1));
}, hasSize(1));
List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(5));
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId());
assertThat(resultDoc.getContent()).contains("The Great Depression (1929–1939) was an economic shock");
assertThat(resultDoc.getMetadata()).hasSize(2);
assertThat(resultDoc.getMetadata()).containsKey("meta2");
assertThat(resultDoc.getMetadata()).containsKey("distance");
});
}
@Test
public void documentUpdateTest() {
contextRunner.run(context -> {
VectorStore vectorStore = context.getBean(VectorStore.class);
Document document = new Document(UUID.randomUUID().toString(), "Spring AI rocks!!",
Collections.singletonMap("meta1", "meta1"));
vectorStore.add(List.of(document));
SearchRequest springSearchRequest = SearchRequest.query("Spring").withTopK(5);
Awaitility.await().atMost(1, MINUTES).until(() -> {
return vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1));
}, hasSize(1));
List<Document> results = vectorStore.similaritySearch(springSearchRequest);
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(document.getId());
assertThat(resultDoc.getContent()).isEqualTo("Spring AI rocks!!");
assertThat(resultDoc.getMetadata()).containsKey("meta1");
assertThat(resultDoc.getMetadata()).containsKey("distance");
Document sameIdDocument = new Document(document.getId(),
"The World is Big and Salvation Lurks Around the Corner",
Collections.singletonMap("meta2", "meta2"));
vectorStore.add(List.of(sameIdDocument));
SearchRequest fooBarSearchRequest = SearchRequest.query("FooBar").withTopK(5);
results = vectorStore.similaritySearch(fooBarSearchRequest);
assertThat(results).hasSize(1);
resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(document.getId());
assertThat(resultDoc.getContent()).isEqualTo("The World is Big and Salvation Lurks Around the Corner");
assertThat(resultDoc.getMetadata()).containsKey("meta2");
assertThat(resultDoc.getMetadata()).containsKey("distance");
});
}
@Test
public void searchThresholdTest() {
contextRunner.run(context -> {
VectorStore vectorStore = context.getBean(VectorStore.class);
vectorStore.add(documents);
Awaitility.await().atMost(1, MINUTES).until(() -> {
return vectorStore
.similaritySearch(SearchRequest.query("Great Depression").withTopK(5).withSimilarityThresholdAll());
}, hasSize(3));
List<Document> fullResult = vectorStore
.similaritySearch(SearchRequest.query("Depression").withTopK(5).withSimilarityThresholdAll());
List<Float> distances = fullResult.stream().map(doc -> (Float) doc.getMetadata().get("distance")).toList();
assertThat(distances).hasSize(3);
float threshold = (distances.get(0) + distances.get(1)) / 2;
List<Document> results = vectorStore
.similaritySearch(SearchRequest.query("Depression").withTopK(5).withSimilarityThreshold(1 - threshold));
assertThat(results).hasSize(1);
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId());
assertThat(resultDoc.getContent()).contains("The Great Depression (1929–1939) was an economic shock");
assertThat(resultDoc.getMetadata()).containsKey("meta2");
assertThat(resultDoc.getMetadata()).containsKey("distance");
});
}
@SpringBootConfiguration
@EnableAutoConfiguration
public static class TestApplication {
@Bean
public GemFireVectorStoreConfig gemfireVectorStoreConfig() {
return GemFireVectorStoreConfig.builder().withHost("localhost").build();
}
@Bean
public GemFireVectorStore vectorStore(GemFireVectorStoreConfig config, EmbeddingClient embeddingClient) {
GemFireVectorStore gemFireVectorStore = new GemFireVectorStore(config, embeddingClient);
gemFireVectorStore.setIndexName(INDEX_NAME);
return gemFireVectorStore;
}
@Bean
public EmbeddingClient embeddingClient() {
return new TransformersEmbeddingClient();
}
}
} | [
"org.springframework.ai.vectorstore.GemFireVectorStore.GemFireVectorStoreConfig.builder"
] | [((3235, 3398), 'org.awaitility.Awaitility.await'), ((3235, 3272), 'org.awaitility.Awaitility.await'), ((3584, 3747), 'org.awaitility.Awaitility.await'), ((3584, 3621), 'org.awaitility.Awaitility.await'), ((4443, 4471), 'java.util.UUID.randomUUID'), ((4668, 4831), 'org.awaitility.Awaitility.await'), ((4668, 4705), 'org.awaitility.Awaitility.await'), ((6124, 6322), 'org.awaitility.Awaitility.await'), ((6124, 6161), 'org.awaitility.Awaitility.await'), ((7393, 7457), 'org.springframework.ai.vectorstore.GemFireVectorStore.GemFireVectorStoreConfig.builder'), ((7393, 7449), 'org.springframework.ai.vectorstore.GemFireVectorStore.GemFireVectorStoreConfig.builder')] |
/*
* 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.autoconfigure.openai.tool;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration;
import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
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.FunctionCallback;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".*")
public class FunctionCallbackWrapperIT {
private final Logger logger = LoggerFactory.getLogger(FunctionCallbackWrapperIT.class);
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.ai.openai.apiKey=" + System.getenv("OPENAI_API_KEY"))
.withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class,
RestClientAutoConfiguration.class, OpenAiAutoConfiguration.class))
.withUserConfiguration(Config.class);
@Test
void functionCallTest() {
contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> {
OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class);
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");
ChatResponse response = chatClient.call(
new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("WeatherInfo").build()));
logger.info("Response: {}", response);
assertThat(response.getResult().getOutput().getContent()).contains("30.0", "10.0", "15.0");
});
}
@Test
void streamFunctionCallTest() {
contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> {
OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class);
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");
Flux<ChatResponse> response = chatClient.stream(
new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("WeatherInfo").build()));
String content = response.collectList()
.block()
.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.joining());
logger.info("Response: {}", content);
assertThat(content).containsAnyOf("30.0", "30");
assertThat(content).containsAnyOf("10.0", "10");
assertThat(content).containsAnyOf("15.0", "15");
});
}
@Configuration
static class Config {
@Bean
public FunctionCallback weatherFunctionInfo() {
return FunctionCallbackWrapper.builder(new MockWeatherService())
.withName("WeatherInfo")
.withDescription("Get the weather in location")
.withResponseConverter((response) -> "" + response.temp() + response.unit())
.build();
}
}
} | [
"org.springframework.ai.openai.OpenAiChatOptions.builder",
"org.springframework.ai.model.function.FunctionCallbackWrapper.builder"
] | [((2987, 3050), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2987, 3042), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3631, 3694), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3631, 3686), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((4256, 4488), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4256, 4475), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4256, 4394), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4256, 4342), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')] |
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.function.FunctionCallbackWrapper;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.openai.api.tool.MockWeatherService;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
*/
public class ChatCompletionRequestTests {
@Test
public void createRequestWithChatOptions() {
var client = new OpenAiChatClient(new OpenAiApi("TEST"),
OpenAiChatOptions.builder().withModel("DEFAULT_MODEL").withTemperature(66.6f).build());
var request = client.createRequest(new Prompt("Test message content"), false);
assertThat(request.messages()).hasSize(1);
assertThat(request.stream()).isFalse();
assertThat(request.model()).isEqualTo("DEFAULT_MODEL");
assertThat(request.temperature()).isEqualTo(66.6f);
request = client.createRequest(new Prompt("Test message content",
OpenAiChatOptions.builder().withModel("PROMPT_MODEL").withTemperature(99.9f).build()), true);
assertThat(request.messages()).hasSize(1);
assertThat(request.stream()).isTrue();
assertThat(request.model()).isEqualTo("PROMPT_MODEL");
assertThat(request.temperature()).isEqualTo(99.9f);
}
@Test
public void promptOptionsTools() {
final String TOOL_FUNCTION_NAME = "CurrentWeather";
var client = new OpenAiChatClient(new OpenAiApi("TEST"),
OpenAiChatOptions.builder().withModel("DEFAULT_MODEL").build());
var request = client.createRequest(new Prompt("Test message content",
OpenAiChatOptions.builder()
.withModel("PROMPT_MODEL")
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withName(TOOL_FUNCTION_NAME)
.withDescription("Get the weather in location")
.withResponseConverter((response) -> "" + response.temp() + response.unit())
.build()))
.build()),
false);
assertThat(client.getFunctionCallbackRegister()).hasSize(1);
assertThat(client.getFunctionCallbackRegister()).containsKeys(TOOL_FUNCTION_NAME);
assertThat(request.messages()).hasSize(1);
assertThat(request.stream()).isFalse();
assertThat(request.model()).isEqualTo("PROMPT_MODEL");
assertThat(request.tools()).hasSize(1);
assertThat(request.tools().get(0).function().name()).isEqualTo(TOOL_FUNCTION_NAME);
}
@Test
public void defaultOptionsTools() {
final String TOOL_FUNCTION_NAME = "CurrentWeather";
var client = new OpenAiChatClient(new OpenAiApi("TEST"),
OpenAiChatOptions.builder()
.withModel("DEFAULT_MODEL")
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withName(TOOL_FUNCTION_NAME)
.withDescription("Get the weather in location")
.withResponseConverter((response) -> "" + response.temp() + response.unit())
.build()))
.build());
var request = client.createRequest(new Prompt("Test message content"), false);
assertThat(client.getFunctionCallbackRegister()).hasSize(1);
assertThat(client.getFunctionCallbackRegister()).containsKeys(TOOL_FUNCTION_NAME);
assertThat(client.getFunctionCallbackRegister().get(TOOL_FUNCTION_NAME).getDescription())
.isEqualTo("Get the weather in location");
assertThat(request.messages()).hasSize(1);
assertThat(request.stream()).isFalse();
assertThat(request.model()).isEqualTo("DEFAULT_MODEL");
assertThat(request.tools()).as("Default Options callback functions are not automatically enabled!")
.isNullOrEmpty();
// Explicitly enable the function
request = client.createRequest(new Prompt("Test message content",
OpenAiChatOptions.builder().withFunction(TOOL_FUNCTION_NAME).build()), false);
assertThat(request.tools()).hasSize(1);
assertThat(request.tools().get(0).function().name()).as("Explicitly enabled function")
.isEqualTo(TOOL_FUNCTION_NAME);
// Override the default options function with one from the prompt
request = client.createRequest(new Prompt("Test message content",
OpenAiChatOptions.builder()
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withName(TOOL_FUNCTION_NAME)
.withDescription("Overridden function description")
.build()))
.build()),
false);
assertThat(request.tools()).hasSize(1);
assertThat(request.tools().get(0).function().name()).as("Explicitly enabled function")
.isEqualTo(TOOL_FUNCTION_NAME);
assertThat(client.getFunctionCallbackRegister()).hasSize(1);
assertThat(client.getFunctionCallbackRegister()).containsKeys(TOOL_FUNCTION_NAME);
assertThat(client.getFunctionCallbackRegister().get(TOOL_FUNCTION_NAME).getDescription())
.isEqualTo("Overridden function description");
}
}
| [
"org.springframework.ai.model.function.FunctionCallbackWrapper.builder"
] | [((2354, 2599), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2354, 2584), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2354, 2501), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2354, 2447), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3317, 3562), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3317, 3547), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3317, 3464), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3317, 3410), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4780, 4946), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4780, 4931), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4780, 4873), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')] |
/*
* 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.autoconfigure.vectorstore.elasticsearch;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration;
import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.ElasticsearchVectorStore;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration;
import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.core.io.DefaultResourceLoader;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasSize;
@Testcontainers
@EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+")
class ElasticsearchVectorStoreAutoConfigurationIT {
@Container
private static final ElasticsearchContainer elasticsearchContainer = new ElasticsearchContainer(
"docker.elastic.co/elasticsearch/elasticsearch:8.12.2")
.withEnv("xpack.security.enabled", "false");
private static final String DEFAULT = "default cosine similarity";
private List<Document> documents = List.of(
new Document("1", getText("classpath:/test/data/spring.ai.txt"), Map.of("meta1", "meta1")),
new Document("2", getText("classpath:/test/data/time.shelter.txt"), Map.of()),
new Document("3", getText("classpath:/test/data/great.depression.txt"), Map.of("meta2", "meta2")));
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ElasticsearchRestClientAutoConfiguration.class,
ElasticsearchVectorStoreAutoConfiguration.class, RestClientAutoConfiguration.class,
SpringAiRetryAutoConfiguration.class, OpenAiAutoConfiguration.class))
.withPropertyValues("spring.elasticsearch.uris=" + elasticsearchContainer.getHttpHostAddress(),
"spring.ai.openai.api-key=" + System.getenv("OPENAI_API_KEY"));
@ParameterizedTest(name = "{0} : {displayName} ")
@ValueSource(strings = { DEFAULT, """
double value = dotProduct(params.query_vector, 'embedding');
return sigmoid(1, Math.E, -value);
""", "1 / (1 + l1norm(params.query_vector, 'embedding'))",
"1 / (1 + l2norm(params.query_vector, 'embedding'))" })
public void addAndSearchTest(String similarityFunction) {
this.contextRunner.run(context -> {
ElasticsearchVectorStore vectorStore = context.getBean(ElasticsearchVectorStore.class);
if (!DEFAULT.equals(similarityFunction)) {
vectorStore.withSimilarityFunction(similarityFunction);
}
vectorStore.add(documents);
Awaitility.await()
.until(() -> vectorStore
.similaritySearch(SearchRequest.query("Great Depression").withTopK(1).withSimilarityThreshold(0)),
hasSize(1));
List<Document> results = vectorStore
.similaritySearch(SearchRequest.query("Great Depression").withTopK(1).withSimilarityThreshold(0));
assertThat(results).hasSize(1);
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId());
assertThat(resultDoc.getContent()).contains("The Great Depression (1929–1939) was an economic shock");
assertThat(resultDoc.getMetadata()).hasSize(2);
assertThat(resultDoc.getMetadata()).containsKey("meta2");
assertThat(resultDoc.getMetadata()).containsKey("distance");
// Remove all documents from the store
vectorStore.delete(documents.stream().map(Document::getId).toList());
Awaitility.await()
.until(() -> vectorStore
.similaritySearch(SearchRequest.query("Great Depression").withTopK(1).withSimilarityThreshold(0)),
hasSize(0));
});
}
private String getText(String uri) {
var resource = new DefaultResourceLoader().getResource(uri);
try {
return resource.getContentAsString(StandardCharsets.UTF_8);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((3928, 4097), 'org.awaitility.Awaitility.await'), ((3999, 4077), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3999, 4050), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4162, 4240), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4162, 4213), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4793, 4962), 'org.awaitility.Awaitility.await'), ((4864, 4942), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4864, 4915), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
/*
* 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.bedrock.titan.api;
import java.io.IOException;
import java.util.Base64;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import software.amazon.awssdk.regions.Region;
import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel;
import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingRequest;
import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingResponse;
import org.springframework.core.io.DefaultResourceLoader;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
*/
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
public class TitanEmbeddingBedrockApiIT {
@Test
public void embedText() {
TitanEmbeddingBedrockApi titanEmbedApi = new TitanEmbeddingBedrockApi(
TitanEmbeddingModel.TITAN_EMBED_TEXT_V1.id(), Region.US_EAST_1.id());
TitanEmbeddingRequest request = TitanEmbeddingRequest.builder().withInputText("I like to eat apples.").build();
TitanEmbeddingResponse response = titanEmbedApi.embedding(request);
assertThat(response).isNotNull();
assertThat(response.inputTextTokenCount()).isEqualTo(6);
assertThat(response.embedding()).hasSize(1536);
}
@Test
public void embedImage() throws IOException {
TitanEmbeddingBedrockApi titanEmbedApi = new TitanEmbeddingBedrockApi(
TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id(), Region.US_EAST_1.id());
byte[] image = new DefaultResourceLoader().getResource("classpath:/spring_framework.png")
.getContentAsByteArray();
String imageBase64 = Base64.getEncoder().encodeToString(image);
System.out.println(imageBase64.length());
TitanEmbeddingRequest request = TitanEmbeddingRequest.builder().withInputImage(imageBase64).build();
TitanEmbeddingResponse response = titanEmbedApi.embedding(request);
assertThat(response).isNotNull();
assertThat(response.inputTextTokenCount()).isEqualTo(0); // e.g. image input
assertThat(response.embedding()).hasSize(1024);
}
}
| [
"org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingRequest.builder",
"org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id",
"org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_TEXT_V1.id"
] | [((1625, 1669), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_TEXT_V1.id'), ((1671, 1692), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((1730, 1808), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingRequest.builder'), ((1730, 1800), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingRequest.builder'), ((2163, 2208), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id'), ((2210, 2231), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2380, 2421), 'java.util.Base64.getEncoder'), ((2502, 2569), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingRequest.builder'), ((2502, 2561), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingRequest.builder')] |
/*
* 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.ollama.api;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import reactor.core.publisher.Flux;
import org.springframework.ai.ollama.api.OllamaApi.ChatRequest;
import org.springframework.ai.ollama.api.OllamaApi.ChatResponse;
import org.springframework.ai.ollama.api.OllamaApi.EmbeddingRequest;
import org.springframework.ai.ollama.api.OllamaApi.EmbeddingResponse;
import org.springframework.ai.ollama.api.OllamaApi.GenerateRequest;
import org.springframework.ai.ollama.api.OllamaApi.GenerateResponse;
import org.springframework.ai.ollama.api.OllamaApi.Message;
import org.springframework.ai.ollama.api.OllamaApi.Message.Role;
import static org.assertj.core.api.Assertions.assertThat;;
/**
* @author Christian Tzolov
*/
@Disabled("For manual smoke testing only.")
@Testcontainers
public class OllamaApiIT {
private static final Log logger = LogFactory.getLog(OllamaApiIT.class);
@Container
static GenericContainer<?> ollamaContainer = new GenericContainer<>("ollama/ollama:0.1.23").withExposedPorts(11434);
static OllamaApi ollamaApi;
@BeforeAll
public static void beforeAll() throws IOException, InterruptedException {
logger.info("Start pulling the 'orca-mini' generative (3GB) ... would take several minutes ...");
ollamaContainer.execInContainer("ollama", "pull", "orca-mini");
logger.info("orca-mini pulling competed!");
ollamaApi = new OllamaApi("http://" + ollamaContainer.getHost() + ":" + ollamaContainer.getMappedPort(11434));
}
@Test
public void generation() {
var request = GenerateRequest
.builder("What is the capital of Bulgaria and what is the size? What it the national anthem?")
.withModel("orca-mini")
.withStream(false)
.build();
GenerateResponse response = ollamaApi.generate(request);
System.out.println(response);
assertThat(response).isNotNull();
assertThat(response.model()).isEqualTo(response.model());
assertThat(response.response()).contains("Sofia");
}
@Test
public void chat() {
var request = ChatRequest.builder("orca-mini")
.withStream(false)
.withMessages(List.of(
Message.builder(Role.SYSTEM)
.withContent("You are geography teacher. You are talking to a student.")
.build(),
Message.builder(Role.USER)
.withContent("What is the capital of Bulgaria and what is the size? "
+ "What it the national anthem?")
.build()))
.withOptions(OllamaOptions.create().withTemperature(0.9f))
.build();
ChatResponse response = ollamaApi.chat(request);
System.out.println(response);
assertThat(response).isNotNull();
assertThat(response.model()).isEqualTo(response.model());
assertThat(response.done()).isTrue();
assertThat(response.message().role()).isEqualTo(Role.ASSISTANT);
assertThat(response.message().content()).contains("Sofia");
}
@Test
public void streamingChat() {
var request = ChatRequest.builder("orca-mini")
.withStream(true)
.withMessages(List.of(Message.builder(Role.USER)
.withContent("What is the capital of Bulgaria and what is the size? " + "What it the national anthem?")
.build()))
.withOptions(OllamaOptions.create().withTemperature(0.9f).toMap())
.build();
Flux<ChatResponse> response = ollamaApi.streamingChat(request);
List<ChatResponse> responses = response.collectList().block();
System.out.println(responses);
assertThat(response).isNotNull();
assertThat(responses.stream()
.filter(r -> r.message() != null)
.map(r -> r.message().content())
.collect(Collectors.joining(System.lineSeparator()))).contains("Sofia");
ChatResponse lastResponse = responses.get(responses.size() - 1);
assertThat(lastResponse.message().content()).isEmpty();
assertThat(lastResponse.done()).isTrue();
}
@Test
public void embedText() {
EmbeddingRequest request = new EmbeddingRequest("orca-mini", "I like to eat apples");
EmbeddingResponse response = ollamaApi.embeddings(request);
assertThat(response).isNotNull();
assertThat(response.embedding()).hasSize(3200);
}
} | [
"org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder",
"org.springframework.ai.ollama.api.OllamaApi.Message.builder"
] | [((3037, 3487), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3037, 3475), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3037, 3413), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3037, 3091), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3123, 3245), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((3123, 3230), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((3252, 3411), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((3252, 3396), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((3899, 4209), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3899, 4197), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3899, 4127), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3899, 3952), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((3978, 4125), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((3978, 4112), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder')] |
/*
* 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.azure.openai.function;
import java.util.ArrayList;
import java.util.List;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
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.azure.openai.AzureOpenAiChatClient;
import org.springframework.ai.azure.openai.AzureOpenAiChatOptions;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.function.FunctionCallbackWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = AzureOpenAiChatClientFunctionCallIT.TestConfiguration.class)
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+")
@EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+")
class AzureOpenAiChatClientFunctionCallIT {
private static final Logger logger = LoggerFactory.getLogger(AzureOpenAiChatClientFunctionCallIT.class);
@Autowired
private AzureOpenAiChatClient chatClient;
@Test
void functionCallTest() {
UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, in Tokyo, and in Paris?");
List<Message> messages = new ArrayList<>(List.of(userMessage));
var promptOptions = AzureOpenAiChatOptions.builder()
.withDeploymentName("gpt-4-0125-preview")
.withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService())
.withName("getCurrentWeather")
.withDescription("Get the current weather in a given location")
.withResponseConverter((response) -> "" + response.temp() + response.unit())
.build()))
.build();
ChatResponse response = chatClient.call(new Prompt(messages, promptOptions));
logger.info("Response: {}", response);
assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30");
assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", "10");
assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15.0", "15");
}
@SpringBootConfiguration
public static class TestConfiguration {
@Bean
public OpenAIClient openAIClient() {
return new OpenAIClientBuilder().credential(new AzureKeyCredential(System.getenv("AZURE_OPENAI_API_KEY")))
.endpoint(System.getenv("AZURE_OPENAI_ENDPOINT"))
.buildClient();
}
@Bean
public AzureOpenAiChatClient azureOpenAiChatClient(OpenAIClient openAIClient) {
return new AzureOpenAiChatClient(openAIClient,
AzureOpenAiChatOptions.builder()
.withDeploymentName("gpt-4-0125-preview")
.withMaxTokens(500)
.build());
}
}
}
| [
"org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder",
"org.springframework.ai.model.function.FunctionCallbackWrapper.builder"
] | [((2426, 2806), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2426, 2794), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2426, 2503), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2538, 2792), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2538, 2779), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2538, 2698), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2538, 2630), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3652, 3773), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3652, 3758), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3652, 3732), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder')] |
/*
* 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.bedrock.anthropic3;
import org.junit.jupiter.api.Test;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import software.amazon.awssdk.regions.Region;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
*/
public class BedrockAnthropic3CreateRequestTests {
private Anthropic3ChatBedrockApi anthropicChatApi = new Anthropic3ChatBedrockApi(AnthropicChatModel.CLAUDE_V2.id(),
Region.EU_CENTRAL_1.id());
@Test
public void createRequestWithChatOptions() {
var client = new BedrockAnthropic3ChatClient(anthropicChatApi,
Anthropic3ChatOptions.builder()
.withTemperature(66.6f)
.withTopK(66)
.withTopP(0.66f)
.withMaxTokens(666)
.withAnthropicVersion("X.Y.Z")
.withStopSequences(List.of("stop1", "stop2"))
.build());
var request = client.createRequest(new Prompt("Test message content"));
assertThat(request.messages()).isNotEmpty();
assertThat(request.temperature()).isEqualTo(66.6f);
assertThat(request.topK()).isEqualTo(66);
assertThat(request.topP()).isEqualTo(0.66f);
assertThat(request.maxTokens()).isEqualTo(666);
assertThat(request.anthropicVersion()).isEqualTo("X.Y.Z");
assertThat(request.stopSequences()).containsExactly("stop1", "stop2");
request = client.createRequest(new Prompt("Test message content",
Anthropic3ChatOptions.builder()
.withTemperature(99.9f)
.withTopP(0.99f)
.withMaxTokens(999)
.withAnthropicVersion("zzz")
.withStopSequences(List.of("stop3", "stop4"))
.build()
));
assertThat(request.messages()).isNotEmpty();
assertThat(request.temperature()).isEqualTo(99.9f);
assertThat(request.topK()).as("unchanged from the default options").isEqualTo(66);
assertThat(request.topP()).isEqualTo(0.99f);
assertThat(request.maxTokens()).isEqualTo(999);
assertThat(request.anthropicVersion()).isEqualTo("zzz");
assertThat(request.stopSequences()).containsExactly("stop3", "stop4");
}
}
| [
"org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id"
] | [((1233, 1266), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((1271, 1295), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')] |
/*
* 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.autoconfigure.bedrock.llama2;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.AssistantMessage;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.regions.Region;
import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties;
import org.springframework.ai.bedrock.llama2.BedrockLlama2ChatClient;
import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
* @since 0.8.0
*/
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
public class BedrockLlama2ChatAutoConfigurationIT {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.llama2.chat.enabled=true",
"spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"),
"spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"),
"spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(),
"spring.ai.bedrock.llama2.chat.model=" + Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(),
"spring.ai.bedrock.llama2.chat.options.temperature=0.5",
"spring.ai.bedrock.llama2.chat.options.maxGenLen=500")
.withConfiguration(AutoConfigurations.of(BedrockLlama2ChatAutoConfiguration.class));
private final Message systemMessage = new SystemPromptTemplate("""
You are a helpful AI assistant. Your name is {name}.
You are an AI assistant that helps people find information.
Your name is {name}
You should reply to the user's request with your name and also in the style of a {voice}.
""").createMessage(Map.of("name", "Bob", "voice", "pirate"));
private final UserMessage userMessage = new UserMessage(
"Tell me about 3 famous pirates from the Golden Age of Piracy and why they did.");
@Test
public void chatCompletion() {
contextRunner.run(context -> {
BedrockLlama2ChatClient llama2ChatClient = context.getBean(BedrockLlama2ChatClient.class);
ChatResponse response = llama2ChatClient.call(new Prompt(List.of(userMessage, systemMessage)));
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
});
}
@Test
public void chatCompletionStreaming() {
contextRunner.run(context -> {
BedrockLlama2ChatClient llama2ChatClient = context.getBean(BedrockLlama2ChatClient.class);
Flux<ChatResponse> response = llama2ChatClient.stream(new Prompt(List.of(userMessage, systemMessage)));
List<ChatResponse> responses = response.collectList().block();
assertThat(responses.size()).isGreaterThan(2);
String stitchedResponseContent = responses.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.joining());
assertThat(stitchedResponseContent).contains("Blackbeard");
});
}
@Test
public void propertiesTest() {
new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.llama2.chat.enabled=true",
"spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY",
"spring.ai.bedrock.llama2.chat.model=MODEL_XYZ",
"spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(),
"spring.ai.bedrock.llama2.chat.options.temperature=0.55",
"spring.ai.bedrock.llama2.chat.options.maxGenLen=123")
.withConfiguration(AutoConfigurations.of(BedrockLlama2ChatAutoConfiguration.class))
.run(context -> {
var llama2ChatProperties = context.getBean(BedrockLlama2ChatProperties.class);
var awsProperties = context.getBean(BedrockAwsConnectionProperties.class);
assertThat(llama2ChatProperties.isEnabled()).isTrue();
assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id());
assertThat(llama2ChatProperties.getOptions().getTemperature()).isEqualTo(0.55f);
assertThat(llama2ChatProperties.getOptions().getMaxGenLen()).isEqualTo(123);
assertThat(llama2ChatProperties.getModel()).isEqualTo("MODEL_XYZ");
assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY");
assertThat(awsProperties.getSecretKey()).isEqualTo("SECRET_KEY");
});
}
@Test
public void chatCompletionDisabled() {
// It is disabled by default
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(BedrockLlama2ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockLlama2ChatProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockLlama2ChatClient.class)).isEmpty();
});
// Explicitly enable the chat auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.llama2.chat.enabled=true")
.withConfiguration(AutoConfigurations.of(BedrockLlama2ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockLlama2ChatProperties.class)).isNotEmpty();
assertThat(context.getBeansOfType(BedrockLlama2ChatClient.class)).isNotEmpty();
});
// Explicitly disable the chat auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.llama2.chat.enabled=false")
.withConfiguration(AutoConfigurations.of(BedrockLlama2ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockLlama2ChatProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockLlama2ChatClient.class)).isEmpty();
});
}
}
| [
"org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id"
] | [((2389, 2410), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2457, 2496), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id'), ((4614, 4638), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((5145, 5169), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')] |
/*
* 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.autoconfigure.bedrock.anthropic3;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.chat.messages.AssistantMessage;
import reactor.core.publisher.Flux;
import software.amazon.awssdk.regions.Region;
import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties;
import org.springframework.ai.bedrock.anthropic3.BedrockAnthropic3ChatClient;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Christian Tzolov
* @since 1.0.0
*/
@EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*")
@EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*")
public class BedrockAnthropic3ChatAutoConfigurationIT {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.anthropic3.chat.enabled=true",
"spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"),
"spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"),
"spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(),
"spring.ai.bedrock.anthropic3.chat.model=" + AnthropicChatModel.CLAUDE_V3_SONNET.id(),
"spring.ai.bedrock.anthropic3.chat.options.temperature=0.5")
.withConfiguration(AutoConfigurations.of(BedrockAnthropic3ChatAutoConfiguration.class));
private final Message systemMessage = new SystemPromptTemplate("""
You are a helpful AI assistant. Your name is {name}.
You are an AI assistant that helps people find information.
Your name is {name}
You should reply to the user's request with your name and also in the style of a {voice}.
""").createMessage(Map.of("name", "Bob", "voice", "pirate"));
private final UserMessage userMessage = new UserMessage(
"Tell me about 3 famous pirates from the Golden Age of Piracy and why they did.");
@Test
public void chatCompletion() {
contextRunner.run(context -> {
BedrockAnthropic3ChatClient anthropicChatClient = context.getBean(BedrockAnthropic3ChatClient.class);
ChatResponse response = anthropicChatClient.call(new Prompt(List.of(userMessage, systemMessage)));
assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard");
});
}
@Test
public void chatCompletionStreaming() {
contextRunner.run(context -> {
BedrockAnthropic3ChatClient anthropicChatClient = context.getBean(BedrockAnthropic3ChatClient.class);
Flux<ChatResponse> response = anthropicChatClient.stream(new Prompt(List.of(userMessage, systemMessage)));
List<ChatResponse> responses = response.collectList().block();
assertThat(responses.size()).isGreaterThan(2);
String stitchedResponseContent = responses.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.joining());
assertThat(stitchedResponseContent).contains("Blackbeard");
});
}
@Test
public void propertiesTest() {
new ApplicationContextRunner()
.withPropertyValues("spring.ai.bedrock.anthropic3.chat.enabled=true",
"spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY",
"spring.ai.bedrock.anthropic3.chat.model=MODEL_XYZ",
"spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(),
"spring.ai.bedrock.anthropic3.chat.options.temperature=0.55")
.withConfiguration(AutoConfigurations.of(BedrockAnthropic3ChatAutoConfiguration.class))
.run(context -> {
var anthropicChatProperties = context.getBean(BedrockAnthropic3ChatProperties.class);
var awsProperties = context.getBean(BedrockAwsConnectionProperties.class);
assertThat(anthropicChatProperties.isEnabled()).isTrue();
assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id());
assertThat(anthropicChatProperties.getOptions().getTemperature()).isEqualTo(0.55f);
assertThat(anthropicChatProperties.getModel()).isEqualTo("MODEL_XYZ");
assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY");
assertThat(awsProperties.getSecretKey()).isEqualTo("SECRET_KEY");
});
}
@Test
public void chatCompletionDisabled() {
// It is disabled by default
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(BedrockAnthropic3ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockAnthropic3ChatProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockAnthropic3ChatClient.class)).isEmpty();
});
// Explicitly enable the chat auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.anthropic3.chat.enabled=true")
.withConfiguration(AutoConfigurations.of(BedrockAnthropic3ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockAnthropic3ChatProperties.class)).isNotEmpty();
assertThat(context.getBeansOfType(BedrockAnthropic3ChatClient.class)).isNotEmpty();
});
// Explicitly disable the chat auto-configuration.
new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.anthropic3.chat.enabled=false")
.withConfiguration(AutoConfigurations.of(BedrockAnthropic3ChatAutoConfiguration.class))
.run(context -> {
assertThat(context.getBeansOfType(BedrockAnthropic3ChatProperties.class)).isEmpty();
assertThat(context.getBeansOfType(BedrockAnthropic3ChatClient.class)).isEmpty();
});
}
}
| [
"org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V3_SONNET.id"
] | [((2420, 2441), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2492, 2532), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V3_SONNET.id'), ((4635, 4659), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((5124, 5148), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')] |
/*
* 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.autoconfigure.vectorstore.qdrant;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import io.qdrant.client.QdrantClient;
import io.qdrant.client.QdrantGrpcClient;
import io.qdrant.client.grpc.Collections.Distance;
import io.qdrant.client.grpc.Collections.VectorParams;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.transformers.TransformersEmbeddingClient;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test using a free tier Qdrant Cloud instance: https://cloud.qdrant.io
*
* @author Christian Tzolov
* @since 0.8.1
*/
// NOTE: The free Qdrant Cluster and the QDRANT_API_KEY expire after 4 weeks of
// inactivity.
@EnabledIfEnvironmentVariable(named = "QDRANT_API_KEY", matches = ".+")
@EnabledIfEnvironmentVariable(named = "QDRANT_HOST", matches = ".+")
public class QdrantVectorStoreCloudAutoConfigurationIT {
private static final String COLLECTION_NAME = "test_collection";
// Because we pre-create the collection.
private static final int EMBEDDING_DIMENSION = 384;
private static final String CLOUD_API_KEY = System.getenv("QDRANT_API_KEY");
private static final String CLOUD_HOST = System.getenv("QDRANT_HOST");
// NOTE: The GRPC port (usually 6334) is different from the HTTP port (usually 6333)!
private static final int CLOUD_GRPC_PORT = 6334;
List<Document> documents = List.of(
new Document(getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")),
new Document(getText("classpath:/test/data/time.shelter.txt")),
new Document(getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad")));
@BeforeAll
static void setup() throws InterruptedException, ExecutionException {
// Create a new test collection
try (QdrantClient client = new QdrantClient(
QdrantGrpcClient.newBuilder(CLOUD_HOST, CLOUD_GRPC_PORT, true).withApiKey(CLOUD_API_KEY).build())) {
if (client.listCollectionsAsync().get().stream().anyMatch(c -> c.equals(COLLECTION_NAME))) {
client.deleteCollectionAsync(COLLECTION_NAME).get();
}
var vectorParams = VectorParams.newBuilder()
.setDistance(Distance.Cosine)
.setSize(EMBEDDING_DIMENSION)
.build();
client.createCollectionAsync(COLLECTION_NAME, vectorParams).get();
}
}
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(QdrantVectorStoreAutoConfiguration.class))
.withUserConfiguration(Config.class)
.withPropertyValues("spring.ai.vectorstore.qdrant.port=" + CLOUD_GRPC_PORT,
"spring.ai.vectorstore.qdrant.host=" + CLOUD_HOST,
"spring.ai.vectorstore.qdrant.api-key=" + CLOUD_API_KEY,
"spring.ai.vectorstore.qdrant.collection-name=" + COLLECTION_NAME,
"spring.ai.vectorstore.qdrant.use-tls=true");
@Test
public void addAndSearch() {
contextRunner.run(context -> {
VectorStore vectorStore = context.getBean(VectorStore.class);
vectorStore.add(documents);
List<Document> results = vectorStore
.similaritySearch(SearchRequest.query("What is Great Depression?").withTopK(1));
assertThat(results).hasSize(1);
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId());
assertThat(resultDoc.getMetadata()).containsKeys("depression", "distance");
// Remove all documents from the store
vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList());
results = vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1));
assertThat(results).hasSize(0);
});
}
public static String getText(String uri) {
var resource = new DefaultResourceLoader().getResource(uri);
try {
return resource.getContentAsString(StandardCharsets.UTF_8);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@Configuration(proxyBeanMethods = false)
static class Config {
@Bean
public EmbeddingClient embeddingClient() {
return new TransformersEmbeddingClient();
}
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((3186, 3282), 'io.qdrant.client.QdrantGrpcClient.newBuilder'), ((3186, 3274), 'io.qdrant.client.QdrantGrpcClient.newBuilder'), ((3469, 3575), 'io.qdrant.client.grpc.Collections.VectorParams.newBuilder'), ((3469, 3562), 'io.qdrant.client.grpc.Collections.VectorParams.newBuilder'), ((3469, 3528), 'io.qdrant.client.grpc.Collections.VectorParams.newBuilder'), ((4415, 4475), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4864, 4915), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ai.openai.audio.transcription;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.metadata.RateLimit;
import org.springframework.ai.openai.OpenAiAudioTranscriptionClient;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionMetadata;
import org.springframework.ai.openai.metadata.audio.OpenAiAudioTranscriptionResponseMetadata;
import org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders;
import org.springframework.ai.retry.RetryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/**
* @author Michael Lavelle
*/
@RestClientTest(OpenAiTranscriptionClientWithTranscriptionResponseMetadataTests.Config.class)
public class OpenAiTranscriptionClientWithTranscriptionResponseMetadataTests {
private static String TEST_API_KEY = "sk-1234567890";
@Autowired
private OpenAiAudioTranscriptionClient openAiTranscriptionClient;
@Autowired
private MockRestServiceServer server;
@AfterEach
void resetMockServer() {
server.reset();
}
@Test
void aiResponseContainsAiMetadata() {
prepareMock();
Resource audioFile = new ClassPathResource("speech/jfk.flac");
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile);
AudioTranscriptionResponse response = this.openAiTranscriptionClient.call(transcriptionRequest);
assertThat(response).isNotNull();
OpenAiAudioTranscriptionResponseMetadata transcriptionResponseMetadata = response.getMetadata();
assertThat(transcriptionResponseMetadata).isNotNull();
RateLimit rateLimit = transcriptionResponseMetadata.getRateLimit();
Duration expectedRequestsReset = Duration.ofDays(2L)
.plus(Duration.ofHours(16L))
.plus(Duration.ofMinutes(15))
.plus(Duration.ofSeconds(29L));
Duration expectedTokensReset = Duration.ofHours(27L)
.plus(Duration.ofSeconds(55L))
.plus(Duration.ofMillis(451L));
assertThat(rateLimit).isNotNull();
assertThat(rateLimit.getRequestsLimit()).isEqualTo(4000L);
assertThat(rateLimit.getRequestsRemaining()).isEqualTo(999);
assertThat(rateLimit.getRequestsReset()).isEqualTo(expectedRequestsReset);
assertThat(rateLimit.getTokensLimit()).isEqualTo(725_000L);
assertThat(rateLimit.getTokensRemaining()).isEqualTo(112_358L);
assertThat(rateLimit.getTokensReset()).isEqualTo(expectedTokensReset);
response.getResults().forEach(transcript -> {
OpenAiAudioTranscriptionMetadata transcriptionMetadata = transcript.getMetadata();
assertThat(transcriptionMetadata).isNotNull();
});
}
private void prepareMock() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName(), "4000");
httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName(), "999");
httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName(), "2d16h15m29s");
httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName(), "725000");
httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName(), "112358");
httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName(), "27h55s451ms");
server.expect(requestTo("/v1/audio/transcriptions"))
.andExpect(method(HttpMethod.POST))
.andExpect(header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_API_KEY))
.andRespond(withSuccess(getJson(), MediaType.APPLICATION_JSON).headers(httpHeaders));
}
private String getJson() {
return """
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"model": "gpt-3.5-turbo-0613",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "I surrender!"
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}
""";
}
@SpringBootConfiguration
static class Config {
@Bean
public OpenAiAudioApi chatCompletionApi(RestClient.Builder builder) {
return new OpenAiAudioApi("", TEST_API_KEY, builder, RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
}
@Bean
public OpenAiAudioTranscriptionClient openAiClient(OpenAiAudioApi openAiAudioApi) {
return new OpenAiAudioTranscriptionClient(openAiAudioApi);
}
}
}
| [
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName",
"org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName"
] | [((3374, 3492), 'java.time.Duration.ofDays'), ((3374, 3458), 'java.time.Duration.ofDays'), ((3374, 3425), 'java.time.Duration.ofDays'), ((3528, 3617), 'java.time.Duration.ofHours'), ((3528, 3583), 'java.time.Duration.ofHours'), ((4350, 4406), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName'), ((4435, 4495), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName'), ((4523, 4579), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName'), ((4615, 4669), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName'), ((4700, 4758), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName'), ((4789, 4843), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName')] |
/*
* 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.autoconfigure.vectorstore.mongo;
import org.junit.jupiter.api.Test;
import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration;
import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Eddú Meléndez
*/
@Testcontainers
class MongoDBAtlasVectorStoreAutoConfigurationIT {
@Container
static GenericContainer<?> mongo = new GenericContainer<>("mongodb/atlas:v1.15.1").withPrivilegedMode(true)
.withCommand("/bin/bash", "-c",
"atlas deployments setup local-test --type local --port 27778 --bindIpAll --username root --password root --force && tail -f /dev/null")
.withExposedPorts(27778)
.waitingFor(Wait.forLogMessage(".*Deployment created!.*\\n", 1))
.withStartupTimeout(Duration.ofMinutes(5));
List<Document> documents = List.of(
new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!",
Collections.singletonMap("meta1", "meta1")),
new Document("Hello World Hello World Hello World Hello World Hello World Hello World Hello World"),
new Document(
"Great Depression Great Depression Great Depression Great Depression Great Depression Great Depression",
Collections.singletonMap("meta2", "meta2")));
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoDataAutoConfiguration.class,
MongoDBAtlasVectorStoreAutoConfiguration.class, RestClientAutoConfiguration.class,
SpringAiRetryAutoConfiguration.class, OpenAiAutoConfiguration.class))
.withPropertyValues("spring.data.mongodb.database=springaisample",
"spring.ai.vectorstore.mongodb.collection-name=test_collection",
// "spring.ai.vectorstore.mongodb.path-name=testembedding",
"spring.ai.vectorstore.mongodb.index-name=text_index",
"spring.ai.openai.api-key=" + System.getenv("OPENAI_API_KEY"),
String.format(
"spring.data.mongodb.uri=" + String.format("mongodb://root:root@%s:%s/?directConnection=true",
mongo.getHost(), mongo.getMappedPort(27778))));
@Test
public void addAndSearch() {
contextRunner.run(context -> {
VectorStore vectorStore = context.getBean(VectorStore.class);
vectorStore.add(documents);
Thread.sleep(5000); // Await a second for the document to be indexed
List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Great").withTopK(1));
assertThat(results).hasSize(1);
Document resultDoc = results.get(0);
assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId());
assertThat(resultDoc.getContent()).isEqualTo(
"Great Depression Great Depression Great Depression Great Depression Great Depression Great Depression");
assertThat(resultDoc.getMetadata()).containsEntry("meta2", "meta2");
// Remove all documents from the store
vectorStore.delete(documents.stream().map(Document::getId).collect(Collectors.toList()));
List<Document> results2 = vectorStore.similaritySearch(SearchRequest.query("Great").withTopK(1));
assertThat(results2).isEmpty();
});
}
} | [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((4002, 4042), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4618, 4658), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package com.thomasvitale.ai.spring;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
class ChatService {
private final ChatClient chatClient;
private final SimpleVectorStore vectorStore;
ChatService(ChatClient chatClient, SimpleVectorStore vectorStore) {
this.chatClient = chatClient;
this.vectorStore = vectorStore;
}
AssistantMessage chatWithDocument(String message) {
var systemPromptTemplate = new SystemPromptTemplate("""
Answer questions given the context information below (DOCUMENTS section) and no prior knowledge,
but act as if you knew this information innately. If the answer is not found in the DOCUMENTS section,
simply state that you don't know the answer. In the answer, include the source file name from which
the context information is extracted from.
DOCUMENTS:
{documents}
""");
List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2));
String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator()));
Map<String,Object> model = Map.of("documents", documents);
var systemMessage = systemPromptTemplate.createMessage(model);
var userMessage = new UserMessage(message);
var prompt = new Prompt(List.of(systemMessage, userMessage));
var chatResponse = chatClient.call(prompt);
return chatResponse.getResult().getOutput();
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1601, 1641), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package com.thomasvitale.ai.spring;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
class ChatService {
private final ChatClient chatClient;
private final SimpleVectorStore vectorStore;
ChatService(ChatClient chatClient, SimpleVectorStore vectorStore) {
this.chatClient = chatClient;
this.vectorStore = vectorStore;
}
AssistantMessage chatWithDocument(String message) {
var systemPromptTemplate = new SystemPromptTemplate("""
Answer questions given the context information below (DOCUMENTS section) and no prior knowledge,
but act as if you knew this information innately. If the answer is not found in the DOCUMENTS section,
simply state that you don't know the answer. In the answer, include the source file name from which
the context information is extracted from.
DOCUMENTS:
{documents}
""");
List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2));
String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator()));
Map<String,Object> model = Map.of("documents", documents);
var systemMessage = systemPromptTemplate.createMessage(model);
var userMessage = new UserMessage(message);
var prompt = new Prompt(List.of(systemMessage, userMessage));
var chatResponse = chatClient.call(prompt);
return chatResponse.getResult().getOutput();
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1601, 1641), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package com.thomasvitale.ai.spring;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.document.DefaultContentFormatter;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.transformer.KeywordMetadataEnricher;
import org.springframework.ai.transformer.SummaryMetadataEnricher;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.List;
@SpringBootApplication
public class DocumentTransformersMetadataOllamaApplication {
@Bean
DefaultContentFormatter defaultContentFormatter() {
return DefaultContentFormatter.builder()
.withExcludedEmbedMetadataKeys("NewEmbedKey")
.withExcludedInferenceMetadataKeys("NewInferenceKey")
.build();
}
@Bean
KeywordMetadataEnricher keywordMetadataEnricher(ChatClient chatClient) {
return new KeywordMetadataEnricher(chatClient, 3);
}
@Bean
SummaryMetadataEnricher summaryMetadataEnricher(ChatClient chatClient) {
return new SummaryMetadataEnricher(chatClient, List.of(
SummaryMetadataEnricher.SummaryType.PREVIOUS,
SummaryMetadataEnricher.SummaryType.CURRENT,
SummaryMetadataEnricher.SummaryType.NEXT));
}
@Bean
SimpleVectorStore documentWriter(EmbeddingClient embeddingClient) {
return new SimpleVectorStore(embeddingClient);
}
public static void main(String[] args) {
SpringApplication.run(DocumentTransformersMetadataOllamaApplication.class, args);
}
}
| [
"org.springframework.ai.document.DefaultContentFormatter.builder"
] | [((763, 953), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((763, 928), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((763, 858), 'org.springframework.ai.document.DefaultContentFormatter.builder')] |
package san.royo.world.infra.config;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.document.MetadataMode;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.OpenAiEmbeddingClient;
import org.springframework.ai.openai.OpenAiEmbeddingOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAIConfiguration {
@Bean
public ChatClient chatoCliente() {
var openAiApi = new OpenAiApi(System.getenv("OPENAI_API_KEY"));
return new OpenAiChatClient(openAiApi, OpenAiChatOptions.builder()
.withModel("gpt-3.5-turbo")
.withTemperature(Float.valueOf(0.4f))
.withMaxTokens(200)
.build());
}
@Bean
public EmbeddingClient embeddingClient() {
var openAiApi = new OpenAiApi(System.getenv("OPENAI_API_KEY"));
return new OpenAiEmbeddingClient(openAiApi, MetadataMode.EMBED, OpenAiEmbeddingOptions.builder()
.withModel("text-embedding-3-small")
.build());
}
}
| [
"org.springframework.ai.openai.OpenAiChatOptions.builder",
"org.springframework.ai.openai.OpenAiEmbeddingOptions.builder"
] | [((813, 999), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((813, 974), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((813, 938), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((813, 884), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1211, 1321), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((1211, 1296), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder')] |
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.ollama.rag;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
@Profile("ollama-rag")
@Configuration
public class OllamaRagClientConfig {
@Value("${ai-client.ollama.base-url}")
private String ollamaBaseUrl;
@Value("${ai-client.ollama.chat.options.model}")
private String ollamaOptionsModelName;
@Value("#{T(Float).parseFloat('${ai-client.ollama.chat.options.temperature}')}")
private float ollamaOptionsTemprature;
/**
* We need to mark this bean as primary because the use of the pgVector dependency brings in the auto-configured OllamaChatClient
* by default
*
* @return
*/
@Primary
@Bean
OllamaChatClient ollamaRagChatClient() {
return new OllamaChatClient(ollamaRagApi())
.withDefaultOptions(OllamaOptions.create()
.withModel(ollamaOptionsModelName)
.withTemperature(ollamaOptionsTemprature));
}
@Bean
public OllamaApi ollamaRagApi() {
return new OllamaApi(ollamaBaseUrl);
}
}
| [
"org.springframework.ai.ollama.api.OllamaOptions.create"
] | [((1250, 1397), 'org.springframework.ai.ollama.api.OllamaOptions.create'), ((1250, 1331), 'org.springframework.ai.ollama.api.OllamaOptions.create')] |
package com.chatbots.app.services.impl;
import com.chatbots.app.models.dto.ChatQuestionRequest;
import com.chatbots.app.models.entities.*;
import com.chatbots.app.repositories.ChatBotRepository;
import com.chatbots.app.repositories.ChatEntryHistoryRepository;
import com.chatbots.app.repositories.ChatEntryRepository;
import com.chatbots.app.repositories.UserRepository;
import com.chatbots.app.services.ChatBotService;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.autoconfigure.openai.OpenAiEmbeddingProperties;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
@RequiredArgsConstructor
public class ChatBotServiceImpl implements ChatBotService{
private final EmbeddingServiceImpl embeddingService;
private final OpenAiChatClient chatClient;
@Value("classpath:templates/assistant-template.st")
private Resource assistantTemplate;
@Value("${application.frontend.url}")
private String defaultOrigin;
private final ChatBotRepository chatBotRepository;
private final ChatEntryRepository chatEntryRepository;
private final ChatEntryHistoryRepository chatEntryHistoryRepository;
private final UserRepository userRepository;
@Override
public String getResponse(ChatQuestionRequest request) {
// valdiate chatbot request origin
ChatBot chatBot = chatBotRepository.findByIdAndDeletedIs(UUID.fromString(request.chatBotId()),false).orElseThrow( () -> new RuntimeException("ChatBot not found"));
if(validateOrigin(request.origin(),chatBot)==false){
throw new RuntimeException("Origin not allowed");
}
validateQuestionsLimit(chatBot.getUser());
// get embedding data and create prompt
String data = getEmbeddingData(UUID.fromString(request.chatBotId()),request.question());
PromptTemplate promptTemplate = new PromptTemplate(assistantTemplate);
Map<String, Object> promptParameters = new HashMap<>();
String instructions = chatBot.getInstructions();
promptParameters.put("instructions", instructions);
promptParameters.put("data", data);
// get chat entry and create new if not exist
Optional<ChatEntry> chatEntry = chatEntryRepository.findByUserCode(request.userCode());
if(chatEntry.isEmpty()){
chatEntry = Optional.of(createNewChatEntry(request.userCode(), chatBot,request.origin()));
}
List<Message> messages = new ArrayList<>();
messages.add(new SystemMessage(promptTemplate.create(promptParameters).getContents()));
if(chatEntry.get().getChatEntryHistories()!=null && !chatEntry.get().getChatEntryHistories().isEmpty()){
chatEntry.get().getChatEntryHistories().forEach(chatEntryHistory -> {
messages.add(new UserMessage(chatEntryHistory.getQuestion()));
messages.add(new AssistantMessage(chatEntryHistory.getAnswer()));
});
}
messages.add(new UserMessage(request.question()));
// call chat client and save chat entry history
Prompt fullPrompt = new Prompt(messages, OpenAiChatOptions.builder()
.withTemperature(chatBot.getTemperature())
.build());
String answer = chatClient.call(fullPrompt).getResult().getOutput().getContent();
saveChatEntryHistory(chatEntry.get(), request.question(), answer);
return answer;
}
private ChatEntry createNewChatEntry(String userCode, ChatBot chatBot,String domain){
byte[] decodedBytes = Base64.getDecoder().decode(domain);
String decodedString = new String(decodedBytes);
ChatEntry chatEntry = ChatEntry.builder()
.userCode(userCode)
.chatBot(chatBot)
.domain(decodedString)
.build();
return chatEntryRepository.save(chatEntry);
}
private String getEmbeddingData(UUID chatBotId,String question){
List<Embedding> embeddings = embeddingService.searchPlaces(chatBotId,question);
List<Embedding> bestMatches = embeddings.subList(0, Math.min(2, embeddings.size()));
return bestMatches.stream()
.map(Embedding::getText)
.reduce((a, b) -> a + "\n" + b)
.orElse("");
}
private ChatEntryHistory saveChatEntryHistory(ChatEntry chatEntry, String question, String answer){
ChatEntryHistory chatEntryHistory = ChatEntryHistory.builder()
.question(question)
.answer(answer)
.chatEntry(chatEntry)
.build();
return chatEntryHistoryRepository.save(chatEntryHistory);
}
@Override
public ChatBot createChatBot(ChatBot chatBot,User user) {
User user1 = this.userRepository.findById(user.getId()).orElseThrow(()-> new RuntimeException("User not found "));
List<ChatBot> chatBots = chatBotRepository.findByUser_IdAndDeletedIs(user1.getId(),false);
if(chatBots.size()>=user1.getSubscription().getChatBotsLimit()){
throw new RuntimeException("You have reached the maximum number of chatbots allowed");
}
chatBot.setUser(user1);
chatBot.setDeleted(false);
chatBot.setTrained(false);
chatBot.setTemperature(0.9f);
chatBot.setInstructions("I want you to act as a support agent. Your name is \"AI Assistant\". You will provide me with answers using the given data. If the answer can't be generated using the given data, say I am not sure. and stop after that. Refuse to answer any question not about (the info or your name,your job,hello word). Never break character.");
chatBot.setChatBackgroundColor("#f3f6f4");
chatBot.setMessageBackgroundColor("#ffffff");
chatBot.setButtonBackgroundColor("#4f46e5");
chatBot.setUserMessageColor("#E5EDFF");
chatBot.setBotMessageColor("#ffffff");
chatBot.setHeaderColor("#ffffff");
String randomName = UUID.randomUUID().toString().substring(0, 5);
chatBot.setLogoUrl("https://img.freepik.com/free-vector/chatbot-chat-message-vectorart_78370-4104.jpg");
chatBot.setTextColor("#362e2e");
chatBot.setInitialMessage("Hello, I am AI Assistant. I am here to help you with the information you need. \n feel free to ask me anything.");
return chatBotRepository.save(chatBot);
}
@Override
public ChatBot updateChatBot(ChatBot chatBot) {
ChatBot chatBotToUpdate = chatBotRepository.findByIdAndDeletedIs(chatBot.getId(),false).orElseThrow( () -> new RuntimeException("ChatBot not found"));
chatBotToUpdate.setName(chatBot.getName());
chatBotToUpdate.setInstructions(chatBot.getInstructions());
chatBotToUpdate.setChatBackgroundColor(chatBot.getChatBackgroundColor());
chatBotToUpdate.setHeaderColor(chatBot.getHeaderColor());
chatBotToUpdate.setLogoUrl(chatBot.getLogoUrl());
chatBotToUpdate.setBotMessageColor(chatBot.getBotMessageColor());
chatBotToUpdate.setUserMessageColor(chatBot.getUserMessageColor());
chatBotToUpdate.setMessageBackgroundColor(chatBot.getMessageBackgroundColor());
chatBotToUpdate.setButtonBackgroundColor(chatBot.getButtonBackgroundColor());
chatBotToUpdate.setTextColor(chatBot.getTextColor());
chatBotToUpdate.setInitialMessage(chatBot.getInitialMessage());
chatBotToUpdate.setTemperature(chatBot.getTemperature());
return chatBotRepository.save(chatBotToUpdate);
}
@Override
public Boolean validateOrigin(String encodedOrigin, ChatBot chatBot){
byte[] decodedBytes = Base64.getDecoder().decode(encodedOrigin);
String decodedString = new String(decodedBytes);
if(decodedString.equals(defaultOrigin)){
return true;
}else if(chatBot.getAllowedOrigins()!=null && chatBot.getAllowedOrigins().stream().anyMatch(allowedOrigin -> allowedOrigin.getOrigin().equals(decodedString))){
return true;
}
return false;
}
@Override
public List<ChatBot> getMyChatBots(Integer userId) {
return chatBotRepository.findByUser_IdAndDeletedIs(userId,false);
}
@Override
public ChatBot getChatBotById(UUID chatBotId,Boolean validateOrigin,String origin) {
ChatBot chatBot = chatBotRepository.findByIdAndDeletedIs(chatBotId,false).orElseThrow(() -> new RuntimeException("ChatBot not found"));
if(validateOrigin){
if(validateOrigin(origin,chatBot)==false){
throw new RuntimeException("Origin not allowed");
}
}
return chatBot;
}
@Override
public void deleteChatBot(UUID chatbot_id){
chatBotRepository.deleteById(chatbot_id);
}
private void validateQuestionsLimit(User user){
List<ChatEntry> chatEntries = chatEntryRepository.findByMonthAndYearAndUserId(new Date().getMonth(), new Date().getYear(), user.getId());
Integer questions = 0;
for (ChatEntry chatEntry : chatEntries) {
questions += chatEntry.getChatEntryHistories().size();
}
if(questions>=user.getSubscription().getUserQuestionsLimitPerMonth()){
throw new RuntimeException("You have reached the maximum number of questions allowed");
}
}
}
| [
"org.springframework.ai.openai.OpenAiChatOptions.builder"
] | [((3785, 3896), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3785, 3871), 'org.springframework.ai.openai.OpenAiChatOptions.builder')] |
/*
* Copyright 2024 Google LLC
*
* 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
*
* http://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 services.ai;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.Media;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.vertexai.gemini.MimeTypeDetector;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient;
import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
@Service
public class VertexAIClient {
private static final Logger logger = LoggerFactory.getLogger(VertexAIClient.class);
private VertexAiGeminiChatClient chatClient;
public VertexAIClient(VertexAiGeminiChatClient chatClient){
this.chatClient = chatClient;
}
public String promptOnImage(String prompt,
String bucketName,
String fileName) throws IOException {
long start = System.currentTimeMillis();
// bucket where image has been uploaded
String imageURL = String.format("gs://%s/%s",bucketName, fileName);
// create User Message for AI framework
var multiModalUserMessage = new UserMessage(prompt,
List.of(new Media(MimeTypeDetector.getMimeType(imageURL), imageURL)));
// call the model of choice
ChatResponse multiModalResponse = chatClient.call(new Prompt(List.of(multiModalUserMessage),
VertexAiGeminiChatOptions.builder()
.withModel(VertexModels.GEMINI_PRO_VISION).build()));
String response = multiModalResponse.getResult().getOutput().getContent();
logger.info("Multi-modal response: " + response);
// response from Vertex is in Markdown, remove annotations
response = response.replaceAll("```json", "").replaceAll("```", "").replace("'", "\"");
logger.info("Elapsed time (chat model): " + (System.currentTimeMillis() - start) + "ms");
// return the response in String format, extract values in caller
return response;
}
public String promptModel(String prompt) {
long start = System.currentTimeMillis();
// prompt Chat model
ChatResponse chatResponse = chatClient.call(new Prompt(prompt,
VertexAiGeminiChatOptions.builder()
.withTemperature(0.4f)
.withModel(VertexModels.GEMINI_PRO)
.build())
);
logger.info("Elapsed time (chat model, with SpringAI): " + (System.currentTimeMillis() - start) + "ms");
String output = chatResponse.getResult().getOutput().getContent();
logger.info("Chat Model output: " + output);
// return model response in String format
return output;
}
public String promptModelwithFunctionCalls(SystemMessage systemMessage,
UserMessage userMessage,
String functionName) {
long start = System.currentTimeMillis();
ChatResponse chatResponse = chatClient.call(new Prompt(List.of(systemMessage, userMessage),
VertexAiGeminiChatOptions.builder()
.withModel("gemini-pro")
.withFunction(functionName).build()));
logger.info("Elapsed time (chat model, with SpringAI): " + (System.currentTimeMillis() - start) + "ms");
String output = chatResponse.getResult().getOutput().getContent();
logger.info("Chat Model output with Function Call: " + output);
// return model response in String format
return output;
}
}
| [
"org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder"
] | [((2166, 2268), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((2166, 2260), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((2992, 3143), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((2992, 3118), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((2992, 3066), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3899, 4107), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3899, 4099), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3899, 4015), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder')] |
package com.example;
import java.util.List;
import java.util.Map;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* ベクトル検索を試す。
*
*/
@RestController
@RequestMapping("/search")
public class VectorSearchController {
@Autowired
private VectorStore vectorStore;
@GetMapping
public Object search(@RequestParam String q) {
SearchRequest request = SearchRequest.query(q).withTopK(1);
// 内部では検索クエリーをOpenAIのEmbeddingでベクトル化し、検索を行っている
List<Document> documents = vectorStore.similaritySearch(request);
return documents.stream().map(doc -> doc.getContent()).toList();
}
/**
* データの準備。
*
*/
@PostMapping
public void addDocuments() {
List<Document> documents = List.of(
new Document(
"Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!",
Map.of("meta1", "meta1")),
new Document("The World is Big and Salvation Lurks Around the Corner"),
new Document("You walk forward facing the past and you turn back toward the future.",
Map.of("meta2", "meta2")));
vectorStore.add(documents);
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((879, 913), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package br.com.valdemarjr.springaiexample.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
/**
* Service responsible for deleting an existing database and initializing a new one with the data
* from the PDF file medicaid-wa-faqs.pdf.
*/
@Service
public class SetupService {
private static final Logger log = LoggerFactory.getLogger(SetupService.class);
@Value("classpath:medicaid-wa-faqs.pdf")
private Resource pdf;
private final JdbcTemplate jdbcTemplate;
private final VectorStore vectorStore;
public SetupService(JdbcTemplate jdbcTemplate, VectorStore vectorStore) {
this.jdbcTemplate = jdbcTemplate;
this.vectorStore = vectorStore;
}
public void init() {
// delete an existent database
jdbcTemplate.update("delete from vector_store");
// initialize a new database with the data from the PDF file
var config =
PdfDocumentReaderConfig.builder()
.withPageExtractedTextFormatter(
new ExtractedTextFormatter.Builder().withNumberOfBottomTextLinesToDelete(3).build())
.build();
var pdfReader = new PagePdfDocumentReader(pdf, config);
var textSplitter = new TokenTextSplitter();
var docs = textSplitter.apply(pdfReader.get());
// store the data in the vector store
vectorStore.accept(docs);
log.info("Vector store finished");
}
}
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder"
] | [((1411, 1611), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1411, 1590), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')] |
package com.demo.stl.aijokes.ask;
import com.demo.stl.aijokes.JokeController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class AskController {
Logger logger = LoggerFactory.getLogger(AskController.class);
private final ChatClient aiClient;
private final VectorStore vectorStore;
@Value("classpath:/rag-prompt-template.st")
private Resource ragPromptTemplate;
@Autowired
public AskController(ChatClient aiClient, VectorStore vectorStore){
this.aiClient = aiClient;
this.vectorStore = vectorStore;
}
@GetMapping("/ask")
public Answer ask(@RequestParam ("question") String question){
List<Document> documents = vectorStore.similaritySearch(SearchRequest.query(question).withTopK(2));
List<String> contentList = documents.stream().map(Document::getContent).toList();
PromptTemplate promptTemplate = new PromptTemplate(ragPromptTemplate);
Map<String, Object> promptParameters = new HashMap<>();
promptParameters.put("input", question);
promptParameters.put("documents", String.join("\n", contentList));
Prompt prompt = promptTemplate.create(promptParameters);
ChatResponse response = aiClient.call(prompt);
return new Answer(response.getResult().getOutput().getContent());
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.query"
] | [((1561, 1602), 'org.springframework.ai.vectorstore.SearchRequest.query')] |
package bootiful.service;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.PgVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@SpringBootApplication
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
@Bean
VectorStore vectorStore(EmbeddingClient ec,
JdbcTemplate t) {
return new PgVectorStore(t, ec);
}
@Bean
TokenTextSplitter tokenTextSplitter() {
return new TokenTextSplitter();
}
static void init(VectorStore vectorStore, JdbcTemplate template, Resource pdfResource)
throws Exception {
template.update("delete from vector_store");
var config = PdfDocumentReaderConfig.builder()
.withPageExtractedTextFormatter(new ExtractedTextFormatter.Builder().withNumberOfBottomTextLinesToDelete(3)
.withNumberOfTopPagesToSkipBeforeDelete(1)
.build())
.withPagesPerDocument(1)
.build();
var pdfReader = new PagePdfDocumentReader(pdfResource, config);
var textSplitter = new TokenTextSplitter();
vectorStore.accept(textSplitter.apply(pdfReader.get()));
}
@Bean
ApplicationRunner applicationRunner(
Chatbot chatbot,
VectorStore vectorStore,
JdbcTemplate jdbcTemplate,
@Value("file://${HOME}/Desktop/pdfs/medicaid-wa-faqs.pdf") Resource resource) {
return args -> {
init(vectorStore, jdbcTemplate, resource);
var response = chatbot.chat("what should I know about the transition to consumer direct care network washington?");
System.out.println(Map.of("response", response));
};
}
}
@Component
class Chatbot {
private final String template = """
You're assisting with questions about services offered by Carina.
Carina is a two-sided healthcare marketplace focusing on home care aides (caregivers)
and their Medicaid in-home care clients (adults and children with developmental disabilities and low income elderly population).
Carina's mission is to build online tools to bring good jobs to care workers, so care workers can provide the
best possible care for those who need it.
Use the information from the DOCUMENTS section to provide accurate answers but act as if you knew this information innately.
If unsure, simply state that you don't know.
DOCUMENTS:
{documents}
""";
private final ChatClient aiClient;
private final VectorStore vectorStore;
Chatbot(ChatClient aiClient, VectorStore vectorStore) {
this.aiClient = aiClient;
this.vectorStore = vectorStore;
}
public String chat(String message) {
var listOfSimilarDocuments = this.vectorStore.similaritySearch(message);
var documents = listOfSimilarDocuments
.stream()
.map(Document::getContent)
.collect(Collectors.joining(System.lineSeparator()));
var systemMessage = new SystemPromptTemplate(this.template)
.createMessage(Map.of("documents", documents));
var userMessage = new UserMessage(message);
var prompt = new Prompt(List.of(systemMessage, userMessage));
var aiResponse = aiClient.call(prompt);
return aiResponse.getResult().getOutput().getContent();
}
} // ...
| [
"org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder"
] | [((1866, 2190), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1866, 2165), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1866, 2124), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')] |
/*
* 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.autoconfigure.openai;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
@ConfigurationProperties(OpenAiChatProperties.CONFIG_PREFIX)
public class OpenAiChatProperties extends OpenAiParentProperties {
public static final String CONFIG_PREFIX = "spring.ai.openai.chat";
public static final String DEFAULT_CHAT_MODEL = "gpt-3.5-turbo";
private static final Double DEFAULT_TEMPERATURE = 0.7;
/**
* Enable OpenAI chat client.
*/
private boolean enabled = true;
@NestedConfigurationProperty
private OpenAiChatOptions options = OpenAiChatOptions.builder()
.withModel(DEFAULT_CHAT_MODEL)
.withTemperature(DEFAULT_TEMPERATURE.floatValue())
.build();
public OpenAiChatOptions getOptions() {
return options;
}
public void setOptions(OpenAiChatOptions options) {
this.options = options;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| [
"org.springframework.ai.openai.OpenAiChatOptions.builder"
] | [((1351, 1475), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1351, 1464), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1351, 1411), 'org.springframework.ai.openai.OpenAiChatOptions.builder')] |
/*
* 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.ollama;
import java.util.List;
import reactor.core.publisher.Flux;
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;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.metadata.ChatGenerationMetadata;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaApi.Message.Role;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.util.StringUtils;
/**
* {@link ChatClient} 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
* Library](https://ollama.ai/library). - Llama 2 (7B parameters, 3.8GB size) - Mistral
* (7B parameters, 4.1GB size)
*
* Please refer to the <a href="https://ollama.ai/">official Ollama website</a> for the
* most up-to-date information on available models.
*
* @author Christian Tzolov
* @since 0.8.0
*/
public class OllamaChatClient implements ChatClient, StreamingChatClient {
/**
* Low-level Ollama API library.
*/
private final OllamaApi chatApi;
/**
* Default options to be used for all chat requests.
*/
private OllamaOptions defaultOptions = OllamaOptions.create().withModel(OllamaOptions.DEFAULT_MODEL);
public OllamaChatClient(OllamaApi chatApi) {
this.chatApi = chatApi;
}
/**
* @deprecated Use {@link OllamaOptions#setModel} instead.
*/
@Deprecated
public OllamaChatClient withModel(String model) {
this.defaultOptions.setModel(model);
return this;
}
public OllamaChatClient withDefaultOptions(OllamaOptions options) {
this.defaultOptions = options;
return this;
}
@Override
public ChatResponse call(Prompt prompt) {
OllamaApi.ChatResponse response = this.chatApi.chat(ollamaChatRequest(prompt, false));
var generator = new Generation(response.message().content());
if (response.promptEvalCount() != null && response.evalCount() != null) {
generator = generator
.withGenerationMetadata(ChatGenerationMetadata.from("unknown", extractUsage(response)));
}
return new ChatResponse(List.of(generator));
}
@Override
public Flux<ChatResponse> stream(Prompt prompt) {
Flux<OllamaApi.ChatResponse> response = this.chatApi.streamingChat(ollamaChatRequest(prompt, true));
return response.map(chunk -> {
Generation generation = (chunk.message() != null) ? new Generation(chunk.message().content())
: new Generation("");
if (Boolean.TRUE.equals(chunk.done())) {
generation = generation
.withGenerationMetadata(ChatGenerationMetadata.from("unknown", extractUsage(chunk)));
}
return new ChatResponse(List.of(generation));
});
}
private Usage extractUsage(OllamaApi.ChatResponse response) {
return new Usage() {
@Override
public Long getPromptTokens() {
return response.promptEvalCount().longValue();
}
@Override
public Long getGenerationTokens() {
return response.evalCount().longValue();
}
};
}
/**
* Package access for testing.
*/
OllamaApi.ChatRequest ollamaChatRequest(Prompt prompt, boolean stream) {
List<OllamaApi.Message> ollamaMessages = prompt.getInstructions()
.stream()
.filter(message -> message.getMessageType() == MessageType.USER
|| message.getMessageType() == MessageType.ASSISTANT
|| message.getMessageType() == MessageType.SYSTEM)
.map(m -> OllamaApi.Message.builder(toRole(m)).withContent(m.getContent()).build())
.toList();
// runtime options
OllamaOptions runtimeOptions = null;
if (prompt.getOptions() != null) {
if (prompt.getOptions() instanceof ChatOptions runtimeChatOptions) {
runtimeOptions = ModelOptionsUtils.copyToTarget(runtimeChatOptions, ChatOptions.class,
OllamaOptions.class);
}
else {
throw new IllegalArgumentException("Prompt options are not of type ChatOptions: "
+ prompt.getOptions().getClass().getSimpleName());
}
}
OllamaOptions mergedOptions = ModelOptionsUtils.merge(runtimeOptions, this.defaultOptions, OllamaOptions.class);
// Override the model.
if (!StringUtils.hasText(mergedOptions.getModel())) {
throw new IllegalArgumentException("Model is not set!");
}
String model = mergedOptions.getModel();
return OllamaApi.ChatRequest.builder(model)
.withStream(stream)
.withMessages(ollamaMessages)
.withOptions(mergedOptions)
.build();
}
private OllamaApi.Message.Role toRole(Message message) {
switch (message.getMessageType()) {
case USER:
return Role.USER;
case ASSISTANT:
return Role.ASSISTANT;
case SYSTEM:
return Role.SYSTEM;
default:
throw new IllegalArgumentException("Unsupported message type: " + message.getMessageType());
}
}
} | [
"org.springframework.ai.ollama.api.OllamaApi.Message.builder",
"org.springframework.ai.ollama.api.OllamaOptions.create",
"org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder"
] | [((2314, 2375), 'org.springframework.ai.ollama.api.OllamaOptions.create'), ((4470, 4542), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((4470, 4534), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((4470, 4506), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((5329, 5464), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((5329, 5452), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((5329, 5421), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((5329, 5388), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((5329, 5365), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder')] |
package com.example.springaivectorsearchdemo.services;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class VectorServices {
@Autowired
VectorStore vectorStore;
public List<Document> simpleVector(String query){
List<Document> documents = List.of(
new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
new Document("The World is Big and Salvation Lurks Around the Corner"),
new Document("The World is Big"),
new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));
//add documents to the vector store
vectorStore.add(documents);
// retrieve documents similar to the given query
List<Document> results = vectorStore.similaritySearch(
SearchRequest.defaults()
.withQuery(query)
.withTopK(2)
);
return results;
}
}
| [
"org.springframework.ai.vectorstore.SearchRequest.defaults"
] | [((1227, 1332), 'org.springframework.ai.vectorstore.SearchRequest.defaults'), ((1227, 1294), 'org.springframework.ai.vectorstore.SearchRequest.defaults')] |
package uk.me.jamesburt.image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.image.ImageClient;
import org.springframework.ai.image.ImageOptions;
import org.springframework.ai.image.ImageOptionsBuilder;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Map;
@Controller
public class ImageController {
private static final Logger logger = LoggerFactory.getLogger(ImageController.class);
private final OpenAiChatClient chatClient;
private final ImageClient imageClient;
@Value("classpath:/prompts/imagegen.st")
private Resource imagePrompt;
@Autowired
public ImageController(ImageClient imageClient, OpenAiChatClient chatClient) {
this.imageClient = imageClient;
this.chatClient = chatClient;
}
@GetMapping("safeimagegen")
public String restrictedImageGeneration(@RequestParam(name = "animal") String animal,
@RequestParam(name = "activity") String activity,
@RequestParam(name = "mood") String mood) {
PromptTemplate promptTemplate = new PromptTemplate(imagePrompt);
Message message = promptTemplate.createMessage(Map.of("animal", animal, "activity", activity, "mood", mood));
Prompt prompt = new Prompt(List.of(message));
logger.info(prompt.toString());
ChatResponse response = chatClient.call(prompt);
String generatedImagePrompt = response.getResult().toString();
logger.info("AI responded.");
logger.info(generatedImagePrompt);
ImageOptions imageOptions = ImageOptionsBuilder.builder().withModel("dall-e-3").build();
ImagePrompt imagePrompt = new ImagePrompt(generatedImagePrompt, imageOptions);
ImageResponse imageResponse = imageClient.call(imagePrompt);
String imageUrl = imageResponse.getResult().getOutput().getUrl();
return "redirect:"+imageUrl;
}
}
| [
"org.springframework.ai.image.ImageOptionsBuilder.builder"
] | [((2440, 2499), 'org.springframework.ai.image.ImageOptionsBuilder.builder'), ((2440, 2491), 'org.springframework.ai.image.ImageOptionsBuilder.builder')] |
/*
* 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.autoconfigure.ollama;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Ollama Embedding autoconfiguration properties.
*
* @author Christian Tzolov
* @since 0.8.0
*/
@ConfigurationProperties(OllamaEmbeddingProperties.CONFIG_PREFIX)
public class OllamaEmbeddingProperties {
public static final String CONFIG_PREFIX = "spring.ai.ollama.embedding";
/**
* Enable Ollama embedding client.
*/
private boolean enabled = true;
/**
* Client lever Ollama options. Use this property to configure generative temperature,
* topK and topP and alike parameters. The null values are ignored defaulting to the
* generative's defaults.
*/
@NestedConfigurationProperty
private OllamaOptions options = OllamaOptions.create().withModel(OllamaOptions.DEFAULT_MODEL);
public String getModel() {
return this.options.getModel();
}
public void setModel(String model) {
this.options.setModel(model);
}
public OllamaOptions getOptions() {
return this.options;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return this.enabled;
}
}
| [
"org.springframework.ai.ollama.api.OllamaOptions.create"
] | [((1528, 1589), 'org.springframework.ai.ollama.api.OllamaOptions.create')] |
/*
* 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.autoconfigure.vectorstore.qdrant;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.qdrant.QdrantVectorStore;
import org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* @author Anush Shetty
* @author Eddú Meléndez
* @since 0.8.1
*/
@AutoConfiguration
@ConditionalOnClass({ QdrantVectorStore.class, EmbeddingClient.class })
@EnableConfigurationProperties(QdrantVectorStoreProperties.class)
public class QdrantVectorStoreAutoConfiguration {
@Bean
@ConditionalOnMissingBean(QdrantConnectionDetails.class)
PropertiesQdrantConnectionDetails qdrantConnectionDetails(QdrantVectorStoreProperties properties) {
return new PropertiesQdrantConnectionDetails(properties);
}
@Bean
@ConditionalOnMissingBean
public QdrantVectorStore vectorStore(EmbeddingClient embeddingClient, QdrantVectorStoreProperties properties,
QdrantConnectionDetails connectionDetails) {
var config = QdrantVectorStoreConfig.builder()
.withCollectionName(properties.getCollectionName())
.withHost(connectionDetails.getHost())
.withPort(connectionDetails.getPort())
.withTls(properties.isUseTls())
.withApiKey(properties.getApiKey())
.build();
return new QdrantVectorStore(config, embeddingClient);
}
private static class PropertiesQdrantConnectionDetails implements QdrantConnectionDetails {
private final QdrantVectorStoreProperties properties;
PropertiesQdrantConnectionDetails(QdrantVectorStoreProperties properties) {
this.properties = properties;
}
@Override
public String getHost() {
return this.properties.getHost();
}
@Override
public int getPort() {
return this.properties.getPort();
}
}
}
| [
"org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig.builder"
] | [((1982, 2240), 'org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig.builder'), ((1982, 2228), 'org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig.builder'), ((1982, 2189), 'org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig.builder'), ((1982, 2154), 'org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig.builder'), ((1982, 2112), 'org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig.builder'), ((1982, 2070), 'org.springframework.ai.vectorstore.qdrant.QdrantVectorStore.QdrantVectorStoreConfig.builder')] |
/*
* 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.autoconfigure.mistralai;
import org.springframework.ai.mistralai.MistralAiChatOptions;
import org.springframework.ai.mistralai.api.MistralAiApi;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* @author Ricken Bazolo
* @author Christian Tzolov
* @since 0.8.1
*/
@ConfigurationProperties(MistralAiChatProperties.CONFIG_PREFIX)
public class MistralAiChatProperties extends MistralAiParentProperties {
public static final String CONFIG_PREFIX = "spring.ai.mistralai.chat";
public static final String DEFAULT_CHAT_MODEL = MistralAiApi.ChatModel.TINY.getValue();
private static final Double DEFAULT_TEMPERATURE = 0.7;
private static final Float DEFAULT_TOP_P = 1.0f;
private static final Boolean IS_ENABLED = false;
public MistralAiChatProperties() {
super.setBaseUrl(MistralAiCommonProperties.DEFAULT_BASE_URL);
}
/**
* Enable OpenAI chat client.
*/
private boolean enabled = true;
@NestedConfigurationProperty
private MistralAiChatOptions options = MistralAiChatOptions.builder()
.withModel(DEFAULT_CHAT_MODEL)
.withTemperature(DEFAULT_TEMPERATURE.floatValue())
.withSafePrompt(!IS_ENABLED)
.withTopP(DEFAULT_TOP_P)
.build();
public MistralAiChatOptions getOptions() {
return this.options;
}
public void setOptions(MistralAiChatOptions options) {
this.options = options;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| [
"org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue",
"org.springframework.ai.mistralai.MistralAiChatOptions.builder"
] | [((1290, 1328), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue'), ((1739, 1924), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((1739, 1913), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((1739, 1886), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((1739, 1855), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((1739, 1802), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder')] |
/*
* 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.autoconfigure.bedrock.anthropic3;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi;
import org.springframework.ai.bedrock.anthropic3.Anthropic3ChatOptions;
import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.util.Assert;
/**
* Configuration properties for Bedrock Anthropic Claude 3.
*
* @author Christian Tzolov
* @since 1.0.0
*/
@ConfigurationProperties(BedrockAnthropic3ChatProperties.CONFIG_PREFIX)
public class BedrockAnthropic3ChatProperties {
public static final String CONFIG_PREFIX = "spring.ai.bedrock.anthropic3.chat";
/**
* Enable Bedrock Anthropic chat client. Disabled by default.
*/
private boolean enabled = false;
/**
* The generative id to use. See the {@link AnthropicChatModel} for the supported
* models.
*/
private String model = AnthropicChatModel.CLAUDE_V3_SONNET.id();
@NestedConfigurationProperty
private Anthropic3ChatOptions options = Anthropic3ChatOptions.builder()
.withTemperature(0.7f)
.withMaxTokens(300)
.withTopK(10)
.withAnthropicVersion(Anthropic3ChatBedrockApi.DEFAULT_ANTHROPIC_VERSION)
// .withStopSequences(List.of("\n\nHuman:"))
.build();
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public Anthropic3ChatOptions getOptions() {
return options;
}
public void setOptions(Anthropic3ChatOptions options) {
Assert.notNull(options, "AnthropicChatOptions must not be null");
Assert.notNull(options.getTemperature(), "AnthropicChatOptions.temperature must not be null");
this.options = options;
}
}
| [
"org.springframework.ai.bedrock.anthropic3.Anthropic3ChatOptions.builder",
"org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V3_SONNET.id"
] | [((1685, 1725), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V3_SONNET.id'), ((1799, 2027), 'org.springframework.ai.bedrock.anthropic3.Anthropic3ChatOptions.builder'), ((1799, 1969), 'org.springframework.ai.bedrock.anthropic3.Anthropic3ChatOptions.builder'), ((1799, 1893), 'org.springframework.ai.bedrock.anthropic3.Anthropic3ChatOptions.builder'), ((1799, 1877), 'org.springframework.ai.bedrock.anthropic3.Anthropic3ChatOptions.builder'), ((1799, 1855), 'org.springframework.ai.bedrock.anthropic3.Anthropic3ChatOptions.builder')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.