code
stringlengths
1.04k
14.1k
apis
sequencelengths
1
7
extract_api
stringlengths
72
2.99k
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')]
/* * 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')]
/* * 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 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.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.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')]
/* * 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.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.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.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.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.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.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.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.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.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.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.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 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')]
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.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')]
package com.thomasvitale.ai.spring; import jakarta.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.document.Document; 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.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class DocumentInitializer { private static final Logger log = LoggerFactory.getLogger(DocumentInitializer.class); private final SimpleVectorStore vectorStore; @Value("classpath:documents/story1.pdf") Resource pdfFile1; @Value("classpath:documents/story2.pdf") Resource pdfFile2; public DocumentInitializer(SimpleVectorStore vectorStore) { this.vectorStore = vectorStore; } @PostConstruct public void run() { List<Document> documents = new ArrayList<>(); log.info("Loading PDF files as Documents"); var pdfReader1 = new PagePdfDocumentReader(pdfFile1); documents.addAll(pdfReader1.get()); log.info("Loading PDF files as Documents after reformatting"); var pdfReader2 = new PagePdfDocumentReader(pdfFile2, PdfDocumentReaderConfig.builder() .withPageExtractedTextFormatter(ExtractedTextFormatter.builder() .withNumberOfTopPagesToSkipBeforeDelete(0) .withNumberOfBottomTextLinesToDelete(1) .withNumberOfTopTextLinesToDelete(1) .build()) .withPagesPerDocument(1) .build()); documents.addAll(pdfReader2.get()); log.info("Creating and storing Embeddings from Documents"); vectorStore.add(documents); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((1474, 1880), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1474, 1855), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1474, 1814), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1556, 1813), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1556, 1780), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1556, 1719), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1556, 1655), 'org.springframework.ai.reader.ExtractedTextFormatter.builder')]
package org.springframework.ai.aot.test.pgvector; 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 PgVectorStoreApplication { public static void main(String[] args) { new SpringApplicationBuilder(PgVectorStoreApplication.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" ]
[((1540, 1581), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package com.xisui.springbootai; import org.junit.jupiter.api.Test; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.reader.JsonReader; import org.springframework.ai.reader.TextReader; import org.springframework.ai.reader.tika.TikaDocumentReader; 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.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import java.util.List; /** * @author tycoding * @since 2024/3/5 */ @SpringBootTest public class EmbeddingTest { @Autowired private EmbeddingClient embeddingClient; @Autowired private VectorStore vectorStore; @Value("classpath:data.json") private Resource jsonResource; @Value("classpath:data.docx") private Resource docxResource; @Value("classpath:data.xlsx") private Resource excelResource; @Value("classpath:data.txt") private Resource txtResource; @Test void embedding() { String text = "我是一个Java程序员"; List<Double> embedList = embeddingClient.embed(text); List<Document> documents = List.of(new Document(text)); vectorStore.add(documents); } @Test void search() { List<Document> d1 = vectorStore.similaritySearch("我是"); List<Document> d2 = vectorStore.similaritySearch(SearchRequest.query("我是").withTopK(5)); System.out.println("----"); } @Test void jsonReader() { JsonReader reader = new JsonReader(jsonResource, "type", "keyword"); vectorStore.add(reader.get()); } @Test void txtReader() { TextReader reader = new TextReader(txtResource); reader.getCustomMetadata().put("filename", "data1.txt"); vectorStore.add(reader.get()); } @Test void docReader() { TikaDocumentReader reader = new TikaDocumentReader(docxResource); vectorStore.add(reader.get()); } @Test void filter() { } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1589, 1630), '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.embedding; import org.junit.jupiter.api.Test; import org.springframework.ai.embedding.EmbeddingRequest; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.ai.openai.OpenAiEmbeddingClient; import org.springframework.ai.openai.OpenAiEmbeddingOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest class EmbeddingIT { @Autowired private OpenAiEmbeddingClient embeddingClient; @Test void defaultEmbedding() { assertThat(embeddingClient).isNotNull(); EmbeddingResponse embeddingResponse = embeddingClient.embedForResponse(List.of("Hello World")); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0)).isNotNull(); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(1536); assertThat(embeddingResponse.getMetadata()).containsEntry("model", "text-embedding-ada-002"); assertThat(embeddingResponse.getMetadata()).containsEntry("total-tokens", 2); assertThat(embeddingResponse.getMetadata()).containsEntry("prompt-tokens", 2); assertThat(embeddingClient.dimensions()).isEqualTo(1536); } @Test void embedding3Large() { EmbeddingResponse embeddingResponse = embeddingClient.call(new EmbeddingRequest(List.of("Hello World"), OpenAiEmbeddingOptions.builder().withModel("text-embedding-3-large").build())); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0)).isNotNull(); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(3072); assertThat(embeddingResponse.getMetadata()).containsEntry("model", "text-embedding-3-large"); assertThat(embeddingResponse.getMetadata()).containsEntry("total-tokens", 2); assertThat(embeddingResponse.getMetadata()).containsEntry("prompt-tokens", 2); // assertThat(embeddingClient.dimensions()).isEqualTo(3072); } @Test void textEmbeddingAda002() { EmbeddingResponse embeddingResponse = embeddingClient.call(new EmbeddingRequest(List.of("Hello World"), OpenAiEmbeddingOptions.builder().withModel("text-embedding-3-small").build())); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0)).isNotNull(); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(1536); assertThat(embeddingResponse.getMetadata()).containsEntry("model", "text-embedding-3-small"); assertThat(embeddingResponse.getMetadata()).containsEntry("total-tokens", 2); assertThat(embeddingResponse.getMetadata()).containsEntry("prompt-tokens", 2); // assertThat(embeddingClient.dimensions()).isEqualTo(3072); } }
[ "org.springframework.ai.openai.OpenAiEmbeddingOptions.builder" ]
[((2092, 2168), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((2092, 2160), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((2846, 2922), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((2846, 2914), '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 static org.assertj.core.api.Assertions.assertThat; 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.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.RedisVectorStore.MetadataField; import org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.core.io.DefaultResourceLoader; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import com.redis.testcontainers.RedisStackContainer; /** * @author Julien Ruaux */ @Testcontainers class RedisVectorStoreIT { @Container static RedisStackContainer redisContainer = new RedisStackContainer( RedisStackContainer.DEFAULT_IMAGE_NAME.withTag(RedisStackContainer.DEFAULT_TAG)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestApplication.class); 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); } } @BeforeEach void cleanDatabase() { this.contextRunner.run(context -> context.getBean(RedisVectorStore.class).getJedis().flushAll()); } @Test void ensureIndexGetsCreated() { this.contextRunner.run(context -> { assertThat(context.getBean(RedisVectorStore.class) .getJedis() .ftList() .contains(RedisVectorStore.DEFAULT_INDEX_NAME)); }); } @Test void addAndSearch() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); 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("meta1", RedisVectorStore.DISTANCE_FIELD_NAME); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).isEmpty(); }); } @Test void searchWithFilters() throws InterruptedException { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2020)); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "NL")); var bgDocument2 = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2023)); vectorStore.add(List.of(bgDocument, nlDocument, bgDocument2)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("The World").withTopK(5)); assertThat(results).hasSize(3); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'NL'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG'")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG' && year == 2020")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("NOT(country == 'BG' && year == 2020)")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(nlDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(nlDocument.getId(), bgDocument2.getId()); }); } @Test void documentUpdate() { 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)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5)); assertThat(results).hasSize(1); 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(RedisVectorStore.DISTANCE_FIELD_NAME); 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)); results = vectorStore.similaritySearch(SearchRequest.query("FooBar").withTopK(5)); 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(RedisVectorStore.DISTANCE_FIELD_NAME); vectorStore.delete(List.of(document.getId())); }); } @Test void searchWithThreshold() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> fullResult = vectorStore .similaritySearch(SearchRequest.query("Spring").withTopK(5).withSimilarityThresholdAll()); List<Float> distances = fullResult.stream() .map(doc -> (Float) doc.getMetadata().get(RedisVectorStore.DISTANCE_FIELD_NAME)) .toList(); assertThat(distances).hasSize(3); float threshold = (distances.get(0) + distances.get(1)) / 2; List<Document> results = vectorStore .similaritySearch(SearchRequest.query("Spring").withTopK(5).withSimilarityThreshold(1 - threshold)); 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()).containsKeys("meta1", RedisVectorStore.DISTANCE_FIELD_NAME); }); } @SpringBootConfiguration @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) public static class TestApplication { @Bean public RedisVectorStore vectorStore(EmbeddingClient embeddingClient) { return new RedisVectorStore(RedisVectorStoreConfig.builder() .withURI(redisContainer.getRedisURI()) .withMetadataFields(MetadataField.tag("meta1"), MetadataField.tag("meta2"), MetadataField.tag("country"), MetadataField.numeric("year")) .build(), embeddingClient); } @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder" ]
[((2022, 2101), 'com.redis.testcontainers.RedisStackContainer.DEFAULT_IMAGE_NAME.withTag'), ((6436, 6464), 'java.util.UUID.randomUUID'), ((9159, 9394), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((9159, 9381), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((9159, 9234), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.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.filter; import org.junit.jupiter.api.Test; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.filter.FilterExpressionTextParser.FilterExpressionParseException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Christian Tzolov */ public class SearchRequestTests { @Test public void createDefaults() { var emptyRequest = SearchRequest.defaults(); assertThat(emptyRequest.getQuery()).isEqualTo(""); checkDefaults(emptyRequest); } @Test public void createQuery() { var emptyRequest = SearchRequest.query("New Query"); assertThat(emptyRequest.getQuery()).isEqualTo("New Query"); checkDefaults(emptyRequest); } @Test public void createFrom() { var originalRequest = SearchRequest.query("New Query") .withTopK(696) .withSimilarityThreshold(0.678) .withFilterExpression("country == 'NL'"); var newRequest = SearchRequest.from(originalRequest); assertThat(newRequest).isNotSameAs(originalRequest); assertThat(newRequest.getQuery()).isEqualTo(originalRequest.getQuery()); assertThat(newRequest.getTopK()).isEqualTo(originalRequest.getTopK()); assertThat(newRequest.getFilterExpression()).isEqualTo(originalRequest.getFilterExpression()); assertThat(newRequest.getSimilarityThreshold()).isEqualTo(originalRequest.getSimilarityThreshold()); } @Test public void withQuery() { var emptyRequest = SearchRequest.defaults(); assertThat(emptyRequest.getQuery()).isEqualTo(""); emptyRequest.withQuery("New Query"); assertThat(emptyRequest.getQuery()).isEqualTo("New Query"); } @Test() public void withSimilarityThreshold() { var request = SearchRequest.query("Test").withSimilarityThreshold(0.678); assertThat(request.getSimilarityThreshold()).isEqualTo(0.678); request.withSimilarityThreshold(0.9); assertThat(request.getSimilarityThreshold()).isEqualTo(0.9); assertThatThrownBy(() -> { request.withSimilarityThreshold(-1); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Similarity threshold must be in [0,1] range."); assertThatThrownBy(() -> { request.withSimilarityThreshold(1.1); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Similarity threshold must be in [0,1] range."); } @Test() public void withTopK() { var request = SearchRequest.query("Test").withTopK(66); assertThat(request.getTopK()).isEqualTo(66); request.withTopK(89); assertThat(request.getTopK()).isEqualTo(89); assertThatThrownBy(() -> { request.withTopK(-1); }).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("TopK should be positive."); } @Test() public void withFilterExpression() { var request = SearchRequest.query("Test").withFilterExpression("country == 'BG' && year >= 2022"); assertThat(request.getFilterExpression()).isEqualTo(new Filter.Expression(Filter.ExpressionType.AND, new Filter.Expression(Filter.ExpressionType.EQ, new Filter.Key("country"), new Filter.Value("BG")), new Filter.Expression(Filter.ExpressionType.GTE, new Filter.Key("year"), new Filter.Value(2022)))); assertThat(request.hasFilterExpression()).isTrue(); request.withFilterExpression("active == true"); assertThat(request.getFilterExpression()).isEqualTo( new Filter.Expression(Filter.ExpressionType.EQ, new Filter.Key("active"), new Filter.Value(true))); assertThat(request.hasFilterExpression()).isTrue(); request.withFilterExpression(new FilterExpressionBuilder().eq("country", "NL").build()); assertThat(request.getFilterExpression()).isEqualTo( new Filter.Expression(Filter.ExpressionType.EQ, new Filter.Key("country"), new Filter.Value("NL"))); assertThat(request.hasFilterExpression()).isTrue(); request.withFilterExpression((String) null); assertThat(request.getFilterExpression()).isNull(); assertThat(request.hasFilterExpression()).isFalse(); request.withFilterExpression((Filter.Expression) null); assertThat(request.getFilterExpression()).isNull(); assertThat(request.hasFilterExpression()).isFalse(); assertThatThrownBy(() -> { request.withFilterExpression("FooBar"); }).isInstanceOf(FilterExpressionParseException.class) .hasMessageContaining("Error: no viable alternative at input 'FooBar'"); } private void checkDefaults(SearchRequest request) { assertThat(request.getFilterExpression()).isNull(); assertThat(request.getSimilarityThreshold()).isEqualTo(SearchRequest.SIMILARITY_THRESHOLD_ACCEPT_ALL); assertThat(request.getTopK()).isEqualTo(SearchRequest.DEFAULT_TOP_K); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1490, 1619), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((1490, 1575), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((1490, 1540), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((2392, 2450), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3066, 3106), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3451, 3534), '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.cohere.api; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; 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.CohereEmbeddingResponse; 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 CohereEmbeddingBedrockApiIT { CohereEmbeddingBedrockApi api = new CohereEmbeddingBedrockApi( CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); @Test public void embedText() { CohereEmbeddingRequest request = new CohereEmbeddingRequest( List.of("I like to eat apples", "I like to eat oranges"), CohereEmbeddingRequest.InputType.SEARCH_DOCUMENT, CohereEmbeddingRequest.Truncate.NONE); CohereEmbeddingResponse response = api.embedding(request); assertThat(response).isNotNull(); assertThat(response.texts()).isEqualTo(request.texts()); assertThat(response.embeddings()).hasSize(2); assertThat(response.embeddings().get(0)).hasSize(1024); } }
[ "org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id" ]
[((1642, 1696), 'org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id'), ((1750, 1771), '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.bedrock.titan; 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.Disabled; 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 software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel; 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 BedrockTitanChatClientIT { @Autowired private BedrockTitanChatClient 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"); } @Disabled("TODO: Fix the parser instructions to return the correct format") @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); } @Disabled("TODO: Fix the parser instructions to return the correct format") @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) { } @Disabled("TODO: Fix the parser instructions to return the correct format") @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); } @Disabled("TODO: Fix the parser instructions to return the correct format") @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 TitanChatBedrockApi titanApi() { return new TitanChatBedrockApi(TitanChatModel.TITAN_TEXT_EXPRESS_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); } @Bean public BedrockTitanChatClient titanChatClient(TitanChatBedrockApi titanApi) { return new BedrockTitanChatClient(titanApi); } } }
[ "org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id" ]
[((6965, 7006), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id'), ((7062, 7083), '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.bedrock.cohere; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.LogitBias; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.ReturnLikelihoods; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.Truncate; import org.springframework.ai.chat.prompt.Prompt; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class BedrockCohereChatCreateRequestTests { private CohereChatBedrockApi chatApi = new CohereChatBedrockApi(CohereChatModel.COHERE_COMMAND_V14.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); @Test public void createRequestWithChatOptions() { var client = new BedrockCohereChatClient(chatApi, BedrockCohereChatOptions.builder() .withTemperature(66.6f) .withTopK(66) .withTopP(0.66f) .withMaxTokens(678) .withStopSequences(List.of("stop1", "stop2")) .withReturnLikelihoods(ReturnLikelihoods.ALL) .withNumGenerations(3) .withLogitBias(new LogitBias("t", 6.6f)) .withTruncate(Truncate.END) .build()); CohereChatRequest request = client.createRequest(new Prompt("Test message content"), true); assertThat(request.prompt()).isNotEmpty(); assertThat(request.stream()).isTrue(); assertThat(request.temperature()).isEqualTo(66.6f); assertThat(request.topK()).isEqualTo(66); assertThat(request.topP()).isEqualTo(0.66f); assertThat(request.maxTokens()).isEqualTo(678); assertThat(request.stopSequences()).containsExactly("stop1", "stop2"); assertThat(request.returnLikelihoods()).isEqualTo(ReturnLikelihoods.ALL); assertThat(request.numGenerations()).isEqualTo(3); assertThat(request.logitBias()).isEqualTo(new LogitBias("t", 6.6f)); assertThat(request.truncate()).isEqualTo(Truncate.END); request = client.createRequest(new Prompt("Test message content", BedrockCohereChatOptions.builder() .withTemperature(99.9f) .withTopK(99) .withTopP(0.99f) .withMaxTokens(888) .withStopSequences(List.of("stop3", "stop4")) .withReturnLikelihoods(ReturnLikelihoods.GENERATION) .withNumGenerations(13) .withLogitBias(new LogitBias("t", 9.9f)) .withTruncate(Truncate.START) .build()), false ); assertThat(request.prompt()).isNotEmpty(); assertThat(request.stream()).isFalse(); assertThat(request.temperature()).isEqualTo(99.9f); assertThat(request.topK()).isEqualTo(99); assertThat(request.topP()).isEqualTo(0.99f); assertThat(request.maxTokens()).isEqualTo(888); assertThat(request.stopSequences()).containsExactly("stop3", "stop4"); assertThat(request.returnLikelihoods()).isEqualTo(ReturnLikelihoods.GENERATION); assertThat(request.numGenerations()).isEqualTo(13); assertThat(request.logitBias()).isEqualTo(new LogitBias("t", 9.9f)); assertThat(request.truncate()).isEqualTo(Truncate.START); } }
[ "org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id" ]
[((1726, 1765), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id'), ((1819, 1840), '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.mistralai; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletion; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionChunk; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionFinishReason; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.Role; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest; import org.springframework.ai.mistralai.api.MistralAiApi.Embedding; import org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingList; import org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingRequest; import org.springframework.ai.retry.RetryUtils; import org.springframework.ai.retry.TransientAiException; import org.springframework.http.ResponseEntity; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; import org.springframework.retry.support.RetryTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; /** * @author Christian Tzolov */ @SuppressWarnings("unchecked") @ExtendWith(MockitoExtension.class) public class MistralAiRetryTests { private class TestRetryListener implements RetryListener { int onErrorRetryCount = 0; int onSuccessRetryCount = 0; @Override public <T, E extends Throwable> void onSuccess(RetryContext context, RetryCallback<T, E> callback, T result) { onSuccessRetryCount = context.getRetryCount(); } @Override public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) { onErrorRetryCount = context.getRetryCount(); } } private TestRetryListener retryListener; private RetryTemplate retryTemplate; private @Mock MistralAiApi mistralAiApi; private MistralAiChatClient chatClient; private MistralAiEmbeddingClient embeddingClient; @BeforeEach public void beforeEach() { retryTemplate = RetryUtils.DEFAULT_RETRY_TEMPLATE; retryListener = new TestRetryListener(); retryTemplate.registerListener(retryListener); chatClient = new MistralAiChatClient(mistralAiApi, MistralAiChatOptions.builder() .withTemperature(0.7f) .withTopP(1f) .withSafePrompt(false) .withModel(MistralAiApi.ChatModel.TINY.getValue()) .build(), null, retryTemplate); embeddingClient = new MistralAiEmbeddingClient(mistralAiApi, MetadataMode.EMBED, MistralAiEmbeddingOptions.builder().withModel(MistralAiApi.EmbeddingModel.EMBED.getValue()).build(), retryTemplate); } @Test public void mistralAiChatTransientError() { var choice = new ChatCompletion.Choice(0, new ChatCompletionMessage("Response", Role.ASSISTANT), ChatCompletionFinishReason.STOP); ChatCompletion expectedChatCompletion = new ChatCompletion("id", "chat.completion", 789l, "model", List.of(choice), new MistralAiApi.Usage(10, 10, 10)); when(mistralAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedChatCompletion))); var result = chatClient.call(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void mistralAiChatNonTransientError() { when(mistralAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.call(new Prompt("text"))); } @Test public void mistralAiChatStreamTransientError() { var choice = new ChatCompletionChunk.ChunkChoice(0, new ChatCompletionMessage("Response", Role.ASSISTANT), ChatCompletionFinishReason.STOP); ChatCompletionChunk expectedChatCompletion = new ChatCompletionChunk("id", "chat.completion.chunk", 789l, "model", List.of(choice)); when(mistralAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(Flux.just(expectedChatCompletion)); var result = chatClient.stream(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.collectList().block().get(0).getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void mistralAiChatStreamNonTransientError() { when(mistralAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.stream(new Prompt("text"))); } @Test public void mistralAiEmbeddingTransientError() { EmbeddingList<Embedding> expectedEmbeddings = new EmbeddingList<>("list", List.of(new Embedding(0, List.of(9.9, 8.8))), "model", new MistralAiApi.Usage(10, 10, 10)); when(mistralAiApi.embeddings(isA(EmbeddingRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedEmbeddings))); var result = embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null)); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput()).isEqualTo(List.of(9.9, 8.8)); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void mistralAiEmbeddingNonTransientError() { when(mistralAiApi.embeddings(isA(EmbeddingRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null))); } }
[ "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue", "org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue" ]
[((3594, 3632), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue'), ((3808, 3852), 'org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue')]
/* * 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.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 static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".*") public class FunctionCallbackInPromptIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallbackInPromptIT.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)); @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?"); var promptOptions = OpenAiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("CurrentWeatherService") .withDescription("Get the weather in location") .withResponseConverter((response) -> "" + response.temp() + response.unit()) .build())) .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30.0", "10.0", "15.0"); }); } @Test void streamingFunctionCallTest() { 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?"); var promptOptions = OpenAiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("CurrentWeatherService") .withDescription("Get the weather in location") .withResponseConverter((response) -> "" + response.temp() + response.unit()) .build())) .build(); Flux<ChatResponse> response = chatClient.stream(new Prompt(List.of(userMessage), 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("30.0", "30"); assertThat(content).containsAnyOf("10.0", "10"); assertThat(content).containsAnyOf("15.0", "15"); }); } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder" ]
[((2715, 3039), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2715, 3026), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2778, 3024), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2778, 3010), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2778, 2928), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2778, 2875), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3648, 3972), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3648, 3959), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3711, 3957), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3711, 3943), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3711, 3861), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3711, 3808), '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.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.mistralai.MistralAiAutoConfiguration; 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.MistralAiChatClient; import org.springframework.ai.mistralai.MistralAiChatOptions; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".*") public class PaymentStatusPromptIT { private final Logger logger = LoggerFactory.getLogger(WeatherServicePromptIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.mistralai.apiKey=" + System.getenv("MISTRAL_AI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, MistralAiAutoConfiguration.class)); public record Transaction(@JsonProperty(required = true, value = "transaction_id") String id) { } public record Status(@JsonProperty(required = true, value = "status") String status) { } record StatusDate(String status, String date) { } // Assuming we have the following payment data. public static final Map<Transaction, StatusDate> DATA = Map.of(new Transaction("T1001"), new StatusDate("Paid", "2021-10-05"), new Transaction("T1002"), new StatusDate("Unpaid", "2021-10-06"), new Transaction("T1003"), new StatusDate("Paid", "2021-10-07"), new Transaction("T1004"), new StatusDate("Paid", "2021-10-05"), new Transaction("T1005"), new StatusDate("Pending", "2021-10-08")); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.mistralai.chat.options.model=" + MistralAiApi.ChatModel.SMALL.getValue()) .run(context -> { MistralAiChatClient chatClient = context.getBean(MistralAiChatClient.class); UserMessage userMessage = new UserMessage("What's the status of my transaction with id T1001?"); var promptOptions = MistralAiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new Function<Transaction, Status>() { public Status apply(Transaction transaction) { return new Status(DATA.get(transaction).status()); } }) .withName("retrievePaymentStatus") .withDescription("Get payment status of a transaction") .build())) .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("T1001"); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("paid"); }); } }
[ "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue", "org.springframework.ai.mistralai.MistralAiChatOptions.builder" ]
[((3188, 3227), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue'), ((3459, 3856), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((3459, 3842), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((3526, 3840), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3526, 3825), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3526, 3763), '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.jurassic2.api; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatRequest; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatResponse; 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 Ai21Jurassic2ChatBedrockApiIT { Ai21Jurassic2ChatBedrockApi api = new Ai21Jurassic2ChatBedrockApi(Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id(), Region.US_EAST_1.id()); @Test public void chatCompletion() { Ai21Jurassic2ChatRequest request = new Ai21Jurassic2ChatRequest("Give me the names of 3 famous pirates?", 0.9f, 0.9f, 100, null, // List.of("END"), new Ai21Jurassic2ChatRequest.IntegerScalePenalty(1, true, true, true, true, true), new Ai21Jurassic2ChatRequest.FloatScalePenalty(0.5f, true, true, true, true, true), new Ai21Jurassic2ChatRequest.IntegerScalePenalty(1, true, true, true, true, true)); Ai21Jurassic2ChatResponse response = api.chatCompletion(request); assertThat(response).isNotNull(); assertThat(response.completions()).isNotEmpty(); assertThat(response.amazonBedrockInvocationMetrics()).isNull(); String responseContent = response.completions() .stream() .map(c -> c.data().text()) .collect(Collectors.joining(System.lineSeparator())); assertThat(responseContent).contains("Blackbeard"); } // Note: Ai21Jurassic2 doesn't support streaming yet! }
[ "org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id" ]
[((1542, 1586), 'org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id'), ((1591, 1612), '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.autoconfigure.azure.tool; import java.util.List; import java.util.function.Function; 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.azure.openai.AzureOpenAiAutoConfiguration; 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.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; 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.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+") @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+") class FunctionCallWithFunctionBeanIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withPropertyValues( // @formatter:off "spring.ai.azure.openai.api-key=" + System.getenv("AZURE_OPENAI_API_KEY"), "spring.ai.azure.openai.endpoint=" + System.getenv("AZURE_OPENAI_ENDPOINT")) // @formatter:onn .withConfiguration(AutoConfigurations.of(AzureOpenAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner.withPropertyValues("spring.ai.azure.openai.chat.options.model=gpt-4-0125-preview") .run(context -> { ChatClient chatClient = context.getBean(AzureOpenAiChatClient.class); UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, Paris and in Tokyo? Use Multi-turn function calling."); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), AzureOpenAiChatOptions.builder().withFunction("weatherFunction").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); response = chatClient.call(new Prompt(List.of(userMessage), AzureOpenAiChatOptions.builder().withFunction("weatherFunction3").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } @Configuration static class Config { @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction() { return new MockWeatherService(); } // Relies on the Request's JsonClassDescription annotation to provide the // function description. @Bean public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction3() { MockWeatherService weatherService = new MockWeatherService(); return (weatherService::apply); } } }
[ "org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder" ]
[((2882, 2954), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2882, 2946), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3164, 3237), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3164, 3229), '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.vertexai.palm2; 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.vertexai.palm2.api.VertexAiPaLm2Api; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class VertexAiPaLm2ChatRequestTests { VertexAiPaLm2ChatClient client = new VertexAiPaLm2ChatClient(new VertexAiPaLm2Api("bla")); @Test public void createRequestWithDefaultOptions() { var request = client.createRequest(new Prompt("Test message content")); assertThat(request.prompt().messages()).hasSize(1); assertThat(request.candidateCount()).isEqualTo(1); assertThat(request.temperature()).isEqualTo(0.7f); assertThat(request.topK()).isEqualTo(20); assertThat(request.topP()).isNull(); } @Test public void createRequestWithPromptVertexAiOptions() { // Runtime options should override the default options. VertexAiPaLm2ChatOptions promptOptions = VertexAiPaLm2ChatOptions.builder() .withTemperature(0.8f) .withTopP(0.5f) .withTopK(99) // .withCandidateCount(2) .build(); var request = client.createRequest(new Prompt("Test message content", promptOptions)); assertThat(request.prompt().messages()).hasSize(1); assertThat(request.candidateCount()).isEqualTo(1); assertThat(request.temperature()).isEqualTo(0.8f); assertThat(request.topK()).isEqualTo(99); assertThat(request.topP()).isEqualTo(0.5f); } @Test public void createRequestWithPromptPortableChatOptions() { // runtime options. ChatOptions portablePromptOptions = ChatOptionsBuilder.builder() .withTemperature(0.9f) .withTopK(100) .withTopP(0.6f) .build(); var request = client.createRequest(new Prompt("Test message content", portablePromptOptions)); assertThat(request.prompt().messages()).hasSize(1); assertThat(request.candidateCount()).isEqualTo(1); assertThat(request.temperature()).isEqualTo(0.9f); assertThat(request.topK()).isEqualTo(100); assertThat(request.topP()).isEqualTo(0.6f); } }
[ "org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder" ]
[((2330, 2433), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2330, 2421), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2330, 2402), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2330, 2384), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder')]
package org.springframework.ai.aot.test.openai; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonClassDescription; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.OpenAiEmbeddingClient; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; 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; import org.springframework.context.annotation.Description; import org.springframework.context.annotation.ImportRuntimeHints; @SpringBootApplication @ImportRuntimeHints(OpenaiAotDemoApplication.MockWeatherServiceRuntimeHints.class) public class OpenaiAotDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(OpenaiAotDemoApplication.class) .web(WebApplicationType.NONE) .run(args); } @Bean ApplicationRunner applicationRunner(OpenAiChatClient chatClient, OpenAiEmbeddingClient embeddingClient) { return args -> { System.out.println("ChatClient: " + chatClient.getClass().getName()); System.out.println("EmbeddingClient: " + embeddingClient.getClass().getName()); // Synchronous Chat Client String response = chatClient.call("Tell me a joke."); System.out.println("SYNC RESPONSE: " + response); // Streaming Chat Client Flux<ChatResponse> flux = chatClient.stream(new Prompt("Tell me a joke.")); String fluxResponse = flux.collectList().block().stream().map(r -> r.getResult().getOutput().getContent()) .collect(Collectors.joining()); System.out.println("ASYNC RESPONSE: " + fluxResponse); // Embedding Client List<List<Double>> embeddings = embeddingClient.embed(List.of("Hello", "World")); System.out.println("EMBEDDINGS SIZE: " + embeddings.size()); // Function calling ChatResponse weatherResponse = chatClient.call(new Prompt("What is the weather in Amsterdam, Netherlands?", OpenAiChatOptions.builder().withFunction("weatherInfo").build())); System.out.println("WEATHER RESPONSE: " + weatherResponse.getResult().getOutput().getContent()); }; } @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherInfo() { return new MockWeatherService(); } public static class MockWeatherService implements Function<MockWeatherService.Request, MockWeatherService.Response> { @JsonInclude(Include.NON_NULL) @JsonClassDescription("Weather API request") public record Request( @JsonProperty(required = true, value = "location") @JsonPropertyDescription("The city and state e.g. San Francisco, CA") String location, @JsonProperty(required = true, value = "lat") @JsonPropertyDescription("The city latitude") double lat, @JsonProperty(required = true, value = "lon") @JsonPropertyDescription("The city longitude") double lon, @JsonProperty(required = true, value = "unit") @JsonPropertyDescription("Temperature unit") Unit unit) { } public enum Unit { C, F; } @JsonInclude(Include.NON_NULL) public record Response(double temperature, double feels_like, double temp_min, double temp_max, int pressure, int humidity, Unit unit) { } @Override public Response apply(Request request) { System.out.println("Weather request: " + request); return new Response(11, 15, 20, 2, 53, 45, Unit.C); } } public static class MockWeatherServiceRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { // Register method for reflection var mcs = MemberCategory.values(); hints.reflection().registerType(MockWeatherService.Request.class, mcs); hints.reflection().registerType(MockWeatherService.Response.class, mcs); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((2890, 2953), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2890, 2945), '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.openai.audio.speech; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.openai.OpenAiAudioSpeechOptions; import org.springframework.ai.openai.OpenAiTestConfiguration; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.metadata.audio.OpenAiAudioSpeechResponseMetadata; import org.springframework.ai.openai.testutils.AbstractIT; import org.springframework.boot.test.context.SpringBootTest; import reactor.core.publisher.Flux; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = OpenAiTestConfiguration.class) @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") class OpenAiSpeechClientIT extends AbstractIT { private static final Float SPEED = 1.0f; @Test void shouldSuccessfullyStreamAudioBytesForEmptyMessage() { Flux<byte[]> response = openAiAudioSpeechClient .stream("Today is a wonderful day to build something people love!"); assertThat(response).isNotNull(); assertThat(response.collectList().block()).isNotNull(); System.out.println(response.collectList().block()); } @Test void shouldProduceAudioBytesDirectlyFromMessage() { byte[] audioBytes = openAiAudioSpeechClient.call("Today is a wonderful day to build something people love!"); assertThat(audioBytes).hasSizeGreaterThan(0); } @Test void shouldGenerateNonEmptyMp3AudioFromSpeechPrompt() { OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .withModel(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); SpeechPrompt speechPrompt = new SpeechPrompt("Today is a wonderful day to build something people love!", speechOptions); SpeechResponse response = openAiAudioSpeechClient.call(speechPrompt); byte[] audioBytes = response.getResult().getOutput(); assertThat(response.getResults()).hasSize(1); assertThat(response.getResults().get(0).getOutput()).isNotEmpty(); assertThat(audioBytes).hasSizeGreaterThan(0); } @Test void speechRateLimitTest() { OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .withModel(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); SpeechPrompt speechPrompt = new SpeechPrompt("Today is a wonderful day to build something people love!", speechOptions); SpeechResponse response = openAiAudioSpeechClient.call(speechPrompt); OpenAiAudioSpeechResponseMetadata metadata = response.getMetadata(); assertThat(metadata).isNotNull(); assertThat(metadata.getRateLimit()).isNotNull(); assertThat(metadata.getRateLimit().getRequestsLimit()).isPositive(); assertThat(metadata.getRateLimit().getRequestsLimit()).isPositive(); } @Test void shouldStreamNonEmptyResponsesForValidSpeechPrompts() { OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .withModel(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); SpeechPrompt speechPrompt = new SpeechPrompt("Today is a wonderful day to build something people love!", speechOptions); Flux<SpeechResponse> responseFlux = openAiAudioSpeechClient.stream(speechPrompt); assertThat(responseFlux).isNotNull(); List<SpeechResponse> responses = responseFlux.collectList().block(); assertThat(responses).isNotNull(); responses.forEach(response -> { System.out.println("Audio data chunk size: " + response.getResult().getOutput().length); assertThat(response.getResult().getOutput()).isNotEmpty(); }); } }
[ "org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder" ]
[((2180, 2431), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2419), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2368), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2291), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2270), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3189), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3177), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3126), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3049), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3028), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 4058), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 4046), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 3995), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 3918), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 3897), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.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.weaviate; import org.junit.jupiter.api.Test; import org.springframework.ai.autoconfigure.vectorstore.weaviate.WeaviateVectorStoreAutoConfiguration; import org.springframework.ai.autoconfigure.vectorstore.weaviate.WeaviateVectorStoreProperties; 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.ai.vectorstore.WeaviateVectorStore; 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.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.weaviate.WeaviateContainer; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @SpringJUnitConfig @Testcontainers @TestPropertySource(properties = { "spring.ai.vectorstore.weaviate.filter-field.country=TEXT", "spring.ai.vectorstore.weaviate.filter-field.year=NUMBER", "spring.ai.vectorstore.weaviate.filter-field.active=BOOLEAN", "spring.ai.vectorstore.weaviate.filter-field.price=NUMBER" }) class WeaviateContainerConnectionDetailsFactoryTest { @Container @ServiceConnection static WeaviateContainer weaviateContainer = new WeaviateContainer("semitechnologies/weaviate:1.22.4"); @Autowired private WeaviateVectorStoreProperties properties; @Autowired private VectorStore vectorStore; @Test public void addAndSearchWithFilters() { assertThat(properties.getFilterField()).hasSize(4); assertThat(properties.getFilterField().get("country")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.TEXT); assertThat(properties.getFilterField().get("year")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.NUMBER); assertThat(properties.getFilterField().get("active")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.BOOLEAN); assertThat(properties.getFilterField().get("price")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.NUMBER); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Bulgaria", "price", 3.14, "active", true, "year", 2020)); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Netherlands", "price", 1.57, "active", false, "year", 2023)); 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()); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("price > 1.57 && active == true")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("year in [2020, 2023]")); assertThat(results).hasSize(2); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("year > 2020 && year <= 2023")); 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(WeaviateVectorStoreAutoConfiguration.class) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3730, 3774), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5055, 5128), 'java.util.List.of'), ((5055, 5119), 'java.util.List.of'), ((5055, 5095), '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.vertexai.gemini.function; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.google.cloud.vertexai.VertexAI; import org.junit.jupiter.api.AfterEach; 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.ChatResponse; import org.springframework.ai.chat.Generation; 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.model.function.FunctionCallbackWrapper; import org.springframework.ai.model.function.FunctionCallbackWrapper.Builder.SchemaType; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.TransportType; 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 @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*") public class VertexAiGeminiChatClientFunctionCallingIT { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private VertexAiGeminiChatClient vertexGeminiClient; @AfterEach public void afterEach() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void functionCallExplicitOpenApiSchema() { UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, in Paris and in Tokyo, Japan? Use Multi-turn function calling. Provide answer for all requested locations."); List<Message> messages = new ArrayList<>(List.of(userMessage)); String openApiSchema = """ { "type": "OBJECT", "properties": { "location": { "type": "STRING", "description": "The city and state e.g. San Francisco, CA" }, "unit" : { "type" : "STRING", "enum" : [ "C", "F" ], "description" : "Temperature unit" } }, "required": ["location", "unit"] } """; var promptOptions = VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("getCurrentWeather") .withDescription("Get the current weather in a given location") .withInputTypeSchema(openApiSchema) .build())) .build(); ChatResponse response = vertexGeminiClient.call(new Prompt(messages, promptOptions)); logger.info("Response: {}", response); // System.out.println(response.getResult().getOutput().getContent()); 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"); } @Test public void functionCallTestInferredOpenApiSchema() { // UserMessage userMessage = new UserMessage("What's the weather like in San // Francisco, Paris and Tokyo?"); UserMessage userMessage = new UserMessage("What's the weather like in Paris?"); List<Message> messages = new ArrayList<>(List.of(userMessage)); var promptOptions = VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withSchemaType(SchemaType.OPEN_API_SCHEMA) .withName("getCurrentWeather") .withDescription("Get the current weather in a given location") .build())) .build(); ChatResponse response = vertexGeminiClient.call(new Prompt(messages, promptOptions)); logger.info("Response: {}", response); // System.out.println(response.getResult().getOutput().getContent()); // 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"); } @Test public void functionCallTestInferredOpenApiSchemaStream() { UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, in Paris and in Tokyo? Use Multi-turn function calling."); List<Message> messages = new ArrayList<>(List.of(userMessage)); var promptOptions = VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withSchemaType(SchemaType.OPEN_API_SCHEMA) .withName("getCurrentWeather") .withDescription("Get the current weather in a given location") .build())) .build(); Flux<ChatResponse> response = vertexGeminiClient.stream(new Prompt(messages, promptOptions)); String responseString = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", responseString); assertThat(responseString).containsAnyOf("15.0", "15"); assertThat(responseString).containsAnyOf("30.0", "30"); assertThat(responseString).containsAnyOf("10.0", "10"); } @SpringBootConfiguration public static class TestConfiguration { @Bean public VertexAI vertexAiApi() { String projectId = System.getenv("VERTEX_AI_GEMINI_PROJECT_ID"); String location = System.getenv("VERTEX_AI_GEMINI_LOCATION"); return new VertexAI(projectId, location); } @Bean public VertexAiGeminiChatClient vertexAiEmbedding(VertexAI vertexAi) { return new VertexAiGeminiChatClient(vertexAi, VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withTemperature(0.9f) .withTransportType(TransportType.REST) .build()); } } }
[ "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder" ]
[((3304, 3673), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3304, 3661), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3304, 3411), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3354, 3410), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((3446, 3659), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3446, 3646), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3446, 3606), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3446, 3538), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4501, 4878), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4501, 4866), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4501, 4608), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4551, 4607), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((4643, 4864), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4643, 4851), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4643, 4783), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4643, 4748), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5682, 6059), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5682, 6047), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5682, 5789), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5732, 5788), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((5824, 6045), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5824, 6032), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5824, 5964), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5824, 5929), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7053, 7252), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7053, 7237), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7053, 7192), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7053, 7163), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7106, 7162), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue')]
package com.kousenit.springaiexamples.rag; 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.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.embedding.EmbeddingClient; import org.springframework.ai.reader.JsonReader; 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.SimpleVectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import java.io.File; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class RagService { private static final Logger logger = LoggerFactory.getLogger(RagService.class); @Value("classpath:/data/bikes.json") private Resource bikesResource; @Value("classpath:/prompts/system-qa.st") private Resource systemBikePrompt; private final ChatClient aiClient; private final EmbeddingClient embeddingClient; @Autowired public RagService(@Qualifier("openAiChatClient") ChatClient aiClient, @Qualifier("openAiEmbeddingClient") EmbeddingClient embeddingClient) { this.aiClient = aiClient; this.embeddingClient = embeddingClient; } public Generation retrieve(String message) { SimpleVectorStore vectorStore = new SimpleVectorStore(embeddingClient); File bikeVectorStore = new File("src/main/resources/data/bikeVectorStore.json"); if (bikeVectorStore.exists()) { vectorStore.load(bikeVectorStore); } else { // Step 1 - Load JSON document as Documents logger.info("Loading JSON as Documents"); JsonReader jsonReader = new JsonReader(bikesResource, "name", "price", "shortDescription", "description"); List<Document> documents = jsonReader.get(); logger.info("Loading JSON as Documents"); TextSplitter splitter = new TokenTextSplitter(); List<Document> splitDocuments = splitter.apply(documents); // Step 2 - Create embeddings and save to vector store logger.info("Creating Embeddings..."); vectorStore.add(splitDocuments); logger.info("Embeddings created."); vectorStore.save(bikeVectorStore); } // Step 3 retrieve related documents to query logger.info("Retrieving relevant documents"); List<Document> similarDocuments = vectorStore.similaritySearch( SearchRequest.query(message).withTopK(4)); logger.info(String.format("Found %s relevant documents.", similarDocuments.size())); // Step 4 Embed documents into SystemMessage with the `system-qa.st` prompt template Message systemMessage = getSystemMessage(similarDocuments); UserMessage userMessage = new UserMessage(message); // Step 5 - Ask the AI model logger.info("Asking AI model to reply to question."); Prompt prompt = new Prompt(List.of(systemMessage, userMessage)); logger.info(prompt.toString()); ChatResponse response = aiClient.call(prompt); logger.info("AI responded."); logger.info(response.getResult().toString()); return response.getResult(); } private Message getSystemMessage(List<Document> similarDocuments) { String documents = similarDocuments.stream() .map(Document::getContent) .collect(Collectors.joining("\n")); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemBikePrompt); return systemPromptTemplate.createMessage(Map.of("documents", documents)); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3128, 3168), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package org.example.springai.retriever; import java.util.List; import java.util.Objects; import java.util.Optional; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentRetriever; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; /** * spring-ai 에서 삭제된 클래스 들고옴 * 아래는 해당 커밋메시지 * b35c71061ed1560241a4e3708775cd703acf2553 */ public class VectorStoreRetriever implements DocumentRetriever { private VectorStore vectorStore; int k; Optional<Double> threshold = Optional.empty(); public VectorStoreRetriever(VectorStore vectorStore) { this(vectorStore, 4); } public VectorStoreRetriever(VectorStore vectorStore, int k) { Objects.requireNonNull(vectorStore, "VectorStore must not be null"); this.vectorStore = vectorStore; this.k = k; } public VectorStoreRetriever(VectorStore vectorStore, int k, double threshold) { Objects.requireNonNull(vectorStore, "VectorStore must not be null"); this.vectorStore = vectorStore; this.k = k; this.threshold = Optional.of(threshold); } public VectorStore getVectorStore() { return vectorStore; } public int getK() { return k; } public Optional<Double> getThreshold() { return threshold; } @Override public List<Document> retrieve(String query) { SearchRequest request = SearchRequest.query(query).withTopK(this.k); if (threshold.isPresent()) { request.withSimilarityThreshold(this.threshold.get()); } return this.vectorStore.similaritySearch(request); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1529, 1572), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package ai.ssudikon.springai; 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.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.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 SpringAiExpApplication { public static void main(String[] args) { SpringApplication.run(SpringAiExpApplication.class, args); } @Component static class AlexPopeAiClient { private final VectorStore vectorStore; private final ChatClient chatClient; AlexPopeAiClient(VectorStore vectorStore, ChatClient chatClient) { this.vectorStore = vectorStore; this.chatClient = chatClient; } public String chat(String query) { var prompt = """ You're assisting with questions about alexander pope. Alexander Pope (1688–1744) was an English poet, translator, and satirist known for his significant contributions to 18th-century English literature. He is renowned for works like "The Rape of the Lock," "The Dunciad," and "An Essay on Criticism." Pope's writing style often featured satire and discursive poetry, and his translations of Homer were also notable. 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} """; var listOfSimilarDocs = vectorStore.similaritySearch(query); var docs = listOfSimilarDocs.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator())); var systemMessage = new SystemPromptTemplate(prompt).createMessage(Map.of("documents", docs)); var userMessage = new UserMessage(query); var promptList = new Prompt(List.of(systemMessage, userMessage)); var aiResponse = chatClient.call(promptList); return aiResponse.getResult().getOutput().getContent(); } } @Bean ApplicationRunner applicationRunner(VectorStore vectorStore, @Value("file:/Users/sudikonda/Developer/Java/IdeaProjects/spring-ai-exp/src/main/resources/AlexanderPope-Wikipedia.pdf") Resource resource, JdbcTemplate jdbcTemplate, ChatClient chatClient, AlexPopeAiClient alexPopeAiClient) { return args -> { init(vectorStore, resource, jdbcTemplate); String chatResponse = alexPopeAiClient.chat("Who is Alexander Pope"); System.out.println("chatResponse = " + chatResponse); }; } private static void init(VectorStore vectorStore, Resource resource, JdbcTemplate jdbcTemplate) { jdbcTemplate.update("DELETE FROM vector_store"); PdfDocumentReaderConfig config = PdfDocumentReaderConfig.builder().withPageExtractedTextFormatter(new ExtractedTextFormatter.Builder().withNumberOfBottomTextLinesToDelete(3).withNumberOfTopPagesToSkipBeforeDelete(1).build()).withPagesPerDocument(1).build(); PagePdfDocumentReader pagePdfDocumentReader = new PagePdfDocumentReader(resource, config); TokenTextSplitter tokenTextSplitter = new TokenTextSplitter(); List<Document> docs = tokenTextSplitter.apply(pagePdfDocumentReader.get()); vectorStore.accept(docs); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder" ]
[((3902, 4125), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3902, 4117), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3902, 4093), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')]
package com.example.springaioutputparserdemo; import com.example.springaioutputparserdemo.entity.ActorsFilms; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.image.*; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.ai.parser.BeanOutputParser; 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; import java.util.Map; @RestController public class OutputParserController { @Autowired private ChatClient chatClient; @Autowired private ImageClient openAImageClient; @GetMapping("/ai/output") public ActorsFilms generate(@RequestParam(value = "actor", defaultValue = "Jeff Bridges") String actor) { var outputParser = new BeanOutputParser<>(ActorsFilms.class); String userMessage = """ Generate the filmography for the actor {actor}. {format} """; PromptTemplate promptTemplate = new PromptTemplate(userMessage, Map.of("actor", actor, "format", outputParser.getFormat() )); Prompt prompt = promptTemplate.create(); Generation generation = chatClient.call(prompt).getResult(); ActorsFilms actorsFilms = outputParser.parse(generation.getOutput().getContent()); return actorsFilms; } @GetMapping("/image") public Image getImage(){ ImageResponse response = openAImageClient.call( new ImagePrompt("Give me clear and HD image of a" + " football player on ground", OpenAiImageOptions.builder() .withQuality("hd") .withN(4) .withHeight(1024) .withWidth(1024).build()) ); //return response.getResult().getOutput().toString(); return response.getResult().getOutput(); } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((1895, 2115), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2107), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2060), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2012), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 1972), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
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(""" You're assisting with questions about products in a bicycle catalog. 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. 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" ]
[((1539, 1579), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package com.alok.ai.spring.ollama; import com.alok.ai.spring.model.Message; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/ollama/chat") @RestController public class OllamaChatController { private final OllamaApi ollamaApi; private final String model; private final OllamaApi.Message geographyTeacherRoleContextMessage = OllamaApi.Message.builder(OllamaApi.Message.Role.ASSISTANT) .withContent("You are geography teacher. You are talking to a student.") .build(); private final OllamaApi.Message historyTeacherRoleContextMessage = OllamaApi.Message.builder(OllamaApi.Message.Role.ASSISTANT) .withContent("You are history teacher. You are talking to a student.") .build(); @Autowired public OllamaChatController(OllamaApi ollamaApi, @Value("${spring.ai.ollama.chat.model}") String model) { this.ollamaApi = ollamaApi; this.model = model; } @PostMapping(value = "/teacher/geography") public ResponseEntity<OllamaApi.Message> chatWithGeographyTeacher( @RequestBody Message message ) { return ResponseEntity.ok(ollamaApi.chat(OllamaApi.ChatRequest.builder(model) .withStream(false) // not streaming .withMessages(List.of( geographyTeacherRoleContextMessage, OllamaApi.Message.builder(OllamaApi.Message.Role.USER) .withContent(message.question()) .build() ) ) .withOptions(OllamaOptions.create().withTemperature(0.9f)) .build()).message()); } @PostMapping(value = "/teacher/history") public ResponseEntity<OllamaApi.Message> chatWithHistoryTeacher( @RequestBody Message message ) { return ResponseEntity.ok(ollamaApi.chat(OllamaApi.ChatRequest.builder(model) .withStream(false) // not streaming .withMessages(List.of( historyTeacherRoleContextMessage, OllamaApi.Message.builder(OllamaApi.Message.Role.USER) .withContent(message.question()) .build() ) ) .withOptions(OllamaOptions.create().withTemperature(0.9f)) .build()).message()); } }
[ "org.springframework.ai.ollama.api.OllamaApi.Message.builder", "org.springframework.ai.ollama.api.OllamaOptions.create", "org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder" ]
[((661, 826), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((661, 805), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((661, 720), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 1063), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 1042), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 959), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1477, 1993), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1968), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1893), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1548), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1513), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1689, 1849), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1689, 1808), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1689, 1743), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1923, 1967), 'org.springframework.ai.ollama.api.OllamaOptions.create'), ((2225, 2771), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2746), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2671), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2296), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2261), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2451, 2627), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2451, 2578), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2451, 2505), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2701, 2745), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
package com.example.springaivectorsearchqueryjson.services; import org.springframework.ai.document.Document; import org.springframework.ai.reader.JsonMetadataGenerator; import org.springframework.ai.reader.JsonReader; 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.stereotype.Service; import java.util.List; import java.util.Map; @Service public class VectorService { @Autowired VectorStore vectorStore; @Value("classpath:/data/bikes.json") Resource bikesResouce; public List<Document> queryJSONVector(String query){ // read json file JsonReader jsonReader = new JsonReader(bikesResouce, new ProductMetadataGenerator(), "name","shortDescription", "description", "price","tags"); // create document object List<Document> documents = jsonReader.get(); // add to vectorstore vectorStore.add(documents); // query vector search List<Document> results = vectorStore.similaritySearch( SearchRequest.defaults() .withQuery(query) .withTopK(1) ); return results ; } public class ProductMetadataGenerator implements JsonMetadataGenerator { @Override public Map<String, Object> generate(Map<String, Object> jsonMap) { return Map.of("name", jsonMap.get("name"), "shortDescription", jsonMap.get("shortDescription")); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.defaults" ]
[((1301, 1406), 'org.springframework.ai.vectorstore.SearchRequest.defaults'), ((1301, 1368), 'org.springframework.ai.vectorstore.SearchRequest.defaults')]
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.openai; 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.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Profile("openai") @Configuration public class OpenAiClientConfig { @Value("${ai-client.openai.api-key}") private String openAiApiKey; @Value("${ai-client.openai.chat.model}") private String openAiModelName; @Value("#{T(Float).parseFloat('${ai-client.openai.chat.temperature}')}") private float openAiTemperature; @Value("${ai-client.openai.chat.max-tokens}") private int openAiMaxTokens; @Bean public OpenAiApi openAiChatApi() { return new OpenAiApi(openAiApiKey); } @Bean OpenAiChatClient openAiChatClient(OpenAiApi openAiApi) { return new OpenAiChatClient(openAiApi, OpenAiChatOptions.builder() .withModel(openAiModelName) .withTemperature(openAiTemperature) .withMaxTokens(openAiMaxTokens) .build()) ; } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((1124, 1352), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1319), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1263), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1203), '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.openai; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * OpenAI Image autoconfiguration properties. * * @author Thomas Vitale * @since 0.8.0 */ @ConfigurationProperties(OpenAiImageProperties.CONFIG_PREFIX) public class OpenAiImageProperties extends OpenAiParentProperties { public static final String CONFIG_PREFIX = "spring.ai.openai.image"; /** * Enable OpenAI Image client. */ private boolean enabled = true; /** * Options for OpenAI Image API. */ @NestedConfigurationProperty private OpenAiImageOptions options = OpenAiImageOptions.builder().build(); public OpenAiImageOptions getOptions() { return options; } public void setOptions(OpenAiImageOptions options) { this.options = options; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((1375, 1411), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]