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')]
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card