code
stringlengths
1.02k
14.1k
apis
sequencelengths
1
7
extract_api
stringlengths
72
2.99k
/* * 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.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.image.ImageMessage; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.openai.OpenAiAudioTranscriptionClient; import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.OpenAiEmbeddingClient; import org.springframework.ai.openai.OpenAiEmbeddingOptions; import org.springframework.ai.openai.OpenAiImageClient; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletion; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionChunk; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionFinishReason; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionMessage; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionMessage.Role; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionRequest; import org.springframework.ai.openai.api.OpenAiApi.Embedding; import org.springframework.ai.openai.api.OpenAiApi.EmbeddingList; import org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.api.OpenAiAudioApi.StructuredResponse; import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptResponseFormat; import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest; import org.springframework.ai.openai.api.OpenAiImageApi; import org.springframework.ai.openai.api.OpenAiImageApi.Data; import org.springframework.ai.openai.api.OpenAiImageApi.OpenAiImageRequest; import org.springframework.ai.openai.api.OpenAiImageApi.OpenAiImageResponse; import org.springframework.ai.openai.audio.transcription.AudioTranscriptionPrompt; import org.springframework.ai.openai.audio.transcription.AudioTranscriptionResponse; import org.springframework.ai.retry.RetryUtils; import org.springframework.ai.retry.TransientAiException; import org.springframework.core.io.ClassPathResource; import org.springframework.http.ResponseEntity; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; import org.springframework.retry.support.RetryTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; /** * @author Christian Tzolov */ @SuppressWarnings("unchecked") @ExtendWith(MockitoExtension.class) public class OpenAiRetryTests { private class TestRetryListener implements RetryListener { int onErrorRetryCount = 0; int onSuccessRetryCount = 0; @Override public <T, E extends Throwable> void onSuccess(RetryContext context, RetryCallback<T, E> callback, T result) { onSuccessRetryCount = context.getRetryCount(); } @Override public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) { onErrorRetryCount = context.getRetryCount(); } } private TestRetryListener retryListener; private RetryTemplate retryTemplate; private @Mock OpenAiApi openAiApi; private @Mock OpenAiAudioApi openAiAudioApi; private @Mock OpenAiImageApi openAiImageApi; private OpenAiChatClient chatClient; private OpenAiEmbeddingClient embeddingClient; private OpenAiAudioTranscriptionClient audioTranscriptionClient; private OpenAiImageClient imageClient; @BeforeEach public void beforeEach() { retryTemplate = RetryUtils.DEFAULT_RETRY_TEMPLATE; retryListener = new TestRetryListener(); retryTemplate.registerListener(retryListener); chatClient = new OpenAiChatClient(openAiApi, OpenAiChatOptions.builder().build(), null, retryTemplate); embeddingClient = new OpenAiEmbeddingClient(openAiApi, MetadataMode.EMBED, OpenAiEmbeddingOptions.builder().build(), retryTemplate); audioTranscriptionClient = new OpenAiAudioTranscriptionClient(openAiAudioApi, OpenAiAudioTranscriptionOptions.builder() .withModel("model") .withResponseFormat(TranscriptResponseFormat.JSON) .build(), retryTemplate); imageClient = new OpenAiImageClient(openAiImageApi, OpenAiImageOptions.builder().build(), retryTemplate); } @Test public void openAiChatTransientError() { var choice = new ChatCompletion.Choice(ChatCompletionFinishReason.STOP, 0, new ChatCompletionMessage("Response", Role.ASSISTANT), null); ChatCompletion expectedChatCompletion = new ChatCompletion("id", List.of(choice), 666l, "model", null, null, new OpenAiApi.Usage(10, 10, 10)); when(openAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedChatCompletion))); var result = chatClient.call(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiChatNonTransientError() { when(openAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.call(new Prompt("text"))); } @Test public void openAiChatStreamTransientError() { var choice = new ChatCompletionChunk.ChunkChoice(ChatCompletionFinishReason.STOP, 0, new ChatCompletionMessage("Response", Role.ASSISTANT), null); ChatCompletionChunk expectedChatCompletion = new ChatCompletionChunk("id", List.of(choice), 666l, "model", null, null); when(openAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(Flux.just(expectedChatCompletion)); var result = chatClient.stream(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.collectList().block().get(0).getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiChatStreamNonTransientError() { when(openAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.stream(new Prompt("text"))); } @Test public void openAiEmbeddingTransientError() { EmbeddingList<Embedding> expectedEmbeddings = new EmbeddingList<>("list", List.of(new Embedding(0, List.of(9.9, 8.8))), "model", new OpenAiApi.Usage(10, 10, 10)); when(openAiApi.embeddings(isA(EmbeddingRequest.class))).thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedEmbeddings))); var result = embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null)); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput()).isEqualTo(List.of(9.9, 8.8)); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiEmbeddingNonTransientError() { when(openAiApi.embeddings(isA(EmbeddingRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null))); } @Test public void openAiAudioTranscriptionTransientError() { var expectedResponse = new StructuredResponse("nl", 6.7f, "Transcription Text", List.of(), List.of()); when(openAiAudioApi.createTranscription(isA(TranscriptionRequest.class), isA(Class.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedResponse))); AudioTranscriptionResponse result = audioTranscriptionClient .call(new AudioTranscriptionPrompt(new ClassPathResource("speech/jfk.flac"))); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput()).isEqualTo(expectedResponse.text()); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiAudioTranscriptionNonTransientError() { when(openAiAudioApi.createTranscription(isA(TranscriptionRequest.class), isA(Class.class))) .thenThrow(new RuntimeException("Transient Error 1")); assertThrows(RuntimeException.class, () -> audioTranscriptionClient .call(new AudioTranscriptionPrompt(new ClassPathResource("speech/jfk.flac")))); } @Test public void openAiImageTransientError() { var expectedResponse = new OpenAiImageResponse(678l, List.of(new Data("url678", "b64", "prompt"))); when(openAiImageApi.createImage(isA(OpenAiImageRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedResponse))); var result = imageClient.call(new ImagePrompt(List.of(new ImageMessage("Image Message")))); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput().getUrl()).isEqualTo("url678"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiImageNonTransientError() { when(openAiImageApi.createImage(isA(OpenAiImageRequest.class))) .thenThrow(new RuntimeException("Transient Error 1")); assertThrows(RuntimeException.class, () -> imageClient.call(new ImagePrompt(List.of(new ImageMessage("Image Message"))))); } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder", "org.springframework.ai.openai.OpenAiImageOptions.builder", "org.springframework.ai.openai.OpenAiEmbeddingOptions.builder" ]
[((4961, 4996), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((5101, 5141), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((5243, 5379), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((5243, 5365), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((5243, 5309), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((5455, 5491), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
package org.springframework.ai.aot.test.vertexai.gemini; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonClassDescription; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.MediaData; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Description; import org.springframework.context.annotation.ImportRuntimeHints; import org.springframework.core.io.ClassPathResource; import org.springframework.util.MimeTypeUtils; @SpringBootApplication @ImportRuntimeHints(VertexAiGeminiAotDemoApplication.MockWeatherServiceRuntimeHints.class) public class VertexAiGeminiAotDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(VertexAiGeminiAotDemoApplication.class) .web(WebApplicationType.NONE) .run(args); } @Bean ApplicationRunner applicationRunner(VertexAiGeminiChatClient chatClient) { return args -> { System.out.println("ChatClient: " + chatClient.getClass().getName()); // Synchronous Chat Client String response = chatClient.call("Tell me a joke."); System.out.println("SYNC RESPONSE: " + response); // Streaming Chat Client Flux<ChatResponse> flux = chatClient.stream(new Prompt("Tell me a joke.")); String fluxResponse = flux.collectList().block().stream().map(r -> r.getResult().getOutput().getContent()) .collect(Collectors.joining()); System.out.println("ASYNC RESPONSE: " + fluxResponse); // Multi-modal query. NOTE: switch the model to "gemini-pro-vision"! byte[] data = new ClassPathResource("/vertex.test.png").getContentAsByteArray(); var multiModalUserMessage = new UserMessage("Explain what do you see o this picture?", List.of(new MediaData(MimeTypeUtils.IMAGE_PNG, data))); ChatResponse multiModalResponse = chatClient.call(new Prompt(List.of(multiModalUserMessage), VertexAiGeminiChatOptions.builder().withModel("gemini-pro-vision").build())); System.out.println("MULTI-MODAL RESPONSE: " + multiModalResponse.getResult().getOutput().getContent()); // Function calling var systemMessage = new SystemMessage(""" Use Multi-turn function calling. Answer for all listed locations. If the information was not fetched call the function again. Repeat at most 3 times. """); UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, in Paris and in Tokyo?"); ChatResponse weatherResponse = chatClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("weatherInfo").build())); System.out.println("WEATHER RESPONSE: " + weatherResponse.getResult().getOutput().getContent()); }; } @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherInfo() { return new MockWeatherService(); } public static class MockWeatherService implements Function<MockWeatherService.Request, MockWeatherService.Response> { @JsonInclude(Include.NON_NULL) @JsonClassDescription("Weather API request") public record Request( @JsonProperty(required = true, value = "location") @JsonPropertyDescription("The city and state e.g. San Francisco, CA") String location, @JsonProperty(required = true, value = "unit") @JsonPropertyDescription("Temperature unit") Unit unit) { } public enum Unit { C, F; } @JsonInclude(Include.NON_NULL) public record Response(double temperature, double feels_like, double temp_min, double temp_max, int pressure, int humidity, Unit unit) { } @Override public Response apply(Request request) { System.out.println("Weather request: " + request); return new Response(11, 15, 20, 2, 53, 45, Unit.C); } } public static class MockWeatherServiceRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { // Register method for reflection var mcs = MemberCategory.values(); // hints.reflection().registerType(MockWeatherService.Request.class, mcs); // hints.reflection().registerType(MockWeatherService.Response.class, mcs); hints.resources().registerResource(new ClassPathResource("/vertex.test.png")); } } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder" ]
[((3148, 3222), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3148, 3214), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3937, 4008), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3937, 4000), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.redis; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.ai.ResourceUtils; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import com.redis.testcontainers.RedisStackContainer; /** * @author Julien Ruaux */ @Testcontainers class RedisVectorStoreAutoConfigurationIT { @Container static RedisStackContainer redisContainer = new RedisStackContainer( RedisStackContainer.DEFAULT_IMAGE_NAME.withTag(RedisStackContainer.DEFAULT_TAG)); List<Document> documents = List.of( new Document(ResourceUtils.getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document(ResourceUtils.getText("classpath:/test/data/time.shelter.txt")), new Document( ResourceUtils.getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.redis.index=myIdx") .withPropertyValues("spring.ai.vectorstore.redis.prefix=doc:"); @Test void addAndSearch() { contextRunner.withPropertyValues("spring.ai.vectorstore.redis.uri=" + redisContainer.getRedisURI()) .run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).isEmpty(); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1756, 1835), 'com.redis.testcontainers.RedisStackContainer.DEFAULT_IMAGE_NAME.withTag'), ((2834, 2875), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3344, 3385), '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.image; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.ai.image.ImageGeneration; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.image.ImageResponseMetadata; import org.springframework.ai.openai.OpenAiImageClient; import org.springframework.ai.openai.api.OpenAiImageApi; import org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders; 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 java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; /** * @author John Blum * @author Christian Tzolov * @since 0.7.0 */ @RestClientTest(OpenAiImageClientWithImageResponseMetadataTests.Config.class) public class OpenAiImageClientWithImageResponseMetadataTests { private static String TEST_API_KEY = "sk-1234567890"; @Autowired private OpenAiImageClient openAiImageClient; @Autowired private MockRestServiceServer server; @AfterEach void resetMockServer() { server.reset(); } @Test void aiResponseContainsImageResponseMetadata() { prepareMock(); ImagePrompt prompt = new ImagePrompt("Create an image of a mini golden doodle dog."); ImageResponse response = this.openAiImageClient.call(prompt); assertThat(response).isNotNull(); List<ImageGeneration> imageGenerations = response.getResults(); assertThat(imageGenerations).isNotNull(); assertThat(imageGenerations).hasSize(2); ImageResponseMetadata imageResponseMetadata = response.getMetadata(); assertThat(imageResponseMetadata).isNotNull(); Long created = imageResponseMetadata.created(); assertThat(created).isNotNull(); assertThat(created).isEqualTo(1589478378); ImageResponseMetadata responseMetadata = response.getMetadata(); assertThat(responseMetadata).isNotNull(); } private void prepareMock() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName(), "4000"); httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName(), "999"); httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName(), "2d16h15m29s"); httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName(), "725000"); httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName(), "112358"); httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName(), "27h55s451ms"); server.expect(requestTo("v1/images/generations")) .andExpect(method(HttpMethod.POST)) .andExpect(header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_API_KEY)) .andRespond(withSuccess(getJson(), MediaType.APPLICATION_JSON).headers(httpHeaders)); } private String getJson() { return """ { "created": 1589478378, "data": [ { "url": "https://upload.wikimedia.org/wikipedia/commons/4/4e/Mini_Golden_Doodle.jpg" }, { "url": "https://upload.wikimedia.org/wikipedia/commons/8/85/Goldendoodle_puppy_Marty.jpg" } ] } """; } @SpringBootConfiguration static class Config { @Bean public OpenAiImageApi imageGenerationApi(RestClient.Builder builder) { return new OpenAiImageApi("", TEST_API_KEY, builder); } @Bean public OpenAiImageClient openAiImageClient(OpenAiImageApi openAiImageApi) { return new OpenAiImageClient(openAiImageApi); } } }
[ "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" ]
[((3237, 3293), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName'), ((3322, 3382), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName'), ((3410, 3466), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName'), ((3502, 3556), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName'), ((3587, 3645), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName'), ((3676, 3730), '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.vertexai.gemini.tool; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.vertexai.gemini.VertexAiGeminiAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallback; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.ai.model.function.FunctionCallbackWrapper.Builder.SchemaType; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*") public class FunctionCallWithFunctionWrapperIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionWrapperIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.vertex.ai.gemini.project-id=" + System.getenv("VERTEX_AI_GEMINI_PROJECT_ID"), "spring.ai.vertex.ai.gemini.location=" + System.getenv("VERTEX_AI_GEMINI_LOCATION")) .withConfiguration(AutoConfigurations.of(VertexAiGeminiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.vertex.ai.gemini.chat.options.model=" + VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .run(context -> { VertexAiGeminiChatClient chatClient = context.getBean(VertexAiGeminiChatClient.class); var systemMessage = new SystemMessage(""" Use Multi-turn function calling. Answer for all listed locations. If the information was not fetched call the function again. Repeat at most 3 times. """); var userMessage = new UserMessage("What's the weather like in San Francisco, Paris and in Tokyo?"); ChatResponse response = chatClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("WeatherInfo").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", "10"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15", "15.0"); }); } @Configuration static class Config { @Bean public FunctionCallback weatherFunctionInfo() { return FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("WeatherInfo") .withSchemaType(SchemaType.OPEN_API_SCHEMA) .withDescription("Get the current weather in a given location") .build(); } } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue" ]
[((2721, 2777), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((3322, 3393), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3322, 3385), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3836, 4051), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3836, 4038), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3836, 3970), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3836, 3922), '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.watsonx.api; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.springframework.ai.watsonx.WatsonxAiChatOptions; import java.util.List; /** * @author Pablo Sanchidrian Herrera * @author John Jairo Moreno Rojas */ public class WatsonxAiChatOptionTest { @Test public void testOptions() { WatsonxAiChatOptions options = WatsonxAiChatOptions.builder() .withDecodingMethod("sample") .withTemperature(1.2f) .withTopK(20) .withTopP(0.5f) .withMaxNewTokens(100) .withMinNewTokens(20) .withStopSequences(List.of("\n\n\n")) .withRepetitionPenalty(1.1f) .withRandomSeed(4) .build(); var optionsMap = options.toMap(); assertThat(optionsMap).containsEntry("decoding_method", "sample"); assertThat(optionsMap).containsEntry("temperature", 1.2); assertThat(optionsMap).containsEntry("top_k", 20); assertThat(optionsMap).containsEntry("top_p", 0.5); assertThat(optionsMap).containsEntry("max_new_tokens", 100); assertThat(optionsMap).containsEntry("min_new_tokens", 20); assertThat(optionsMap).containsEntry("stop_sequences", List.of("\n\n\n")); assertThat(optionsMap).containsEntry("repetition_penalty", 1.1); assertThat(optionsMap).containsEntry("random_seed", 4); } @Test public void testFilterOut() { WatsonxAiChatOptions options = WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build(); var mappedOptions = WatsonxAiChatOptions.filterNonSupportedFields(options.toMap()); assertThat(mappedOptions).doesNotContainEntry("model", "google/flan-ul2"); } }
[ "org.springframework.ai.watsonx.WatsonxAiChatOptions.builder" ]
[((1021, 1304), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1292), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1270), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1238), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1197), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1172), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1146), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1127), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1110), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1084), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1982, 2049), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1982, 2041), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.mistralai.tool; import java.util.List; import java.util.Map; import java.util.function.Function; import com.fasterxml.jackson.annotation.JsonProperty; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.mistralai.MistralAiAutoConfiguration; import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.mistralai.MistralAiChatClient; import org.springframework.ai.mistralai.MistralAiChatOptions; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".*") class PaymentStatusBeanIT { private final Logger logger = LoggerFactory.getLogger(PaymentStatusBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.mistralai.apiKey=" + System.getenv("MISTRAL_AI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, MistralAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.mistralai.chat.options.model=" + MistralAiApi.ChatModel.LARGE.getValue()) .run(context -> { MistralAiChatClient chatClient = context.getBean(MistralAiChatClient.class); ChatResponse response = chatClient .call(new Prompt(List.of(new UserMessage("What's the status of my transaction with id T1001?")), MistralAiChatOptions.builder() .withFunction("retrievePaymentStatus") .withFunction("retrievePaymentDate") .build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("T1001"); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("paid"); }); } // Assuming we have the following data public static final Map<String, StatusDate> DATA = Map.of("T1001", new StatusDate("Paid", "2021-10-05"), "T1002", new StatusDate("Unpaid", "2021-10-06"), "T1003", new StatusDate("Paid", "2021-10-07"), "T1004", new StatusDate("Paid", "2021-10-05"), "T1005", new StatusDate("Pending", "2021-10-08")); record StatusDate(String status, String date) { } @Configuration static class Config { public record Transaction(@JsonProperty(required = true, value = "transaction_id") String transactionId) { } public record Status(@JsonProperty(required = true, value = "status") String status) { } public record Date(@JsonProperty(required = true, value = "date") String date) { } @Bean @Description("Get payment status of a transaction") public Function<Transaction, Status> retrievePaymentStatus() { return (transaction) -> new Status(DATA.get(transaction.transactionId).status()); } @Bean @Description("Get payment date of a transaction") public Function<Transaction, Date> retrievePaymentDate() { return (transaction) -> new Date(DATA.get(transaction.transactionId).date()); } } }
[ "org.springframework.ai.mistralai.MistralAiChatOptions.builder", "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue" ]
[((2623, 2662), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue'), ((2916, 3055), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((2916, 3038), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((2916, 2993), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.cohere.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.cohere.api.CohereChatBedrockApi.CohereChatModel; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.Truncate; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatResponse; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatResponse.Generation.FinishReason; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class CohereChatBedrockApiIT { private CohereChatBedrockApi cohereChatApi = new CohereChatBedrockApi(CohereChatModel.COHERE_COMMAND_V14.id(), Region.US_EAST_1.id()); @Test public void requestBuilder() { CohereChatRequest request1 = new CohereChatRequest( "What is the capital of Bulgaria and what is the size? What it the national anthem?", 0.5f, 0.9f, 15, 40, List.of("END"), CohereChatRequest.ReturnLikelihoods.ALL, false, 1, null, Truncate.NONE); var request2 = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withTemperature(0.5f) .withTopP(0.9f) .withTopK(15) .withMaxTokens(40) .withStopSequences(List.of("END")) .withReturnLikelihoods(CohereChatRequest.ReturnLikelihoods.ALL) .withStream(false) .withNumGenerations(1) .withLogitBias(null) .withTruncate(Truncate.NONE) .build(); assertThat(request1).isEqualTo(request2); } @Test public void chatCompletion() { var request = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(false) .withTemperature(0.5f) .withTopP(0.8f) .withTopK(15) .withMaxTokens(100) .withStopSequences(List.of("END")) .withReturnLikelihoods(CohereChatRequest.ReturnLikelihoods.ALL) .withNumGenerations(3) .withLogitBias(null) .withTruncate(Truncate.NONE) .build(); CohereChatResponse response = cohereChatApi.chatCompletion(request); assertThat(response).isNotNull(); assertThat(response.prompt()).isEqualTo(request.prompt()); assertThat(response.generations()).hasSize(request.numGenerations()); assertThat(response.generations().get(0).text()).isNotEmpty(); } @Test public void chatCompletionStream() { var request = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(true) .withTemperature(0.5f) .withTopP(0.8f) .withTopK(15) .withMaxTokens(100) .withStopSequences(List.of("END")) .withReturnLikelihoods(CohereChatRequest.ReturnLikelihoods.ALL) .withNumGenerations(3) .withLogitBias(null) .withTruncate(Truncate.NONE) .build(); Flux<CohereChatResponse.Generation> responseStream = cohereChatApi.chatCompletionStream(request); List<CohereChatResponse.Generation> responses = responseStream.collectList().block(); assertThat(responses).isNotNull(); assertThat(responses).hasSizeGreaterThan(10); assertThat(responses.get(0).text()).isNotEmpty(); CohereChatResponse.Generation lastResponse = responses.get(responses.size() - 1); assertThat(lastResponse.text()).isNull(); assertThat(lastResponse.isFinished()).isTrue(); assertThat(lastResponse.finishReason()).isEqualTo(FinishReason.MAX_TOKENS); assertThat(lastResponse.amazonBedrockInvocationMetrics()).isNotNull(); } @Test public void testStreamConfigurations() { var streamRequest = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(true) .build(); assertThatThrownBy(() -> cohereChatApi.chatCompletion(streamRequest)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The request must be configured to return the complete response!"); var notStreamRequest = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(false) .build(); assertThatThrownBy(() -> cohereChatApi.chatCompletionStream(notStreamRequest)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The request must be configured to stream the response!"); } }
[ "org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id" ]
[((1787, 1826), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id'), ((1831, 1852), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vertexai.gemini.tool; import java.util.List; import java.util.function.Function; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.vertexai.gemini.VertexAiGeminiAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*") class FunctionCallWithFunctionBeanIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.vertex.ai.gemini.project-id=" + System.getenv("VERTEX_AI_GEMINI_PROJECT_ID"), "spring.ai.vertex.ai.gemini.location=" + System.getenv("VERTEX_AI_GEMINI_LOCATION")) .withConfiguration(AutoConfigurations.of(VertexAiGeminiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.vertex.ai.gemini.chat.options.model=" + VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .run(context -> { VertexAiGeminiChatClient chatClient = context.getBean(VertexAiGeminiChatClient.class); var systemMessage = new SystemMessage(""" Use Multi-turn function calling. Answer for all listed locations. If the information was not fetched call the function again. Repeat at most 3 times. """); var userMessage = new UserMessage( "What's the weather like in San Francisco, Paris and in Tokyo (Japan)?"); ChatResponse response = chatClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("weatherFunction").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); response = chatClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("weatherFunction3").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } @Configuration static class Config { @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction() { return new MockWeatherService(); } // Relies on the Request's JsonClassDescription annotation to provide the // function description. @Bean public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction3() { MockWeatherService weatherService = new MockWeatherService(); return (weatherService::apply); } } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue" ]
[((2583, 2639), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((3199, 3274), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3199, 3266), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3499, 3575), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3499, 3567), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.qdrant; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.qdrant.QdrantContainer; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.DefaultResourceLoader; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov * @since 0.8.1 */ @Testcontainers public class QdrantVectorStoreAutoConfigurationIT { private static final String COLLECTION_NAME = "test_collection"; private static final int QDRANT_GRPC_PORT = 6334; @Container 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"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(QdrantVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.qdrant.port=" + qdrantContainer.getMappedPort(QDRANT_GRPC_PORT), "spring.ai.vectorstore.qdrant.host=" + qdrantContainer.getHost(), "spring.ai.vectorstore.qdrant.collectionName=" + COLLECTION_NAME); @Test public void addAndSearch() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore .similaritySearch(SearchRequest.query("What is Great Depression?").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId()); assertThat(resultDoc.getMetadata()).containsKeys("depression", "distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1)); assertThat(results).hasSize(0); }); } public static String getText(String uri) { var resource = new DefaultResourceLoader().getResource(uri); try { return resource.getContentAsString(StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2991, 3051), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3440, 3491), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.titan.api; import java.util.List; import java.util.stream.Collectors; 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.titan.api.TitanChatBedrockApi.TitanChatModel; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatResponse; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatResponseChunk; import 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 TitanChatBedrockApiIT { TitanChatBedrockApi titanBedrockApi = new TitanChatBedrockApi(TitanChatModel.TITAN_TEXT_EXPRESS_V1.id(), Region.EU_CENTRAL_1.id()); TitanChatRequest titanChatRequest = TitanChatRequest.builder("Give me the names of 3 famous pirates?") .withTemperature(0.5f) .withTopP(0.9f) .withMaxTokenCount(100) .withStopSequences(List.of("|")) .build(); @Test public void chatCompletion() { TitanChatResponse response = titanBedrockApi.chatCompletion(titanChatRequest); assertThat(response.results()).hasSize(1); assertThat(response.results().get(0).outputText()).contains("Blackbeard"); } @Test public void chatCompletionStream() { Flux<TitanChatResponseChunk> response = titanBedrockApi.chatCompletionStream(titanChatRequest); List<TitanChatResponseChunk> results = response.collectList().block(); assertThat(results.stream() .map(TitanChatResponseChunk::outputText) .collect(Collectors.joining(System.lineSeparator()))).contains("Blackbeard"); } }
[ "org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest.builder", "org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id" ]
[((1617, 1658), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id'), ((1663, 1687), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((1728, 1909), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest.builder'), ((1728, 1898), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest.builder'), ((1728, 1863), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest.builder'), ((1728, 1837), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest.builder'), ((1728, 1819), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatRequest.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.api; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel; 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 reactor.core.publisher.Flux; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import java.util.List; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.DEFAULT_ANTHROPIC_VERSION; /** * @author Ben Middleton */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class Anthropic3ChatBedrockApiIT { private final Logger logger = LoggerFactory.getLogger(Anthropic3ChatBedrockApiIT.class); private Anthropic3ChatBedrockApi anthropicChatApi = new Anthropic3ChatBedrockApi( AnthropicChatModel.CLAUDE_INSTANT_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); @Test public void chatCompletion() { MediaContent anthropicMessage = new MediaContent("Name 3 famous pirates"); ChatCompletionMessage chatCompletionMessage = new ChatCompletionMessage(List.of(anthropicMessage), Role.USER); AnthropicChatRequest request = AnthropicChatRequest.builder(List.of(chatCompletionMessage)) .withTemperature(0.8f) .withMaxTokens(300) .withTopK(10) .withAnthropicVersion(DEFAULT_ANTHROPIC_VERSION) .build(); AnthropicChatResponse response = anthropicChatApi.chatCompletion(request); System.out.println(response.content()); assertThat(response).isNotNull(); assertThat(response.content().get(0).text()).isNotEmpty(); assertThat(response.content().get(0).text()).contains("Blackbeard"); assertThat(response.stopReason()).isEqualTo("end_turn"); assertThat(response.stopSequence()).isNull(); assertThat(response.usage().inputTokens()).isGreaterThan(10); assertThat(response.usage().outputTokens()).isGreaterThan(100); logger.info("" + response); } @Test public void chatMultiCompletion() { MediaContent anthropicInitialMessage = new MediaContent("Name 3 famous pirates"); ChatCompletionMessage chatCompletionInitialMessage = new ChatCompletionMessage(List.of(anthropicInitialMessage), Role.USER); MediaContent anthropicAssistantMessage = new MediaContent( "Here are 3 famous pirates: Blackbeard, Calico Jack, Henry Morgan"); ChatCompletionMessage chatCompletionAssistantMessage = new ChatCompletionMessage( List.of(anthropicAssistantMessage), Role.ASSISTANT); MediaContent anthropicFollowupMessage = new MediaContent("Why are they famous?"); ChatCompletionMessage chatCompletionFollowupMessage = new ChatCompletionMessage( List.of(anthropicFollowupMessage), Role.USER); AnthropicChatRequest request = AnthropicChatRequest .builder(List.of(chatCompletionInitialMessage, chatCompletionAssistantMessage, chatCompletionFollowupMessage)) .withTemperature(0.8f) .withMaxTokens(400) .withTopK(10) .withAnthropicVersion(DEFAULT_ANTHROPIC_VERSION) .build(); AnthropicChatResponse response = anthropicChatApi.chatCompletion(request); System.out.println(response.content()); assertThat(response).isNotNull(); assertThat(response.content().get(0).text()).isNotEmpty(); assertThat(response.content().get(0).text()).contains("Blackbeard"); assertThat(response.stopReason()).isEqualTo("end_turn"); assertThat(response.stopSequence()).isNull(); assertThat(response.usage().inputTokens()).isGreaterThan(30); assertThat(response.usage().outputTokens()).isGreaterThan(200); logger.info("" + response); } @Test public void chatCompletionStream() { MediaContent anthropicMessage = new MediaContent("Name 3 famous pirates"); ChatCompletionMessage chatCompletionMessage = new ChatCompletionMessage(List.of(anthropicMessage), Role.USER); AnthropicChatRequest request = AnthropicChatRequest.builder(List.of(chatCompletionMessage)) .withTemperature(0.8f) .withMaxTokens(300) .withTopK(10) .withAnthropicVersion(DEFAULT_ANTHROPIC_VERSION) .build(); Flux<Anthropic3ChatBedrockApi.AnthropicChatStreamingResponse> responseStream = anthropicChatApi .chatCompletionStream(request); List<Anthropic3ChatBedrockApi.AnthropicChatStreamingResponse> responses = responseStream.collectList().block(); assertThat(responses).isNotNull(); assertThat(responses).hasSizeGreaterThan(10); assertThat(responses.stream() .filter(message -> message.type() == StreamingType.CONTENT_BLOCK_DELTA) .map(message -> message.delta().text()) .collect(Collectors.joining())).contains("Blackbeard"); } }
[ "org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder", "org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_INSTANT_V1.id" ]
[((2418, 2459), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_INSTANT_V1.id'), ((2513, 2534), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2821, 3011), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((2821, 2999), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((2821, 2947), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((2821, 2930), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((2821, 2907), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((5464, 5654), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((5464, 5642), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((5464, 5590), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((5464, 5573), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatRequest.builder'), ((5464, 5550), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.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.openai.transformer; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.ai.document.DefaultContentFormatter; import org.springframework.ai.document.Document; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.transformer.ContentFormatTransformer; import org.springframework.ai.transformer.KeywordMetadataEnricher; import org.springframework.ai.transformer.SummaryMetadataEnricher; import org.springframework.ai.transformer.SummaryMetadataEnricher.SummaryType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @SpringBootTest public class MetadataTransformerIT { @Autowired KeywordMetadataEnricher keywordMetadataEnricher; @Autowired SummaryMetadataEnricher summaryMetadataEnricher; @Autowired ContentFormatTransformer contentFormatTransformer; @Autowired DefaultContentFormatter defaultContentFormatter; Document document1 = new Document("Somewhere in the Andes, they believe to this very day that the" + " future is behind you. It comes up from behind your back, surprising and unforeseeable, while the past " + " is always before your eyes, that which has already happened. When they talk about the past, the people of" + " the Aymara tribe point in front of them. You walk forward facing the past and you turn back toward the future.", new HashMap<>(Map.of("key", "value"))); Document document2 = new Document( "The Spring Framework is divided into modules. Applications can choose which modules" + " they need. At the heart are the modules of the core container, including a configuration generative and a " + "dependency injection mechanism. Beyond that, the Spring Framework provides foundational support " + " for different application architectures, including messaging, transactional data and persistence, " + "and web. It also includes the Servlet-based Spring MVC web framework and, in parallel, the Spring " + "WebFlux reactive web framework."); @Test public void testKeywordExtractor() { var updatedDocuments = keywordMetadataEnricher.apply(List.of(document1, document2)); List<Map<String, Object>> keywords = updatedDocuments.stream().map(d -> d.getMetadata()).toList(); assertThat(updatedDocuments.size()).isEqualTo(2); var keywords1 = keywords.get(0); var keywords2 = keywords.get(1); assertThat(keywords1).containsKeys("excerpt_keywords"); assertThat(keywords2).containsKeys("excerpt_keywords"); assertThat((String) keywords1.get("excerpt_keywords")).contains("Andes", "Aymara"); assertThat((String) keywords2.get("excerpt_keywords")).contains("Spring Framework", "dependency injection"); } @Test public void testSummaryExtractor() { var updatedDocuments = summaryMetadataEnricher.apply(List.of(document1, document2)); List<Map<String, Object>> summaries = updatedDocuments.stream().map(d -> d.getMetadata()).toList(); assertThat(summaries.size()).isEqualTo(2); var summary1 = summaries.get(0); var summary2 = summaries.get(1); assertThat(summary1).containsKeys("section_summary", "next_section_summary"); assertThat(summary1).doesNotContainKeys("prev_section_summary"); assertThat(summary2).containsKeys("section_summary", "prev_section_summary"); assertThat(summary2).doesNotContainKeys("next_section_summary"); assertThat((String) summary1.get("section_summary")).isNotEmpty(); assertThat((String) summary1.get("next_section_summary")).isNotEmpty(); assertThat((String) summary2.get("section_summary")).isNotEmpty(); assertThat((String) summary2.get("prev_section_summary")).isNotEmpty(); assertThat((String) summary1.get("section_summary")).isEqualTo((String) summary2.get("prev_section_summary")); assertThat((String) summary1.get("next_section_summary")).isEqualTo((String) summary2.get("section_summary")); } @Test public void testContentFormatEnricher() { assertThat(((DefaultContentFormatter) document1.getContentFormatter()).getExcludedEmbedMetadataKeys()) .doesNotContain("NewEmbedKey"); assertThat(((DefaultContentFormatter) document1.getContentFormatter()).getExcludedInferenceMetadataKeys()) .doesNotContain("NewInferenceKey"); assertThat(((DefaultContentFormatter) document2.getContentFormatter()).getExcludedEmbedMetadataKeys()) .doesNotContain("NewEmbedKey"); assertThat(((DefaultContentFormatter) document2.getContentFormatter()).getExcludedInferenceMetadataKeys()) .doesNotContain("NewInferenceKey"); List<Document> enrichedDocuments = contentFormatTransformer.apply(List.of(document1, document2)); assertThat(enrichedDocuments.size()).isEqualTo(2); var doc1 = enrichedDocuments.get(0); var doc2 = enrichedDocuments.get(1); assertThat(doc1).isEqualTo(document1); assertThat(doc2).isEqualTo(document2); assertThat(((DefaultContentFormatter) doc1.getContentFormatter()).getTextTemplate()) .isSameAs(defaultContentFormatter.getTextTemplate()); assertThat(((DefaultContentFormatter) doc1.getContentFormatter()).getExcludedEmbedMetadataKeys()) .contains("NewEmbedKey"); assertThat(((DefaultContentFormatter) doc1.getContentFormatter()).getExcludedInferenceMetadataKeys()) .contains("NewInferenceKey"); assertThat(((DefaultContentFormatter) doc2.getContentFormatter()).getTextTemplate()) .isSameAs(defaultContentFormatter.getTextTemplate()); assertThat(((DefaultContentFormatter) doc2.getContentFormatter()).getExcludedEmbedMetadataKeys()) .contains("NewEmbedKey"); assertThat(((DefaultContentFormatter) doc2.getContentFormatter()).getExcludedInferenceMetadataKeys()) .contains("NewInferenceKey"); } @SpringBootConfiguration public static class OpenAiTestConfiguration { @Bean public OpenAiApi openAiApi() throws IOException { String apiKey = System.getenv("OPENAI_API_KEY"); if (!StringUtils.hasText(apiKey)) { throw new IllegalArgumentException( "You must provide an API key. Put it in an environment variable under the name OPENAI_API_KEY"); } return new OpenAiApi(apiKey); } @Bean public OpenAiChatClient openAiChatClient(OpenAiApi openAiApi) { OpenAiChatClient openAiChatClient = new OpenAiChatClient(openAiApi); return openAiChatClient; } @Bean public KeywordMetadataEnricher keywordMetadata(OpenAiChatClient aiClient) { return new KeywordMetadataEnricher(aiClient, 5); } @Bean public SummaryMetadataEnricher summaryMetadata(OpenAiChatClient aiClient) { return new SummaryMetadataEnricher(aiClient, List.of(SummaryType.PREVIOUS, SummaryType.CURRENT, SummaryType.NEXT)); } @Bean public DefaultContentFormatter defaultContentFormatter() { return DefaultContentFormatter.builder() .withExcludedEmbedMetadataKeys("NewEmbedKey") .withExcludedInferenceMetadataKeys("NewInferenceKey") .build(); } @Bean public ContentFormatTransformer contentFormatTransformer(DefaultContentFormatter defaultContentFormatter) { return new ContentFormatTransformer(defaultContentFormatter, false); } } }
[ "org.springframework.ai.document.DefaultContentFormatter.builder" ]
[((7727, 7881), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((7727, 7868), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((7727, 7810), 'org.springframework.ai.document.DefaultContentFormatter.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.openai.tool; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration; import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallingOptions; import org.springframework.ai.model.function.FunctionCallingOptionsBuilder.PortableFunctionCallingOptions; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".*") class FunctionCallbackWithPlainFunctionBeanIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallbackWithPlainFunctionBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.openai.apiKey=" + System.getenv("OPENAI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, OpenAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); // Test weatherFunction UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunction").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); // Test weatherFunctionTwo response = chatClient.call(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunctionTwo").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } @Test void functionCallWithPortableFunctionCallingOptions() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); // Test weatherFunction UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); PortableFunctionCallingOptions functionOptions = FunctionCallingOptions.builder() .withFunction("weatherFunction") .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), functionOptions)); logger.info("Response: {}", response); }); } @Test void streamFunctionCallTest() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); // Test weatherFunction UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); Flux<ChatResponse> response = chatClient.stream(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunction").build())); String content = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", content); assertThat(content).containsAnyOf("30.0", "30"); assertThat(content).containsAnyOf("10.0", "10"); assertThat(content).containsAnyOf("15.0", "15"); // Test weatherFunctionTwo response = chatClient.stream(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunctionTwo").build())); content = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", content); assertThat(content).containsAnyOf("30.0", "30"); assertThat(content).containsAnyOf("10.0", "10"); assertThat(content).containsAnyOf("15.0", "15"); }); } @Configuration static class Config { @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction() { return new MockWeatherService(); } // Relies on the Request's JsonClassDescription annotation to provide the // function description. @Bean public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunctionTwo() { MockWeatherService weatherService = new MockWeatherService(); return (weatherService::apply); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallingOptions.builder" ]
[((3172, 3239), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3172, 3231), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3475, 3545), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3475, 3537), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((4133, 4215), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((4133, 4202), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((4819, 4886), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((4819, 4878), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((5429, 5499), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((5429, 5491), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.vectorstore; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.awaitility.Duration; 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.PineconeVectorStore.PineconeVectorStoreConfig; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.core.io.DefaultResourceLoader; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "PINECONE_API_KEY", matches = ".+") public class PineconeVectorStoreIT { // Replace the PINECONE_ENVIRONMENT, PINECONE_PROJECT_ID, PINECONE_INDEX_NAME and // PINECONE_API_KEY with your pinecone credentials. private static final String PINECONE_ENVIRONMENT = "gcp-starter"; private static final String PINECONE_PROJECT_ID = "814621f"; private static final String PINECONE_INDEX_NAME = "spring-ai-test-index"; // NOTE: Leave it empty as for free tier as later doesn't support namespaces. private static final String PINECONE_NAMESPACE = ""; List<Document> documents = List.of( new Document("1", getText("classpath:/test/data/spring.ai.txt"), Map.of("meta1", "meta1")), new Document("2", getText("classpath:/test/data/time.shelter.txt"), Map.of()), new Document("3", getText("classpath:/test/data/great.depression.txt"), Map.of("meta2", "meta2"))); public static String getText(String uri) { var resource = new DefaultResourceLoader().getResource(uri); try { return resource.getContentAsString(StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestApplication.class); @BeforeAll public static void beforeAll() { Awaitility.setDefaultPollInterval(2, TimeUnit.SECONDS); Awaitility.setDefaultPollDelay(Duration.ZERO); Awaitility.setDefaultTimeout(Duration.ONE_MINUTE); } @Test public void addAndSearchTest() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); Awaitility.await().until(() -> { return vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1)); }, hasSize(1)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId()); assertThat(resultDoc.getContent()).contains("The Great Depression (1929–1939) was an economic shock"); assertThat(resultDoc.getMetadata()).hasSize(2); assertThat(resultDoc.getMetadata()).containsKey("meta2"); assertThat(resultDoc.getMetadata()).containsKey("distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); Awaitility.await().until(() -> { return vectorStore.similaritySearch(SearchRequest.query("Hello").withTopK(1)); }, hasSize(0)); }); } @Test public void addAndSearchWithFilters() { // Pinecone metadata filtering syntax: // https://docs.pinecone.io/docs/metadata-filtering contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "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)); SearchRequest searchRequest = SearchRequest.query("The World"); Awaitility.await().until(() -> { return vectorStore.similaritySearch(searchRequest.withTopK(1)); }, hasSize(1)); List<Document> results = vectorStore.similaritySearch(searchRequest.withTopK(5)); assertThat(results).hasSize(2); results = vectorStore.similaritySearch(searchRequest.withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'Bulgaria'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch(searchRequest.withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'Netherlands'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch(searchRequest.withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("NOT(country == 'Netherlands')")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); // Remove all documents from the store vectorStore.delete(List.of(bgDocument, nlDocument).stream().map(doc -> doc.getId()).toList()); Awaitility.await().until(() -> { return vectorStore.similaritySearch(searchRequest.withTopK(1)); }, hasSize(0)); }); } @Test public void documentUpdateTest() { // Note ,using OpenAI to calculate embeddings contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); Document document = new Document(UUID.randomUUID().toString(), "Spring AI rocks!!", Collections.singletonMap("meta1", "meta1")); vectorStore.add(List.of(document)); SearchRequest springSearchRequest = SearchRequest.query("Spring").withTopK(5); Awaitility.await().until(() -> { return vectorStore.similaritySearch(springSearchRequest); }, hasSize(1)); List<Document> results = vectorStore.similaritySearch(springSearchRequest); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("Spring AI rocks!!"); assertThat(resultDoc.getMetadata()).containsKey("meta1"); assertThat(resultDoc.getMetadata()).containsKey("distance"); Document sameIdDocument = new Document(document.getId(), "The World is Big and Salvation Lurks Around the Corner", Collections.singletonMap("meta2", "meta2")); vectorStore.add(List.of(sameIdDocument)); SearchRequest fooBarSearchRequest = SearchRequest.query("FooBar").withTopK(5); Awaitility.await().until(() -> { return vectorStore.similaritySearch(fooBarSearchRequest).get(0).getContent(); }, equalTo("The World is Big and Salvation Lurks Around the Corner")); results = vectorStore.similaritySearch(fooBarSearchRequest); assertThat(results).hasSize(1); resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("The World is Big and Salvation Lurks Around the Corner"); assertThat(resultDoc.getMetadata()).containsKey("meta2"); assertThat(resultDoc.getMetadata()).containsKey("distance"); // Remove all documents from the store vectorStore.delete(List.of(document.getId())); Awaitility.await().until(() -> { return vectorStore.similaritySearch(fooBarSearchRequest); }, hasSize(0)); }); } @Test public void searchThresholdTest() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); Awaitility.await().until(() -> { return vectorStore .similaritySearch(SearchRequest.query("Depression").withTopK(50).withSimilarityThresholdAll()); }, hasSize(3)); List<Document> fullResult = vectorStore .similaritySearch(SearchRequest.query("Depression").withTopK(5).withSimilarityThresholdAll()); List<Float> distances = fullResult.stream().map(doc -> (Float) doc.getMetadata().get("distance")).toList(); assertThat(distances).hasSize(3); float threshold = (distances.get(0) + distances.get(1)) / 2; List<Document> results = vectorStore .similaritySearch(SearchRequest.query("Depression").withTopK(5).withSimilarityThreshold(1 - threshold)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId()); assertThat(resultDoc.getContent()).contains("The Great Depression (1929–1939) was an economic shock"); assertThat(resultDoc.getMetadata()).containsKey("meta2"); assertThat(resultDoc.getMetadata()).containsKey("distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); Awaitility.await().until(() -> { return vectorStore.similaritySearch(SearchRequest.query("Hello").withTopK(1)); }, hasSize(0)); }); } @SpringBootConfiguration @EnableAutoConfiguration public static class TestApplication { @Bean public PineconeVectorStoreConfig pineconeVectorStoreConfig() { return PineconeVectorStoreConfig.builder() .withApiKey(System.getenv("PINECONE_API_KEY")) .withEnvironment(PINECONE_ENVIRONMENT) .withProjectId(PINECONE_PROJECT_ID) .withIndexName(PINECONE_INDEX_NAME) .withNamespace(PINECONE_NAMESPACE) .build(); } @Bean public VectorStore vectorStore(PineconeVectorStoreConfig config, EmbeddingClient embeddingClient) { return new PineconeVectorStore(config, embeddingClient); } @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder" ]
[((3532, 3676), 'org.awaitility.Awaitility.await'), ((4343, 4476), 'org.awaitility.Awaitility.await'), ((5118, 5236), 'org.awaitility.Awaitility.await'), ((6216, 6289), 'java.util.List.of'), ((6216, 6280), 'java.util.List.of'), ((6216, 6256), 'java.util.List.of'), ((6296, 6414), 'org.awaitility.Awaitility.await'), ((6654, 6682), 'java.util.UUID.randomUUID'), ((6882, 6994), 'org.awaitility.Awaitility.await'), ((7716, 7903), 'org.awaitility.Awaitility.await'), ((8427, 8539), 'org.awaitility.Awaitility.await'), ((8732, 8906), 'org.awaitility.Awaitility.await'), ((9917, 10050), 'org.awaitility.Awaitility.await'), ((10238, 10499), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((10238, 10486), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((10238, 10447), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((10238, 10407), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((10238, 10367), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((10238, 10324), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.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; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.AssistantMessage; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel; 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 BedrockLlama2ChatClientIT { @Autowired private BedrockLlama2ChatClient 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"); } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void outputParser() { DefaultConversionService conversionService = new DefaultConversionService(); ListOutputParser outputParser = new ListOutputParser(conversionService); String format = outputParser.getFormat(); String template = """ List five {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "ice cream flavors.", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = this.client.call(prompt).getResult(); List<String> list = outputParser.parse(generation.getOutput().getContent()); assertThat(list).hasSize(5); } @Test void mapOutputParser() { MapOutputParser outputParser = new MapOutputParser(); String format = outputParser.getFormat(); String template = """ Provide me a List of {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); Map<String, Object> result = outputParser.parse(generation.getOutput().getContent()); assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); } record ActorsFilmsRecord(String actor, List<String> movies) { } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void beanOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove non JSON tex blocks from the output. Provide your answer in the JSON format with the feature names as the keys. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent()); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void beanStreamOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove Markdown code blocks from the output. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); String generationTextFromStream = client.stream(prompt) .collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream); System.out.println(actorsFilms); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @SpringBootConfiguration public static class TestConfiguration { @Bean public Llama2ChatBedrockApi llama2Api() { return new Llama2ChatBedrockApi(Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); } @Bean public BedrockLlama2ChatClient llama2ChatClient(Llama2ChatBedrockApi llama2Api) { return new BedrockLlama2ChatClient(llama2Api, BedrockLlama2ChatOptions.builder().withTemperature(0.5f).withMaxGenLen(100).withTopP(0.9f).build()); } } }
[ "org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id" ]
[((6861, 6900), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id'), ((6956, 6977), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.chroma; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @Testcontainers public class ChromaVectorStoreAutoConfigurationIT { @Container static GenericContainer<?> chromaContainer = new GenericContainer<>("ghcr.io/chroma-core/chroma:0.4.15") .withExposedPorts(8000); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ChromaVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.chroma.client.host=http://" + chromaContainer.getHost(), "spring.ai.vectorstore.chroma.client.port=" + chromaContainer.getMappedPort(8000), "spring.ai.vectorstore.chroma.store.collectionName=TestCollection"); @Test public void addAndSearchWithFilters() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "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) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2742, 2786), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3434, 3507), 'java.util.List.of'), ((3434, 3498), 'java.util.List.of'), ((3434, 3474), 'java.util.List.of')]
package com.example.carina.data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.PagePdfDocumentReader; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; 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/medicaid-wa-faqs.pdf") private Resource pdfResource; private final VectorStore vectorStore; @Autowired public DataLoadingService(VectorStore vectorStore) { Assert.notNull(vectorStore, "VectorStore must not be null."); this.vectorStore = vectorStore; } public void load() { PagePdfDocumentReader pdfReader = new PagePdfDocumentReader( this.pdfResource, PdfDocumentReaderConfig.builder() .withPageExtractedTextFormatter(ExtractedTextFormatter.builder() .withNumberOfBottomTextLinesToDelete(3) .withNumberOfTopPagesToSkipBeforeDelete(1) // .withLeftAlignment(true) .build()) .withPagesPerDocument(1) .build()); 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( pdfReader.get())); logger.info("Done parsing document, splitting, creating embeddings and storing in vector store"); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((1268, 1721), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1268, 1688), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1268, 1639), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1358, 1638), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1358, 1537), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1358, 1462), 'org.springframework.ai.reader.ExtractedTextFormatter.builder')]
/** * Copyright 2023 Sven Loesekann Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ch.xxx.aidoclibchat.adapter.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.stream.IntStream; import org.postgresql.util.PGobject; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.PgVectorStore; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.ai.vectorstore.filter.Filter; import org.springframework.ai.vectorstore.filter.Filter.ExpressionType; import org.springframework.ai.vectorstore.filter.Filter.Key; import org.springframework.ai.vectorstore.filter.Filter.Value; import org.springframework.ai.vectorstore.filter.FilterExpressionConverter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.pgvector.PGvector; import ch.xxx.aidoclibchat.domain.common.MetaData; import ch.xxx.aidoclibchat.domain.common.MetaData.DataType; import ch.xxx.aidoclibchat.domain.model.entity.DocumentVsRepository; @Repository public class DocumentVSRepositoryBean implements DocumentVsRepository { private final String vectorTableName; private final VectorStore vectorStore; private final JdbcTemplate jdbcTemplate; private final ObjectMapper objectMapper; private final FilterExpressionConverter filterExpressionConverter; public DocumentVSRepositoryBean(JdbcTemplate jdbcTemplate, EmbeddingClient embeddingClient, ObjectMapper objectMapper) { this.jdbcTemplate = jdbcTemplate; this.objectMapper = objectMapper; this.vectorStore = new PgVectorStore(jdbcTemplate, embeddingClient); this.filterExpressionConverter = ((PgVectorStore) this.vectorStore).filterExpressionConverter; this.vectorTableName = PgVectorStore.VECTOR_TABLE_NAME; } @Override public void add(List<Document> documents) { this.vectorStore.add(documents); } @Override public List<Document> retrieve(String query, DataType dataType, int k, double threshold) { return this.vectorStore .similaritySearch(SearchRequest .query(query).withFilterExpression(new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString()))) .withTopK(k).withSimilarityThreshold(threshold)); } @Override public List<Document> retrieve(String query, DataType dataType, int k) { return this.vectorStore.similaritySearch(SearchRequest.query(query).withFilterExpression( new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString()))) .withTopK(k)); } @Override public List<Document> retrieve(String query, DataType dataType) { return this.vectorStore.similaritySearch(SearchRequest.query(query).withFilterExpression( new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString())))); } @Override public List<Document> findAllTableDocuments() { String nativeFilterExpression = this.filterExpressionConverter.convertExpression(new Filter.Expression(ExpressionType.NE, new Key(MetaData.DATATYPE), new Value(DataType.DOCUMENT.toString()))); String jsonPathFilter = " WHERE metadata::jsonb @@ '" + nativeFilterExpression + "'::jsonpath "; return this.jdbcTemplate.query( String.format("SELECT * FROM %s %s LIMIT ? ", this.vectorTableName, jsonPathFilter), new DocumentRowMapper(this.objectMapper), 100000); } @Override public void deleteByIds(List<String> ids) { this.vectorStore.delete(ids); } private static class DocumentRowMapper implements RowMapper<Document> { private static final String COLUMN_EMBEDDING = "embedding"; private static final String COLUMN_METADATA = "metadata"; private static final String COLUMN_ID = "id"; private static final String COLUMN_CONTENT = "content"; private ObjectMapper objectMapper; public DocumentRowMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public Document mapRow(ResultSet rs, int rowNum) throws SQLException { String id = rs.getString(COLUMN_ID); String content = rs.getString(COLUMN_CONTENT); PGobject pgMetadata = rs.getObject(COLUMN_METADATA, PGobject.class); PGobject embedding = rs.getObject(COLUMN_EMBEDDING, PGobject.class); Map<String, Object> metadata = toMap(pgMetadata); Document document = new Document(id, content, metadata); document.setEmbedding(toDoubleList(embedding)); return document; } private List<Double> toDoubleList(PGobject embedding) throws SQLException { float[] floatArray = new PGvector(embedding.getValue()).toArray(); return IntStream.range(0, floatArray.length).mapToDouble(i -> floatArray[i]).boxed().toList(); } @SuppressWarnings("unchecked") private Map<String, Object> toMap(PGobject pgObject) { String source = pgObject.getValue(); try { return (Map<String, Object>) objectMapper.readValue(source, Map.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3233, 3404), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3233, 3387), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3532, 3686), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3919, 3947), 'ch.xxx.aidoclibchat.domain.common.MetaData.DataType.DOCUMENT.toString'), ((5441, 5527), 'java.util.stream.IntStream.range'), ((5441, 5518), 'java.util.stream.IntStream.range'), ((5441, 5510), 'java.util.stream.IntStream.range')]
package com.example.pdfsimilaritysearch; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentReader; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.PagePdfDocumentReader; import org.springframework.ai.reader.pdf.ParagraphPdfDocumentReader; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.task.TaskExecutor; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class UploadController { private final VectorStore vectorStore; private final Resource uploadDir; private final TaskExecutor taskExecutor; private final Logger logger = LoggerFactory.getLogger(UploadController.class); private final ConcurrentMap<String, UploadTask> uploadTaskMap = new ConcurrentHashMap<>(); public UploadController(VectorStore vectorStore, @Value("${upload.dir:file:/tmp}") Resource uploadDir, TaskExecutor taskExecutor) { this.vectorStore = vectorStore; this.uploadDir = uploadDir; this.taskExecutor = taskExecutor; } @GetMapping("/upload") public String index() { return "upload"; } @GetMapping(path = "/upload/{id}/progress") public SseEmitter uploadProgress(@PathVariable String id) { UploadTask uploadTask = this.uploadTaskMap.get(id); if (uploadTask == null) { throw new ResponseStatusException(HttpStatus.GONE, "The requested task has gone."); } if (!uploadTask.isStarted().compareAndSet(false, true)) { throw new ResponseStatusException(HttpStatus.GONE, "The requested task has already started."); } SseEmitter emitter = new SseEmitter(TimeUnit.HOURS.toMillis(1)); emitter.onTimeout(() -> logger.warn("Timeout! ID: {}", uploadTask.id())); emitter.onError(ex -> logger.error("Error! ID: " + uploadTask.id(), ex)); this.taskExecutor.execute(() -> { logger.info("Started the task ID: {}", uploadTask.id()); try { for (Path path : uploadTask.paths()) { Resource resource = new FileSystemResource(path); DocumentReader documentReader; emitter.send(SseEmitter.event() .name("message") .data("⌛️ Adding %s to the vector store.".formatted(path.getFileName()))); try { documentReader = new ParagraphPdfDocumentReader(resource); } catch (RuntimeException e) { documentReader = new PagePdfDocumentReader(resource, PdfDocumentReaderConfig.builder() .withPagesPerDocument(2) .withPageExtractedTextFormatter( ExtractedTextFormatter.builder().withNumberOfBottomTextLinesToDelete(2).build()) .build()); } emitter.send(SseEmitter.event() .name("message") .data("Use %s as the document reader.".formatted(documentReader.getClass()))); List<Document> documents = documentReader.get(); for (int i = 0; i < documents.size(); i++) { Document document = documents.get(i); // TODO Batch processing this.vectorStore.add(List.of(document)); if ((i + 1) % 10 == 0) { emitter.send(SseEmitter.event() .name("message") .data("%d%% done".formatted(100 * (i + 1) / documents.size()))); } } emitter.send(SseEmitter.event() .name("message") .data("✅ Added %s to the vector store.".formatted(path.getFileName()))); } emitter.send("Completed 🎉"); emitter.complete(); } catch (Exception ex) { logger.error("Task failed", ex); emitter.completeWithError(ex); } finally { this.uploadTaskMap.remove(id); } logger.info("Finished the task ID: {}", uploadTask.id()); }); return emitter; } @PostMapping("/upload") public String upload(@RequestParam("files") MultipartFile[] files, RedirectAttributes redirectAttributes) throws Exception { List<Path> paths = new ArrayList<>(); for (MultipartFile file : files) { if (file.isEmpty()) { continue; } byte[] bytes = file.getBytes(); Path path = this.uploadDir.getFile().toPath().resolve(Objects.requireNonNull(file.getOriginalFilename())); Files.write(path, bytes); paths.add(path); } String id = UUID.randomUUID().toString(); this.uploadTaskMap.computeIfAbsent(id, k -> new UploadTask(id, paths, new AtomicBoolean(false))); redirectAttributes .addFlashAttribute("message", "Files have been uploaded. Next, add the uploaded files to the vector store.") .addFlashAttribute("id", id); return "redirect:/upload"; } record UploadTask(String id, List<Path> paths, AtomicBoolean isStarted) { } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((2799, 2825), 'java.util.concurrent.TimeUnit.HOURS.toMillis'), ((3237, 3361), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((3237, 3278), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((3540, 3751), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3540, 3735), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3540, 3605), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3655, 3734), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((3655, 3726), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((3779, 3903), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((3779, 3820), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4183, 4297), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4183, 4226), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4333, 4453), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4333, 4374), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((5259, 5287), 'java.util.UUID.randomUUID')]
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.ollama.chat; import org.springframework.ai.ollama.OllamaEmbeddingClient; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Profile("ollama-chat") @Configuration public class OllamaChatEmbeddingClientConfig { @Value("${ai-client.ollama.chat.options.model}") private String ollamaOptionsModelName; private final OllamaApi ollamaApi; public OllamaChatEmbeddingClientConfig(OllamaApi ollamaApi) { this.ollamaApi = ollamaApi; } @Bean @Primary public OllamaEmbeddingClient ollamaChatEmbeddingClient() { return new OllamaEmbeddingClient(ollamaApi) .withDefaultOptions(OllamaOptions.create() .withModel(ollamaOptionsModelName)); } }
[ "org.springframework.ai.ollama.api.OllamaOptions.create" ]
[((1038, 1119), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
package xyz.austinatchley.poesie.client; import org.springframework.ai.openai.OpenAiImageClient; import org.springframework.ai.openai.OpenAiImageOptions; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import xyz.austinatchley.poesie.entity.ImageEntity; import org.apache.commons.lang3.StringUtils; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.image.Image; import org.springframework.ai.image.ImageGeneration; import org.springframework.ai.image.ImageOptions; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import lombok.NonNull; @Component @Log4j2 @RequiredArgsConstructor public class PoesieOpenAiImageClient implements PoesieImageClient { private static final ImageOptions DEFAULT_IMAGE_OPTIONS = OpenAiImageOptions.builder() .withResponseFormat("url") .build(); private final OpenAiImageClient imageClient; @Override public ImageEntity generateImageResponse(@NonNull final String topic) { final ImagePrompt prompt = generatePrompt(topic, null); return sendRequest(prompt); } @Override public ImageEntity generateImageResponse(@NonNull final String topic, @NonNull final String poem) { final ImagePrompt prompt = generatePrompt(topic, poem); return sendRequest(prompt); } private ImagePrompt generatePrompt(@NonNull final String topic, @Nullable final String poem) { String templateText = """ Create an image to accompany a haiku in an ancient temple hidden in the misty forest. The image should be in the traditional Japanese style, created by a master of the medium after 100 years of pondering the haiku. The theme for both the haiku and image is: {topic}. """; if (StringUtils.isNotBlank(poem)) { templateText += """ The poem is: {text} """; } final PromptTemplate template = new PromptTemplate(templateText); template.add("topic", topic); if (StringUtils.isNotBlank(poem)) { template.add("text", poem); } final String promptText = template.create().getContents(); log.info("Generated prompt: {}", promptText); return new ImagePrompt(promptText, DEFAULT_IMAGE_OPTIONS); } private ImageEntity sendRequest(@NonNull final ImagePrompt prompt) { log.info("Sending OpenAI request with prompt: {}", prompt); ImageResponse response = imageClient.call(prompt); log.info("OpenAI response: {}", response); ImageGeneration imageGeneration = response.getResult(); log.info("Extracted image generation from response: {}", imageGeneration); log.info(imageGeneration.getOutput()); final Image image = imageGeneration.getOutput(); final String url = image.getUrl(); final String metadata = imageGeneration.getMetadata().toString(); return new ImageEntity(url, metadata); } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((977, 1065), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((977, 1044), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
package com.kousenit.springaiexamples.rag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentReader; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.reader.TextReader; import org.springframework.ai.transformer.splitter.TextSplitter; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.io.File; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Service public class PossService { private static final Logger logger = LoggerFactory.getLogger(RagService.class); @Value("classpath:/data/chapter3_poss.txt") private Resource chapterResource; @Value("classpath:/prompts/quiz-prompt.st") private Resource quizPrompt; private final ChatClient aiClient; private final EmbeddingClient embeddingClient; @Autowired public PossService(@Qualifier("openAiChatClient") ChatClient aiClient, @Qualifier("openAiEmbeddingClient") EmbeddingClient embeddingClient) { this.aiClient = aiClient; this.embeddingClient = embeddingClient; } public Generation retrieve(String message) { SimpleVectorStore vectorStore = new SimpleVectorStore(embeddingClient); File possVectorStore = new File("src/main/resources/data/possVectorStore.json"); if (possVectorStore.exists()) { vectorStore.load(possVectorStore); } else { DocumentReader documentReader = new TextReader(chapterResource); List<Document> documents = documentReader.get(); TextSplitter splitter = new TokenTextSplitter(); List<Document> splitDocuments = splitter.apply(documents); logger.info("Creating Embeddings..."); vectorStore.add(splitDocuments); logger.info("Embeddings created."); vectorStore.save(possVectorStore); } List<Document> similarDocuments = vectorStore.similaritySearch( SearchRequest.query(message).withTopK(4)); Message systemMessage = getSystemMessage(similarDocuments, message); UserMessage userMessage = new UserMessage(message); Prompt prompt = new Prompt(List.of(systemMessage, userMessage)); ChatResponse response = aiClient.call(prompt); logger.info(response.getResult().toString()); return response.getResult(); } private Message getSystemMessage(List<Document> similarDocuments, String message) { String documents = similarDocuments.stream() .map(Document::getContent) .collect(Collectors.joining("\n")); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(quizPrompt); return systemPromptTemplate.createMessage( Map.of("documents", documents, "topic", message)); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2848, 2888), '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.ollama; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * Ollama Chat autoconfiguration properties. * * @author Christian Tzolov * @since 0.8.0 */ @ConfigurationProperties(OllamaChatProperties.CONFIG_PREFIX) public class OllamaChatProperties { public static final String CONFIG_PREFIX = "spring.ai.ollama.chat"; /** * Enable Ollama chat client. */ private boolean enabled = true; /** * Client lever Ollama options. Use this property to configure generative temperature, * topK and topP and alike parameters. The null values are ignored defaulting to the * generative's defaults. */ @NestedConfigurationProperty private OllamaOptions options = OllamaOptions.create().withModel(OllamaOptions.DEFAULT_MODEL); public String getModel() { return this.options.getModel(); } public void setModel(String model) { this.options.setModel(model); } public OllamaOptions getOptions() { return this.options; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return this.enabled; } }
[ "org.springframework.ai.ollama.api.OllamaOptions.create" ]
[((1503, 1564), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
package com.thomasvitale.ai.spring; import org.springframework.ai.document.DefaultContentFormatter; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class DocumentTransformersMetadataOllamaApplication { @Bean DefaultContentFormatter defaultContentFormatter() { return DefaultContentFormatter.builder() .withExcludedEmbedMetadataKeys("NewEmbedKey") .withExcludedInferenceMetadataKeys("NewInferenceKey") .build(); } @Bean SimpleVectorStore documentWriter(EmbeddingClient embeddingClient) { return new SimpleVectorStore(embeddingClient); } public static void main(String[] args) { SpringApplication.run(DocumentTransformersMetadataOllamaApplication.class, args); } }
[ "org.springframework.ai.document.DefaultContentFormatter.builder" ]
[((558, 748), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((558, 723), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((558, 653), 'org.springframework.ai.document.DefaultContentFormatter.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.openai; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.openai.OpenAiEmbeddingOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; @ConfigurationProperties(OpenAiEmbeddingProperties.CONFIG_PREFIX) public class OpenAiEmbeddingProperties extends OpenAiParentProperties { public static final String CONFIG_PREFIX = "spring.ai.openai.embedding"; public static final String DEFAULT_EMBEDDING_MODEL = "text-embedding-ada-002"; /** * Enable OpenAI embedding client. */ private boolean enabled = true; private MetadataMode metadataMode = MetadataMode.EMBED; @NestedConfigurationProperty private OpenAiEmbeddingOptions options = OpenAiEmbeddingOptions.builder() .withModel(DEFAULT_EMBEDDING_MODEL) .build(); public OpenAiEmbeddingOptions getOptions() { return this.options; } public void setOptions(OpenAiEmbeddingOptions options) { this.options = options; } public MetadataMode getMetadataMode() { return this.metadataMode; } public void setMetadataMode(MetadataMode metadataMode) { this.metadataMode = metadataMode; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
[ "org.springframework.ai.openai.OpenAiEmbeddingOptions.builder" ]
[((1449, 1530), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((1449, 1519), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.stabilityai; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.image.Image; import org.springframework.ai.image.ImageClient; import org.springframework.ai.image.ImageGeneration; import org.springframework.ai.image.ImageOptions; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.image.ImageResponseMetadata; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.ai.stabilityai.api.StabilityAiApi; import org.springframework.ai.stabilityai.api.StabilityAiImageOptions; import org.springframework.util.Assert; /** * StabilityAiImageClient is a class that implements the ImageClient interface. It * provides a client for calling the StabilityAI image generation API. */ public class StabilityAiImageClient implements ImageClient { private final Logger logger = LoggerFactory.getLogger(getClass()); private StabilityAiImageOptions options; private final StabilityAiApi stabilityAiApi; public StabilityAiImageClient(StabilityAiApi stabilityAiApi) { this(stabilityAiApi, StabilityAiImageOptions.builder().build()); } public StabilityAiImageClient(StabilityAiApi stabilityAiApi, StabilityAiImageOptions options) { Assert.notNull(stabilityAiApi, "StabilityAiApi must not be null"); Assert.notNull(options, "StabilityAiImageOptions must not be null"); this.stabilityAiApi = stabilityAiApi; this.options = options; } public StabilityAiImageOptions getOptions() { return this.options; } /** * Calls the StabilityAiImageClient with the given StabilityAiImagePrompt and returns * the ImageResponse. This overloaded call method lets you pass the full set of Prompt * instructions that StabilityAI supports. * @param imagePrompt the StabilityAiImagePrompt containing the prompt and image model * options * @return the ImageResponse generated by the StabilityAiImageClient */ public ImageResponse call(ImagePrompt imagePrompt) { ImageOptions runtimeOptions = imagePrompt.getOptions(); // Merge the runtime options passed via the prompt with the StabilityAiImageClient // options configured via Autoconfiguration. // Runtime options overwrite StabilityAiImageClient options StabilityAiImageOptions optionsToUse = ModelOptionsUtils.merge(runtimeOptions, this.options, StabilityAiImageOptions.class); // Copy the org.springframework.ai.model derived ImagePrompt and ImageOptions data // types to the data types used in StabilityAiApi StabilityAiApi.GenerateImageRequest generateImageRequest = getGenerateImageRequest(imagePrompt, optionsToUse); // Make the request StabilityAiApi.GenerateImageResponse generateImageResponse = this.stabilityAiApi .generateImage(generateImageRequest); // Convert to org.springframework.ai.model derived ImageResponse data type return convertResponse(generateImageResponse); } private static StabilityAiApi.GenerateImageRequest getGenerateImageRequest(ImagePrompt stabilityAiImagePrompt, StabilityAiImageOptions optionsToUse) { StabilityAiApi.GenerateImageRequest.Builder builder = new StabilityAiApi.GenerateImageRequest.Builder(); StabilityAiApi.GenerateImageRequest generateImageRequest = builder .withTextPrompts(stabilityAiImagePrompt.getInstructions() .stream() .map(message -> new StabilityAiApi.GenerateImageRequest.TextPrompts(message.getText(), message.getWeight())) .collect(Collectors.toList())) .withHeight(optionsToUse.getHeight()) .withWidth(optionsToUse.getWidth()) .withCfgScale(optionsToUse.getCfgScale()) .withClipGuidancePreset(optionsToUse.getClipGuidancePreset()) .withSampler(optionsToUse.getSampler()) .withSamples(optionsToUse.getN()) .withSeed(optionsToUse.getSeed()) .withSteps(optionsToUse.getSteps()) .withStylePreset(optionsToUse.getStylePreset()) .build(); return generateImageRequest; } private ImageResponse convertResponse(StabilityAiApi.GenerateImageResponse generateImageResponse) { List<ImageGeneration> imageGenerationList = generateImageResponse.artifacts().stream().map(entry -> { return new ImageGeneration(new Image(null, entry.base64()), new StabilityAiImageGenerationMetadata(entry.finishReason(), entry.seed())); }).toList(); return new ImageResponse(imageGenerationList, ImageResponseMetadata.NULL); } private StabilityAiImageOptions convertOptions(ImageOptions runtimeOptions) { StabilityAiImageOptions.Builder builder = StabilityAiImageOptions.builder(); if (runtimeOptions == null) { return builder.build(); } if (runtimeOptions.getN() != null) { builder.withN(runtimeOptions.getN()); } if (runtimeOptions.getModel() != null) { builder.withModel(runtimeOptions.getModel()); } if (runtimeOptions.getResponseFormat() != null) { builder.withResponseFormat(runtimeOptions.getResponseFormat()); } if (runtimeOptions.getWidth() != null) { builder.withWidth(runtimeOptions.getWidth()); } if (runtimeOptions.getHeight() != null) { builder.withHeight(runtimeOptions.getHeight()); } if (runtimeOptions instanceof StabilityAiImageOptions) { StabilityAiImageOptions stabilityAiImageOptions = (StabilityAiImageOptions) runtimeOptions; if (stabilityAiImageOptions.getCfgScale() != null) { builder.withCfgScale(stabilityAiImageOptions.getCfgScale()); } if (stabilityAiImageOptions.getClipGuidancePreset() != null) { builder.withClipGuidancePreset(stabilityAiImageOptions.getClipGuidancePreset()); } if (stabilityAiImageOptions.getSampler() != null) { builder.withSampler(stabilityAiImageOptions.getSampler()); } if (stabilityAiImageOptions.getSeed() != null) { builder.withSeed(stabilityAiImageOptions.getSeed()); } if (stabilityAiImageOptions.getSteps() != null) { builder.withSteps(stabilityAiImageOptions.getSteps()); } if (stabilityAiImageOptions.getStylePreset() != null) { builder.withStylePreset(stabilityAiImageOptions.getStylePreset()); } } return builder.build(); } }
[ "org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder" ]
[((1835, 1876), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.anthropic; import java.util.List; import org.springframework.ai.bedrock.anthropic.AnthropicChatOptions; import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.util.Assert; /** * Configuration properties for Bedrock Anthropic. * * @author Christian Tzolov * @since 0.8.0 */ @ConfigurationProperties(BedrockAnthropicChatProperties.CONFIG_PREFIX) public class BedrockAnthropicChatProperties { public static final String CONFIG_PREFIX = "spring.ai.bedrock.anthropic.chat"; /** * Enable Bedrock Anthropic chat client. Disabled by default. */ private boolean enabled = false; /** * The generative id to use. See the {@link AnthropicChatModel} for the supported * models. */ private String model = AnthropicChatModel.CLAUDE_V2.id(); @NestedConfigurationProperty private AnthropicChatOptions options = AnthropicChatOptions.builder() .withTemperature(0.7f) .withMaxTokensToSample(300) .withTopK(10) .withStopSequences(List.of("\n\nHuman:")) .build(); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public AnthropicChatOptions getOptions() { return options; } public void setOptions(AnthropicChatOptions options) { Assert.notNull(options, "AnthropicChatOptions must not be null"); Assert.notNull(options.getTemperature(), "AnthropicChatOptions.temperature must not be null"); this.options = options; } }
[ "org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id", "org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder" ]
[((1613, 1646), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((1719, 1875), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1864), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1820), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1804), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1774), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.chat; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @SpringBootTest(classes = OpenAiChatClient2IT.Config.class) @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") public class OpenAiChatClient2IT { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private OpenAiChatClient openAiChatClient; @Test void responseFormatTest() throws JsonMappingException, JsonProcessingException { // 400 - ResponseError[error=Error[message='json' is not one of ['json_object', // 'text'] - // 'response_format.type', type=invalid_request_error, param=null, code=null]] // 400 - ResponseError[error=Error[message='messages' must contain the word 'json' // in some form, to use // 'response_format' of type 'json_object'., type=invalid_request_error, // param=messages, code=null]] Prompt prompt = new Prompt("List 8 planets. Use JSON response", OpenAiChatOptions.builder() .withResponseFormat(new ChatCompletionRequest.ResponseFormat("json_object")) .build()); ChatResponse response = this.openAiChatClient.call(prompt); assertThat(response).isNotNull(); String content = response.getResult().getOutput().getContent(); logger.info("Response content: {}", content); assertThat(isValidJson(content)).isTrue(); } private static ObjectMapper MAPPER = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); public static boolean isValidJson(String json) { try { MAPPER.readTree(json); } catch (JacksonException e) { return false; } return true; } @SpringBootConfiguration static class Config { @Bean public OpenAiApi chatCompletionApi() { return new OpenAiApi(System.getenv("OPENAI_API_KEY")); } @Bean public OpenAiChatClient openAiClient(OpenAiApi openAiApi) { return new OpenAiChatClient(openAiApi); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((2629, 2752), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2629, 2738), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.reader.pdf; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.springframework.ai.document.Document; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class PagePdfDocumentReaderTests { @Test public void classpathRead() { PagePdfDocumentReader pdfReader = new PagePdfDocumentReader("classpath:/sample1.pdf", PdfDocumentReaderConfig.builder() .withPageTopMargin(0) .withPageBottomMargin(0) .withPageExtractedTextFormatter(ExtractedTextFormatter.builder() .withNumberOfTopTextLinesToDelete(0) .withNumberOfBottomTextLinesToDelete(3) .withNumberOfTopPagesToSkipBeforeDelete(0) .build()) .withPagesPerDocument(1) .build()); List<Document> docs = pdfReader.get(); assertThat(docs).hasSize(4); String allText = docs.stream().map(d -> d.getContent()).collect(Collectors.joining(System.lineSeparator())); assertThat(allText).doesNotContain( List.of("Page 1 of 4", "Page 2 of 4", "Page 3 of 4", "Page 4 of 4", "PDF Bookmark Sample")); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((1212, 1570), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1212, 1556), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1212, 1526), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1212, 1302), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1212, 1272), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1340, 1525), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1340, 1510), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1340, 1461), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1340, 1415), '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.reader.pdf; import org.junit.jupiter.api.Test; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Christian Tzolov */ public class ParagraphPdfDocumentReaderTests { @Test public void testPdfWithoutToc() { assertThatThrownBy(() -> { new ParagraphPdfDocumentReader("classpath:/sample1.pdf", PdfDocumentReaderConfig.builder() .withPageTopMargin(0) .withPageBottomMargin(0) .withPageExtractedTextFormatter(ExtractedTextFormatter.builder() .withNumberOfTopTextLinesToDelete(0) .withNumberOfBottomTextLinesToDelete(3) .withNumberOfTopPagesToSkipBeforeDelete(0) .build()) .withPagesPerDocument(1) .build()); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "Document outline (e.g. TOC) is null. Make sure the PDF document has a table of contents (TOC). If not, consider the PagePdfDocumentReader or the TikaDocumentReader instead."); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((1123, 1490), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1475), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1444), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1215), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1184), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1254, 1443), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1254, 1427), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1254, 1377), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1254, 1330), '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.metadata; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; import org.springframework.ai.chat.metadata.PromptMetadata; import org.springframework.ai.chat.metadata.PromptMetadata.PromptFilterMetadata; /** * Unit Tests for {@link PromptMetadata}. * * @author John Blum * @since 0.7.0 */ public class PromptMetadataTests { private PromptFilterMetadata mockPromptFilterMetadata(int index) { PromptFilterMetadata mockPromptFilterMetadata = mock(PromptFilterMetadata.class); doReturn(index).when(mockPromptFilterMetadata).getPromptIndex(); return mockPromptFilterMetadata; } @Test void emptyPromptMetadata() { PromptMetadata empty = PromptMetadata.empty(); assertThat(empty).isNotNull(); assertThat(empty).isEmpty(); } @Test void promptMetadataWithOneFilter() { PromptFilterMetadata mockPromptFilterMetadata = mockPromptFilterMetadata(0); PromptMetadata promptMetadata = PromptMetadata.of(mockPromptFilterMetadata); assertThat(promptMetadata).isNotNull(); assertThat(promptMetadata).containsExactly(mockPromptFilterMetadata); } @Test void promptMetadataWithTwoFilters() { PromptFilterMetadata mockPromptFilterMetadataOne = mockPromptFilterMetadata(0); PromptFilterMetadata mockPromptFilterMetadataTwo = mockPromptFilterMetadata(1); PromptMetadata promptMetadata = PromptMetadata.of(mockPromptFilterMetadataOne, mockPromptFilterMetadataTwo); assertThat(promptMetadata).isNotNull(); assertThat(promptMetadata).containsExactly(mockPromptFilterMetadataOne, mockPromptFilterMetadataTwo); } @Test void findByPromptIndex() { PromptFilterMetadata mockPromptFilterMetadataOne = mockPromptFilterMetadata(0); PromptFilterMetadata mockPromptFilterMetadataTwo = mockPromptFilterMetadata(1); PromptMetadata promptMetadata = PromptMetadata.of(mockPromptFilterMetadataOne, mockPromptFilterMetadataTwo); assertThat(promptMetadata).isNotNull(); assertThat(promptMetadata).containsExactly(mockPromptFilterMetadataOne, mockPromptFilterMetadataTwo); assertThat(promptMetadata.findByPromptIndex(1).orElse(null)).isEqualTo(mockPromptFilterMetadataTwo); assertThat(promptMetadata.findByPromptIndex(0).orElse(null)).isEqualTo(mockPromptFilterMetadataOne); } @Test void findByPromptIndexWithNoFilters() { assertThat(PromptMetadata.empty().findByPromptIndex(0)).isNotPresent(); } @Test void findByInvalidPromptIndex() { assertThatIllegalArgumentException().isThrownBy(() -> PromptMetadata.empty().findByPromptIndex(-1)) .withMessage("Prompt index [-1] must be greater than equal to 0") .withNoCause(); } @Test void fromPromptIndexAndContentFilterMetadata() { PromptFilterMetadata promptFilterMetadata = PromptFilterMetadata.from(1, "{ content-sentiment: 'SAFE' }"); assertThat(promptFilterMetadata).isNotNull(); assertThat(promptFilterMetadata.getPromptIndex()).isOne(); assertThat(promptFilterMetadata.<String>getContentFilterMetadata()).isEqualTo("{ content-sentiment: 'SAFE' }"); } }
[ "org.springframework.ai.chat.metadata.PromptMetadata.empty" ]
[((3129, 3172), 'org.springframework.ai.chat.metadata.PromptMetadata.empty'), ((3293, 3337), 'org.springframework.ai.chat.metadata.PromptMetadata.empty')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.azure.tool; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.azure.openai.AzureOpenAiAutoConfiguration; import org.springframework.ai.azure.openai.AzureOpenAiChatClient; import org.springframework.ai.azure.openai.AzureOpenAiChatOptions; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallback; import org.springframework.ai.model.function.FunctionCallbackWrapper; 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 static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+") @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+") public class FunctionCallWithFunctionWrapperIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionWrapperIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withPropertyValues( // @formatter:off "spring.ai.azure.openai.api-key=" + System.getenv("AZURE_OPENAI_API_KEY"), "spring.ai.azure.openai.endpoint=" + System.getenv("AZURE_OPENAI_ENDPOINT")) // @formatter:onn .withConfiguration(AutoConfigurations.of(AzureOpenAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner.withPropertyValues("spring.ai.azure.openai.chat.options.model=gpt-4-0125-preview") .run(context -> { AzureOpenAiChatClient chatClient = context.getBean(AzureOpenAiChatClient.class); UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, Paris and in Tokyo?"); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), AzureOpenAiChatOptions.builder().withFunction("WeatherInfo").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", "10"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15", "15.0"); }); } @Configuration static class Config { @Bean public FunctionCallback weatherFunctionInfo() { return FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("WeatherInfo") .withDescription("Get the current weather in a given location") .build(); } } }
[ "org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder" ]
[((2864, 2932), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2864, 2924), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3375, 3542), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3375, 3529), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3375, 3461), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.stabilityai; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.image.*; import org.springframework.ai.stabilityai.StyleEnum; import org.springframework.ai.stabilityai.api.StabilityAiImageOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "STABILITYAI_API_KEY", matches = ".*") public class StabilityAiAutoConfigurationIT { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.stabilityai.image.api-key=" + System.getenv("STABILITYAI_API_KEY")) .withConfiguration(AutoConfigurations.of(StabilityAiImageAutoConfiguration.class)); @Test void generate() { contextRunner.run(context -> { ImageClient imageClient = context.getBean(ImageClient.class); 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 = imageClient.call(imagePrompt); ImageGeneration imageGeneration = imageResponse.getResult(); Image image = imageGeneration.getOutput(); assertThat(image.getB64Json()).isNotEmpty(); }); } }
[ "org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder" ]
[((1714, 1805), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder'), ((1714, 1792), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.titan; import java.io.IOException; import java.util.Base64; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi; import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.io.DefaultResourceLoader; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") class BedrockTitanEmbeddingClientIT { @Autowired private BedrockTitanEmbeddingClient embeddingClient; @Test void singleEmbedding() { 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 void imageEmbedding() throws IOException { byte[] image = new DefaultResourceLoader().getResource("classpath:/spring_framework.png") .getContentAsByteArray(); EmbeddingResponse embeddingResponse = embeddingClient .embedForResponse(List.of(Base64.getEncoder().encodeToString(image))); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty(); assertThat(embeddingClient.dimensions()).isEqualTo(1024); } @SpringBootConfiguration public static class TestConfiguration { @Bean public TitanEmbeddingBedrockApi titanEmbeddingApi() { return new TitanEmbeddingBedrockApi(TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id(), Region.US_EAST_1.id()); } @Bean public BedrockTitanEmbeddingClient titanEmbedding(TitanEmbeddingBedrockApi titanEmbeddingApi) { return new BedrockTitanEmbeddingClient(titanEmbeddingApi); } } }
[ "org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id" ]
[((2380, 2421), 'java.util.Base64.getEncoder'), ((2795, 2840), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id'), ((2842, 2863), '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.milvus; import org.junit.jupiter.api.Test; import org.springframework.ai.ResourceUtils; import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusVectorStoreAutoConfiguration; 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.AutoConfigurations; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.milvus.MilvusContainer; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @SpringJUnitConfig @Testcontainers @TestPropertySource(properties = { "spring.ai.vectorstore.milvus.metricType=COSINE", "spring.ai.vectorstore.milvus.indexType=IVF_FLAT", "spring.ai.vectorstore.milvus.embeddingDimension=384", "spring.ai.vectorstore.milvus.collectionName=myTestCollection" }) class MilvusContainerConnectionDetailsFactoryTest { @Container @ServiceConnection static MilvusContainer milvusContainer = new MilvusContainer("milvusdb/milvus:v2.3.8"); List<Document> documents = List.of( new Document(ResourceUtils.getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document(ResourceUtils.getText("classpath:/test/data/time.shelter.txt")), new Document( ResourceUtils.getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MilvusVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class); @Autowired private VectorStore vectorStore; @Test public void addAndSearch() { vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()) .contains("Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).hasSize(2); assertThat(resultDoc.getMetadata()).containsKeys("spring", "distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(0); } @Configuration(proxyBeanMethods = false) @ImportAutoConfiguration(MilvusVectorStoreAutoConfiguration.class) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3232, 3273), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3849, 3890), '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.vectorstore.neo4j; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.ai.ResourceUtils; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jingzhou Ou */ @Testcontainers public class Neo4jVectorStoreAutoConfigurationIT { // Needs to be Neo4j 5.15+, because Neo4j 5.15 deprecated the used embedding storing // function. @Container static Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>(DockerImageName.parse("neo4j:5.15")) .withRandomPassword(); List<Document> documents = List.of( new Document(ResourceUtils.getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document(ResourceUtils.getText("classpath:/test/data/time.shelter.txt")), new Document( ResourceUtils.getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.neo4j.uri=" + neo4jContainer.getBoltUrl(), "spring.neo4j.authentication.username=" + "neo4j", "spring.neo4j.authentication.password=" + neo4jContainer.getAdminPassword()); @Test void addAndSearch() { contextRunner .withPropertyValues("spring.ai.vectorstore.neo4j.label=my_test_label", "spring.ai.vectorstore.neo4j.embeddingDimension=384", "spring.ai.vectorstore.neo4j.indexName=customIndexName") .run(context -> { var properties = context.getBean(Neo4jVectorStoreProperties.class); assertThat(properties.getLabel()).isEqualTo("my_test_label"); assertThat(properties.getEmbeddingDimension()).isEqualTo(384); assertThat(properties.getIndexName()).isEqualTo("customIndexName"); VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).isEmpty(); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3534, 3575), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4044, 4085), '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 java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.AssistantMessage; import reactor.core.publisher.Flux; import software.amazon.awssdk.regions.Region; import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties; import org.springframework.ai.bedrock.cohere.BedrockCohereChatClient; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.ReturnLikelihoods; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.Truncate; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov * @since 0.8.0 */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class BedrockCohereChatAutoConfigurationIT { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.cohere.chat.enabled=true", "spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"), "spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"), "spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(), "spring.ai.bedrock.cohere.chat.model=" + CohereChatModel.COHERE_COMMAND_V14.id(), "spring.ai.bedrock.cohere.chat.options.temperature=0.5", "spring.ai.bedrock.cohere.chat.options.maxTokens=500") .withConfiguration(AutoConfigurations.of(BedrockCohereChatAutoConfiguration.class)); private final Message systemMessage = new SystemPromptTemplate(""" You are a helpful AI assistant. Your name is {name}. You are an AI assistant that helps people find information. Your name is {name} You should reply to the user's request with your name and also in the style of a {voice}. """).createMessage(Map.of("name", "Bob", "voice", "pirate")); private final UserMessage userMessage = new UserMessage( "Tell me about 3 famous pirates from the Golden Age of Piracy and why they did."); @Test public void chatCompletion() { contextRunner.run(context -> { BedrockCohereChatClient cohereChatClient = context.getBean(BedrockCohereChatClient.class); ChatResponse response = cohereChatClient.call(new Prompt(List.of(userMessage, systemMessage))); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); }); } @Test public void chatCompletionStreaming() { contextRunner.run(context -> { BedrockCohereChatClient cohereChatClient = context.getBean(BedrockCohereChatClient.class); Flux<ChatResponse> response = cohereChatClient.stream(new Prompt(List.of(userMessage, systemMessage))); List<ChatResponse> responses = response.collectList().block(); assertThat(responses.size()).isGreaterThan(2); String stitchedResponseContent = responses.stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); assertThat(stitchedResponseContent).contains("Blackbeard"); }); } @Test public void propertiesTest() { new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.cohere.chat.enabled=true", "spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY", "spring.ai.bedrock.cohere.chat.model=MODEL_XYZ", "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), "spring.ai.bedrock.cohere.chat.options.temperature=0.55", "spring.ai.bedrock.cohere.chat.options.topP=0.55", "spring.ai.bedrock.cohere.chat.options.topK=10", "spring.ai.bedrock.cohere.chat.options.stopSequences=END1,END2", "spring.ai.bedrock.cohere.chat.options.returnLikelihoods=ALL", "spring.ai.bedrock.cohere.chat.options.numGenerations=3", "spring.ai.bedrock.cohere.chat.options.truncate=START", "spring.ai.bedrock.cohere.chat.options.maxTokens=123") .withConfiguration(AutoConfigurations.of(BedrockCohereChatAutoConfiguration.class)) .run(context -> { var chatProperties = context.getBean(BedrockCohereChatProperties.class); var aswProperties = context.getBean(BedrockAwsConnectionProperties.class); assertThat(chatProperties.isEnabled()).isTrue(); assertThat(aswProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id()); assertThat(chatProperties.getModel()).isEqualTo("MODEL_XYZ"); assertThat(chatProperties.getOptions().getTemperature()).isEqualTo(0.55f); assertThat(chatProperties.getOptions().getTopP()).isEqualTo(0.55f); assertThat(chatProperties.getOptions().getTopK()).isEqualTo(10); assertThat(chatProperties.getOptions().getStopSequences()).isEqualTo(List.of("END1", "END2")); assertThat(chatProperties.getOptions().getReturnLikelihoods()).isEqualTo(ReturnLikelihoods.ALL); assertThat(chatProperties.getOptions().getNumGenerations()).isEqualTo(3); assertThat(chatProperties.getOptions().getTruncate()).isEqualTo(Truncate.START); assertThat(chatProperties.getOptions().getMaxTokens()).isEqualTo(123); assertThat(aswProperties.getAccessKey()).isEqualTo("ACCESS_KEY"); assertThat(aswProperties.getSecretKey()).isEqualTo("SECRET_KEY"); }); } @Test public void chatCompletionDisabled() { // It is disabled by default new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BedrockCohereChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockCohereChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockCohereChatClient.class)).isEmpty(); }); // Explicitly enable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.cohere.chat.enabled=true") .withConfiguration(AutoConfigurations.of(BedrockCohereChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockCohereChatProperties.class)).isNotEmpty(); assertThat(context.getBeansOfType(BedrockCohereChatClient.class)).isNotEmpty(); }); // Explicitly disable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.cohere.chat.enabled=false") .withConfiguration(AutoConfigurations.of(BedrockCohereChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockCohereChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockCohereChatClient.class)).isEmpty(); }); } }
[ "org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id" ]
[((2594, 2615), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2662, 2701), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id'), ((4819, 4843), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((5705, 5729), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.anthropic; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.chat.messages.AssistantMessage; import reactor.core.publisher.Flux; import software.amazon.awssdk.regions.Region; import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties; import org.springframework.ai.bedrock.anthropic.BedrockAnthropicChatClient; import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov * @since 0.8.0 */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class BedrockAnthropicChatAutoConfigurationIT { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=true", "spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"), "spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"), "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), "spring.ai.bedrock.anthropic.chat.model=" + AnthropicChatModel.CLAUDE_V2.id(), "spring.ai.bedrock.anthropic.chat.options.temperature=0.5") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)); private final Message systemMessage = new SystemPromptTemplate(""" You are a helpful AI assistant. Your name is {name}. You are an AI assistant that helps people find information. Your name is {name} You should reply to the user's request with your name and also in the style of a {voice}. """).createMessage(Map.of("name", "Bob", "voice", "pirate")); private final UserMessage userMessage = new UserMessage( "Tell me about 3 famous pirates from the Golden Age of Piracy and why they did."); @Test public void chatCompletion() { contextRunner.run(context -> { BedrockAnthropicChatClient anthropicChatClient = context.getBean(BedrockAnthropicChatClient.class); ChatResponse response = anthropicChatClient.call(new Prompt(List.of(userMessage, systemMessage))); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); }); } @Test public void chatCompletionStreaming() { contextRunner.run(context -> { BedrockAnthropicChatClient anthropicChatClient = context.getBean(BedrockAnthropicChatClient.class); Flux<ChatResponse> response = anthropicChatClient.stream(new Prompt(List.of(userMessage, systemMessage))); List<ChatResponse> responses = response.collectList().block(); assertThat(responses.size()).isGreaterThan(2); String stitchedResponseContent = responses.stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); assertThat(stitchedResponseContent).contains("Blackbeard"); }); } @Test public void propertiesTest() { new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=true", "spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY", "spring.ai.bedrock.anthropic.chat.model=MODEL_XYZ", "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), "spring.ai.bedrock.anthropic.chat.options.temperature=0.55") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { var anthropicChatProperties = context.getBean(BedrockAnthropicChatProperties.class); var awsProperties = context.getBean(BedrockAwsConnectionProperties.class); assertThat(anthropicChatProperties.isEnabled()).isTrue(); assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id()); assertThat(anthropicChatProperties.getOptions().getTemperature()).isEqualTo(0.55f); assertThat(anthropicChatProperties.getModel()).isEqualTo("MODEL_XYZ"); assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY"); assertThat(awsProperties.getSecretKey()).isEqualTo("SECRET_KEY"); }); } @Test public void chatCompletionDisabled() { // It is disabled by default new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockAnthropicChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockAnthropicChatClient.class)).isEmpty(); }); // Explicitly enable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=true") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockAnthropicChatProperties.class)).isNotEmpty(); assertThat(context.getBeansOfType(BedrockAnthropicChatClient.class)).isNotEmpty(); }); // Explicitly disable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=false") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockAnthropicChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockAnthropicChatClient.class)).isEmpty(); }); } }
[ "org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id" ]
[((2413, 2437), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((2487, 2520), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((4615, 4639), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((5101, 5125), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')]