code
stringlengths
1.02k
14.1k
apis
sequencelengths
1
7
extract_api
stringlengths
72
2.99k
package com.thomasvitale.ai.spring; import jakarta.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.document.Document; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.PagePdfDocumentReader; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class DocumentInitializer { private static final Logger log = LoggerFactory.getLogger(DocumentInitializer.class); private final SimpleVectorStore vectorStore; @Value("classpath:documents/story1.pdf") Resource pdfFile1; @Value("classpath:documents/story2.pdf") Resource pdfFile2; public DocumentInitializer(SimpleVectorStore vectorStore) { this.vectorStore = vectorStore; } @PostConstruct public void run() { List<Document> documents = new ArrayList<>(); log.info("Loading PDF files as Documents"); var pdfReader1 = new PagePdfDocumentReader(pdfFile1); documents.addAll(pdfReader1.get()); log.info("Loading PDF files as Documents after reformatting"); var pdfReader2 = new PagePdfDocumentReader(pdfFile2, PdfDocumentReaderConfig.builder() .withPageExtractedTextFormatter(ExtractedTextFormatter.builder() .withNumberOfTopPagesToSkipBeforeDelete(0) .withNumberOfBottomTextLinesToDelete(1) .withNumberOfTopTextLinesToDelete(1) .build()) .withPagesPerDocument(1) .build()); documents.addAll(pdfReader2.get()); log.info("Creating and storing Embeddings from Documents"); vectorStore.add(documents); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((1474, 1880), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1474, 1855), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1474, 1814), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1556, 1813), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1556, 1780), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1556, 1719), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1556, 1655), 'org.springframework.ai.reader.ExtractedTextFormatter.builder')]
/* * 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; import java.util.List; import java.util.Map; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.StreamingChatClient; import org.springframework.ai.chat.metadata.ChatGenerationMetadata; import org.springframework.ai.chat.prompt.ChatOptions; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.ai.watsonx.api.WatsonxAiApi; import org.springframework.ai.watsonx.api.WatsonxAiRequest; import org.springframework.ai.watsonx.api.WatsonxAiResponse; import org.springframework.ai.watsonx.utils.MessageToPromptConverter; import org.springframework.util.Assert; /** * {@link ChatClient} implementation for {@literal watsonx.ai}. * * watsonx.ai allows developers to use large language models within a SaaS service. It * supports multiple open-source models as well as IBM created models * [watsonx.ai](https://www.ibm.com/products/watsonx-ai). Please refer to the <a href= * "https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx">watsonx.ai * models</a> for the most up-to-date information about the available models. * * @author Pablo Sanchidrian Herrera * @author John Jario Moreno Rojas * @author Christian Tzolov * @since 1.0.0 */ public class WatsonxAiChatClient implements ChatClient, StreamingChatClient { private final WatsonxAiApi watsonxAiApi; private final WatsonxAiChatOptions defaultOptions; public WatsonxAiChatClient(WatsonxAiApi watsonxAiApi) { this(watsonxAiApi, WatsonxAiChatOptions.builder() .withTemperature(0.7f) .withTopP(1.0f) .withTopK(50) .withDecodingMethod("greedy") .withMaxNewTokens(20) .withMinNewTokens(0) .withRepetitionPenalty(1.0f) .build()); } public WatsonxAiChatClient(WatsonxAiApi watsonxAiApi, WatsonxAiChatOptions defaultOptions) { Assert.notNull(watsonxAiApi, "watsonxAiApi cannot be null"); Assert.notNull(defaultOptions, "defaultOptions cannot be null"); this.watsonxAiApi = watsonxAiApi; this.defaultOptions = defaultOptions; } @Override public ChatResponse call(Prompt prompt) { WatsonxAiRequest request = request(prompt); WatsonxAiResponse response = this.watsonxAiApi.generate(request).getBody(); var generator = new Generation(response.results().get(0).generatedText()); generator = generator.withGenerationMetadata( ChatGenerationMetadata.from(response.results().get(0).stopReason(), response.system())); return new ChatResponse(List.of(generator)); } @Override public Flux<ChatResponse> stream(Prompt prompt) { WatsonxAiRequest request = request(prompt); Flux<WatsonxAiResponse> response = this.watsonxAiApi.generateStreaming(request); return response.map(chunk -> { Generation generation = new Generation(chunk.results().get(0).generatedText()); if (chunk.system() != null) { generation = generation.withGenerationMetadata( ChatGenerationMetadata.from(chunk.results().get(0).stopReason(), chunk.system())); } return new ChatResponse(List.of(generation)); }); } public WatsonxAiRequest request(Prompt prompt) { WatsonxAiChatOptions options = WatsonxAiChatOptions.builder().build(); if (this.defaultOptions != null) { options = ModelOptionsUtils.merge(options, this.defaultOptions, WatsonxAiChatOptions.class); } if (prompt.getOptions() != null) { if (prompt.getOptions() instanceof ChatOptions runtimeOptions) { var updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions, ChatOptions.class, WatsonxAiChatOptions.class); options = ModelOptionsUtils.merge(updatedRuntimeOptions, options, WatsonxAiChatOptions.class); } else { throw new IllegalArgumentException("Prompt options are not of type ChatOptions: " + prompt.getOptions().getClass().getSimpleName()); } } Map<String, Object> parameters = options.toMap(); final String convertedPrompt = MessageToPromptConverter.create() .withAssistantPrompt("") .withHumanPrompt("") .toPrompt(prompt.getInstructions()); return WatsonxAiRequest.builder(convertedPrompt).withParameters(parameters).build(); } }
[ "org.springframework.ai.watsonx.api.WatsonxAiRequest.builder", "org.springframework.ai.watsonx.utils.MessageToPromptConverter.create" ]
[((4737, 4861), 'org.springframework.ai.watsonx.utils.MessageToPromptConverter.create'), ((4737, 4822), 'org.springframework.ai.watsonx.utils.MessageToPromptConverter.create'), ((4737, 4798), 'org.springframework.ai.watsonx.utils.MessageToPromptConverter.create'), ((4873, 4949), 'org.springframework.ai.watsonx.api.WatsonxAiRequest.builder'), ((4873, 4941), 'org.springframework.ai.watsonx.api.WatsonxAiRequest.builder')]
package org.springframework.ai.aot.test.pgvector; import java.util.List; import java.util.Map; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; @SpringBootApplication public class PgVectorStoreApplication { public static void main(String[] args) { new SpringApplicationBuilder(PgVectorStoreApplication.class) .web(WebApplicationType.NONE) .run(args); } @Bean ApplicationRunner applicationRunner(VectorStore vectorStore, EmbeddingClient embeddingClient) { return args -> { List<Document> documents = List.of( new Document( "Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")), new Document("The World is Big and Salvation Lurks Around the Corner"), new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2"))); // Add the documents to PGVector vectorStore.add(documents); Thread.sleep(5000); // Retrieve documents similar to a query List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5)); System.out.println("RESULTS: " + results);}; } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1540, 1581), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package com.xisui.springbootai; import org.junit.jupiter.api.Test; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.reader.JsonReader; import org.springframework.ai.reader.TextReader; import org.springframework.ai.reader.tika.TikaDocumentReader; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import java.util.List; /** * @author tycoding * @since 2024/3/5 */ @SpringBootTest public class EmbeddingTest { @Autowired private EmbeddingClient embeddingClient; @Autowired private VectorStore vectorStore; @Value("classpath:data.json") private Resource jsonResource; @Value("classpath:data.docx") private Resource docxResource; @Value("classpath:data.xlsx") private Resource excelResource; @Value("classpath:data.txt") private Resource txtResource; @Test void embedding() { String text = "我是一个Java程序员"; List<Double> embedList = embeddingClient.embed(text); List<Document> documents = List.of(new Document(text)); vectorStore.add(documents); } @Test void search() { List<Document> d1 = vectorStore.similaritySearch("我是"); List<Document> d2 = vectorStore.similaritySearch(SearchRequest.query("我是").withTopK(5)); System.out.println("----"); } @Test void jsonReader() { JsonReader reader = new JsonReader(jsonResource, "type", "keyword"); vectorStore.add(reader.get()); } @Test void txtReader() { TextReader reader = new TextReader(txtResource); reader.getCustomMetadata().put("filename", "data1.txt"); vectorStore.add(reader.get()); } @Test void docReader() { TikaDocumentReader reader = new TikaDocumentReader(docxResource); vectorStore.add(reader.get()); } @Test void filter() { } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1589, 1630), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.embedding; import org.junit.jupiter.api.Test; import org.springframework.ai.embedding.EmbeddingRequest; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.ai.openai.OpenAiEmbeddingClient; import org.springframework.ai.openai.OpenAiEmbeddingOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest class EmbeddingIT { @Autowired private OpenAiEmbeddingClient embeddingClient; @Test void defaultEmbedding() { assertThat(embeddingClient).isNotNull(); EmbeddingResponse embeddingResponse = embeddingClient.embedForResponse(List.of("Hello World")); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0)).isNotNull(); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(1536); assertThat(embeddingResponse.getMetadata()).containsEntry("model", "text-embedding-ada-002"); assertThat(embeddingResponse.getMetadata()).containsEntry("total-tokens", 2); assertThat(embeddingResponse.getMetadata()).containsEntry("prompt-tokens", 2); assertThat(embeddingClient.dimensions()).isEqualTo(1536); } @Test void embedding3Large() { EmbeddingResponse embeddingResponse = embeddingClient.call(new EmbeddingRequest(List.of("Hello World"), OpenAiEmbeddingOptions.builder().withModel("text-embedding-3-large").build())); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0)).isNotNull(); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(3072); assertThat(embeddingResponse.getMetadata()).containsEntry("model", "text-embedding-3-large"); assertThat(embeddingResponse.getMetadata()).containsEntry("total-tokens", 2); assertThat(embeddingResponse.getMetadata()).containsEntry("prompt-tokens", 2); // assertThat(embeddingClient.dimensions()).isEqualTo(3072); } @Test void textEmbeddingAda002() { EmbeddingResponse embeddingResponse = embeddingClient.call(new EmbeddingRequest(List.of("Hello World"), OpenAiEmbeddingOptions.builder().withModel("text-embedding-3-small").build())); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0)).isNotNull(); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(1536); assertThat(embeddingResponse.getMetadata()).containsEntry("model", "text-embedding-3-small"); assertThat(embeddingResponse.getMetadata()).containsEntry("total-tokens", 2); assertThat(embeddingResponse.getMetadata()).containsEntry("prompt-tokens", 2); // assertThat(embeddingClient.dimensions()).isEqualTo(3072); } }
[ "org.springframework.ai.openai.OpenAiEmbeddingOptions.builder" ]
[((2092, 2168), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((2092, 2160), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((2846, 2922), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((2846, 2914), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.vectorstore; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.RedisVectorStore.MetadataField; import org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.core.io.DefaultResourceLoader; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import com.redis.testcontainers.RedisStackContainer; /** * @author Julien Ruaux */ @Testcontainers class RedisVectorStoreIT { @Container static RedisStackContainer redisContainer = new RedisStackContainer( RedisStackContainer.DEFAULT_IMAGE_NAME.withTag(RedisStackContainer.DEFAULT_TAG)); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestApplication.class); List<Document> documents = List.of( new Document("1", getText("classpath:/test/data/spring.ai.txt"), Map.of("meta1", "meta1")), new Document("2", getText("classpath:/test/data/time.shelter.txt"), Map.of()), new Document("3", getText("classpath:/test/data/great.depression.txt"), Map.of("meta2", "meta2"))); public static String getText(String uri) { var resource = new DefaultResourceLoader().getResource(uri); try { return resource.getContentAsString(StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } @BeforeEach void cleanDatabase() { this.contextRunner.run(context -> context.getBean(RedisVectorStore.class).getJedis().flushAll()); } @Test void ensureIndexGetsCreated() { this.contextRunner.run(context -> { assertThat(context.getBean(RedisVectorStore.class) .getJedis() .ftList() .contains(RedisVectorStore.DEFAULT_INDEX_NAME)); }); } @Test void addAndSearch() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).hasSize(2); assertThat(resultDoc.getMetadata()).containsKeys("meta1", RedisVectorStore.DISTANCE_FIELD_NAME); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).isEmpty(); }); } @Test void searchWithFilters() throws InterruptedException { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2020)); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "NL")); var bgDocument2 = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2023)); vectorStore.add(List.of(bgDocument, nlDocument, bgDocument2)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("The World").withTopK(5)); assertThat(results).hasSize(3); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'NL'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG'")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG' && year == 2020")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("NOT(country == 'BG' && year == 2020)")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(nlDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(nlDocument.getId(), bgDocument2.getId()); }); } @Test void documentUpdate() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); Document document = new Document(UUID.randomUUID().toString(), "Spring AI rocks!!", Collections.singletonMap("meta1", "meta1")); vectorStore.add(List.of(document)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("Spring AI rocks!!"); assertThat(resultDoc.getMetadata()).containsKey("meta1"); assertThat(resultDoc.getMetadata()).containsKey(RedisVectorStore.DISTANCE_FIELD_NAME); Document sameIdDocument = new Document(document.getId(), "The World is Big and Salvation Lurks Around the Corner", Collections.singletonMap("meta2", "meta2")); vectorStore.add(List.of(sameIdDocument)); results = vectorStore.similaritySearch(SearchRequest.query("FooBar").withTopK(5)); assertThat(results).hasSize(1); resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("The World is Big and Salvation Lurks Around the Corner"); assertThat(resultDoc.getMetadata()).containsKey("meta2"); assertThat(resultDoc.getMetadata()).containsKey(RedisVectorStore.DISTANCE_FIELD_NAME); vectorStore.delete(List.of(document.getId())); }); } @Test void searchWithThreshold() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> fullResult = vectorStore .similaritySearch(SearchRequest.query("Spring").withTopK(5).withSimilarityThresholdAll()); List<Float> distances = fullResult.stream() .map(doc -> (Float) doc.getMetadata().get(RedisVectorStore.DISTANCE_FIELD_NAME)) .toList(); assertThat(distances).hasSize(3); float threshold = (distances.get(0) + distances.get(1)) / 2; List<Document> results = vectorStore .similaritySearch(SearchRequest.query("Spring").withTopK(5).withSimilarityThreshold(1 - threshold)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).containsKeys("meta1", RedisVectorStore.DISTANCE_FIELD_NAME); }); } @SpringBootConfiguration @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) public static class TestApplication { @Bean public RedisVectorStore vectorStore(EmbeddingClient embeddingClient) { return new RedisVectorStore(RedisVectorStoreConfig.builder() .withURI(redisContainer.getRedisURI()) .withMetadataFields(MetadataField.tag("meta1"), MetadataField.tag("meta2"), MetadataField.tag("country"), MetadataField.numeric("year")) .build(), embeddingClient); } @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder" ]
[((2022, 2101), 'com.redis.testcontainers.RedisStackContainer.DEFAULT_IMAGE_NAME.withTag'), ((6436, 6464), 'java.util.UUID.randomUUID'), ((9159, 9394), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((9159, 9381), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((9159, 9234), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder')]
package org.springframework.ai.aot.test.mistralai; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.mistralai.MistralAiChatClient; import org.springframework.ai.mistralai.MistralAiChatOptions; import org.springframework.ai.mistralai.MistralAiEmbeddingClient; import org.springframework.ai.mistralai.api.MistralAiApi; 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; @SpringBootApplication public class MistralAiAotDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(MistralAiAotDemoApplication.class) .web(WebApplicationType.NONE) .run(args); } @Bean ApplicationRunner applicationRunner(MistralAiChatClient chatClient, MistralAiEmbeddingClient embeddingClient) { return args -> { // Synchronous Chat Client String response = chatClient.call("Tell me a joke."); System.out.println("SYNC RESPONSE: " + response); // Streaming Chat Client Flux<ChatResponse> flux = chatClient.stream(new Prompt("Tell me a joke.")); String fluxResponse = flux.collectList().block().stream().map(r -> r.getResult().getOutput().getContent()) .collect(Collectors.joining()); System.out.println("ASYNC RESPONSE: " + fluxResponse); // Embedding Client List<List<Double>> embeddings = embeddingClient.embed(List.of("Hello", "World")); System.out.println("EMBEDDINGS SIZE: " + embeddings.size()); // Function calling. // Function name is the bean name. Only the Mistral AI large and small models support function calling. ChatResponse paymentStatusResponse = chatClient .call(new Prompt("What's the status of my transaction with id T1005?", MistralAiChatOptions.builder() .withModel(MistralAiApi.ChatModel.SMALL.getValue()) .withFunction("retrievePaymentStatus").build())); System.out.println("PAYMENT STATUS: " + paymentStatusResponse.getResult().getOutput().getContent()); }; } public record Transaction(String transactionId) { } public record Status(String status) { } @Bean @Description("Get payment status of a transaction") public Function<Transaction, Status> retrievePaymentStatus() { return (transaction) -> new Status(PAYMENT_DATA.get(transaction).status()); } // Assuming we have the following data public static final Map<Transaction, Status> PAYMENT_DATA = Map.of( new Transaction("T1001"), new Status("Paid"), new Transaction("T1002"), new Status("Unpaid"), new Transaction("T1003"), new Status("Paid"), new Transaction("T1004"), new Status("Paid"), new Transaction("T1005"), new Status("Pending")); }
[ "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue", "org.springframework.ai.mistralai.MistralAiChatOptions.builder" ]
[((2380, 2581), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((2380, 2573), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((2380, 2498), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((2458, 2497), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.vectorstore.filter; import org.junit.jupiter.api.Test; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.filter.FilterExpressionTextParser.FilterExpressionParseException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Christian Tzolov */ public class SearchRequestTests { @Test public void createDefaults() { var emptyRequest = SearchRequest.defaults(); assertThat(emptyRequest.getQuery()).isEqualTo(""); checkDefaults(emptyRequest); } @Test public void createQuery() { var emptyRequest = SearchRequest.query("New Query"); assertThat(emptyRequest.getQuery()).isEqualTo("New Query"); checkDefaults(emptyRequest); } @Test public void createFrom() { var originalRequest = SearchRequest.query("New Query") .withTopK(696) .withSimilarityThreshold(0.678) .withFilterExpression("country == 'NL'"); var newRequest = SearchRequest.from(originalRequest); assertThat(newRequest).isNotSameAs(originalRequest); assertThat(newRequest.getQuery()).isEqualTo(originalRequest.getQuery()); assertThat(newRequest.getTopK()).isEqualTo(originalRequest.getTopK()); assertThat(newRequest.getFilterExpression()).isEqualTo(originalRequest.getFilterExpression()); assertThat(newRequest.getSimilarityThreshold()).isEqualTo(originalRequest.getSimilarityThreshold()); } @Test public void withQuery() { var emptyRequest = SearchRequest.defaults(); assertThat(emptyRequest.getQuery()).isEqualTo(""); emptyRequest.withQuery("New Query"); assertThat(emptyRequest.getQuery()).isEqualTo("New Query"); } @Test() public void withSimilarityThreshold() { var request = SearchRequest.query("Test").withSimilarityThreshold(0.678); assertThat(request.getSimilarityThreshold()).isEqualTo(0.678); request.withSimilarityThreshold(0.9); assertThat(request.getSimilarityThreshold()).isEqualTo(0.9); assertThatThrownBy(() -> { request.withSimilarityThreshold(-1); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Similarity threshold must be in [0,1] range."); assertThatThrownBy(() -> { request.withSimilarityThreshold(1.1); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Similarity threshold must be in [0,1] range."); } @Test() public void withTopK() { var request = SearchRequest.query("Test").withTopK(66); assertThat(request.getTopK()).isEqualTo(66); request.withTopK(89); assertThat(request.getTopK()).isEqualTo(89); assertThatThrownBy(() -> { request.withTopK(-1); }).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("TopK should be positive."); } @Test() public void withFilterExpression() { var request = SearchRequest.query("Test").withFilterExpression("country == 'BG' && year >= 2022"); assertThat(request.getFilterExpression()).isEqualTo(new Filter.Expression(Filter.ExpressionType.AND, new Filter.Expression(Filter.ExpressionType.EQ, new Filter.Key("country"), new Filter.Value("BG")), new Filter.Expression(Filter.ExpressionType.GTE, new Filter.Key("year"), new Filter.Value(2022)))); assertThat(request.hasFilterExpression()).isTrue(); request.withFilterExpression("active == true"); assertThat(request.getFilterExpression()).isEqualTo( new Filter.Expression(Filter.ExpressionType.EQ, new Filter.Key("active"), new Filter.Value(true))); assertThat(request.hasFilterExpression()).isTrue(); request.withFilterExpression(new FilterExpressionBuilder().eq("country", "NL").build()); assertThat(request.getFilterExpression()).isEqualTo( new Filter.Expression(Filter.ExpressionType.EQ, new Filter.Key("country"), new Filter.Value("NL"))); assertThat(request.hasFilterExpression()).isTrue(); request.withFilterExpression((String) null); assertThat(request.getFilterExpression()).isNull(); assertThat(request.hasFilterExpression()).isFalse(); request.withFilterExpression((Filter.Expression) null); assertThat(request.getFilterExpression()).isNull(); assertThat(request.hasFilterExpression()).isFalse(); assertThatThrownBy(() -> { request.withFilterExpression("FooBar"); }).isInstanceOf(FilterExpressionParseException.class) .hasMessageContaining("Error: no viable alternative at input 'FooBar'"); } private void checkDefaults(SearchRequest request) { assertThat(request.getFilterExpression()).isNull(); assertThat(request.getSimilarityThreshold()).isEqualTo(SearchRequest.SIMILARITY_THRESHOLD_ACCEPT_ALL); assertThat(request.getTopK()).isEqualTo(SearchRequest.DEFAULT_TOP_K); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1490, 1619), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((1490, 1575), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((1490, 1540), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((2392, 2450), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3066, 3106), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3451, 3534), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.cohere.api; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingRequest; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingResponse; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class CohereEmbeddingBedrockApiIT { CohereEmbeddingBedrockApi api = new CohereEmbeddingBedrockApi( CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); @Test public void embedText() { CohereEmbeddingRequest request = new CohereEmbeddingRequest( List.of("I like to eat apples", "I like to eat oranges"), CohereEmbeddingRequest.InputType.SEARCH_DOCUMENT, CohereEmbeddingRequest.Truncate.NONE); CohereEmbeddingResponse response = api.embedding(request); assertThat(response).isNotNull(); assertThat(response.texts()).isEqualTo(request.texts()); assertThat(response.embeddings()).hasSize(2); assertThat(response.embeddings().get(0)).hasSize(1024); } }
[ "org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id" ]
[((1642, 1696), 'org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id'), ((1750, 1771), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vertexai.gemini; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; 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 VertexAiGeminiAutoConfigurationIT { private static final Log logger = LogFactory.getLog(VertexAiGeminiAutoConfigurationIT.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"), "spring.ai.vertex.ai.gemini.chat.options.model=" + VertexAiGeminiChatClient.ChatModel.GEMINI_PRO_VISION.getValue()) .withConfiguration(AutoConfigurations.of(VertexAiGeminiAutoConfiguration.class)); @Test void generate() { contextRunner.run(context -> { VertexAiGeminiChatClient client = context.getBean(VertexAiGeminiChatClient.class); String response = client.call("Hello"); assertThat(response).isNotEmpty(); logger.info("Response: " + response); }); } @Test void generateStreaming() { contextRunner.run(context -> { VertexAiGeminiChatClient client = context.getBean(VertexAiGeminiChatClient.class); Flux<ChatResponse> responseFlux = client.stream(new Prompt(new UserMessage("Hello"))); String response = responseFlux.collectList().block().stream().map(chatResponse -> { return chatResponse.getResults().get(0).getOutput().getContent(); }).collect(Collectors.joining()); assertThat(response).isNotEmpty(); logger.info("Response: " + response); }); } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO_VISION.getValue" ]
[((2039, 2102), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO_VISION.getValue')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.titan; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.AssistantMessage; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel; import org.springframework.ai.chat.Generation; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.ai.parser.ListOutputParser; import org.springframework.ai.parser.MapOutputParser; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.io.Resource; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") class BedrockTitanChatClientIT { @Autowired private BedrockTitanChatClient client; @Value("classpath:/prompts/system-message.st") private Resource systemResource; @Test void roleTest() { String request = "Tell me about 3 famous pirates from the Golden Age of Piracy and why they did."; String name = "Bob"; String voice = "pirate"; UserMessage userMessage = new UserMessage(request); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource); Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice)); Prompt prompt = new Prompt(List.of(userMessage, systemMessage)); ChatResponse response = client.call(prompt); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void outputParser() { DefaultConversionService conversionService = new DefaultConversionService(); ListOutputParser outputParser = new ListOutputParser(conversionService); String format = outputParser.getFormat(); String template = """ List five {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "ice cream flavors.", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = this.client.call(prompt).getResult(); List<String> list = outputParser.parse(generation.getOutput().getContent()); assertThat(list).hasSize(5); } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void mapOutputParser() { MapOutputParser outputParser = new MapOutputParser(); String format = outputParser.getFormat(); String template = """ Remove Markdown code blocks from the output. Provide me a List of {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); Map<String, Object> result = outputParser.parse(generation.getOutput().getContent()); assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); } record ActorsFilmsRecord(String actor, List<String> movies) { } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void beanOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove Markdown code blocks from the output. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent()); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void beanStreamOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove Markdown code blocks from the output. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); String generationTextFromStream = client.stream(prompt) .collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream); System.out.println(actorsFilms); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @SpringBootConfiguration public static class TestConfiguration { @Bean public TitanChatBedrockApi titanApi() { return new TitanChatBedrockApi(TitanChatModel.TITAN_TEXT_EXPRESS_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); } @Bean public BedrockTitanChatClient titanChatClient(TitanChatBedrockApi titanApi) { return new BedrockTitanChatClient(titanApi); } } }
[ "org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id" ]
[((6965, 7006), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id'), ((7062, 7083), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.cohere; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.LogitBias; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.ReturnLikelihoods; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.Truncate; import org.springframework.ai.chat.prompt.Prompt; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class BedrockCohereChatCreateRequestTests { private CohereChatBedrockApi chatApi = new CohereChatBedrockApi(CohereChatModel.COHERE_COMMAND_V14.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); @Test public void createRequestWithChatOptions() { var client = new BedrockCohereChatClient(chatApi, BedrockCohereChatOptions.builder() .withTemperature(66.6f) .withTopK(66) .withTopP(0.66f) .withMaxTokens(678) .withStopSequences(List.of("stop1", "stop2")) .withReturnLikelihoods(ReturnLikelihoods.ALL) .withNumGenerations(3) .withLogitBias(new LogitBias("t", 6.6f)) .withTruncate(Truncate.END) .build()); CohereChatRequest request = client.createRequest(new Prompt("Test message content"), true); assertThat(request.prompt()).isNotEmpty(); assertThat(request.stream()).isTrue(); assertThat(request.temperature()).isEqualTo(66.6f); assertThat(request.topK()).isEqualTo(66); assertThat(request.topP()).isEqualTo(0.66f); assertThat(request.maxTokens()).isEqualTo(678); assertThat(request.stopSequences()).containsExactly("stop1", "stop2"); assertThat(request.returnLikelihoods()).isEqualTo(ReturnLikelihoods.ALL); assertThat(request.numGenerations()).isEqualTo(3); assertThat(request.logitBias()).isEqualTo(new LogitBias("t", 6.6f)); assertThat(request.truncate()).isEqualTo(Truncate.END); request = client.createRequest(new Prompt("Test message content", BedrockCohereChatOptions.builder() .withTemperature(99.9f) .withTopK(99) .withTopP(0.99f) .withMaxTokens(888) .withStopSequences(List.of("stop3", "stop4")) .withReturnLikelihoods(ReturnLikelihoods.GENERATION) .withNumGenerations(13) .withLogitBias(new LogitBias("t", 9.9f)) .withTruncate(Truncate.START) .build()), false ); assertThat(request.prompt()).isNotEmpty(); assertThat(request.stream()).isFalse(); assertThat(request.temperature()).isEqualTo(99.9f); assertThat(request.topK()).isEqualTo(99); assertThat(request.topP()).isEqualTo(0.99f); assertThat(request.maxTokens()).isEqualTo(888); assertThat(request.stopSequences()).containsExactly("stop3", "stop4"); assertThat(request.returnLikelihoods()).isEqualTo(ReturnLikelihoods.GENERATION); assertThat(request.numGenerations()).isEqualTo(13); assertThat(request.logitBias()).isEqualTo(new LogitBias("t", 9.9f)); assertThat(request.truncate()).isEqualTo(Truncate.START); } }
[ "org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id" ]
[((1726, 1765), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id'), ((1819, 1840), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.ollama; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.ai.chat.prompt.ChatOptionsBuilder; import org.springframework.ai.chat.messages.AssistantMessage; import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; 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.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.convert.support.DefaultConversionService; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @Testcontainers @Disabled("For manual smoke testing only.") class OllamaChatClientIT { private static String MODEL = "mistral"; private static final Log logger = LogFactory.getLog(OllamaChatClientIT.class); @Container static GenericContainer<?> ollamaContainer = new GenericContainer<>("ollama/ollama:0.1.23").withExposedPorts(11434); static String baseUrl; @BeforeAll public static void beforeAll() throws IOException, InterruptedException { logger.info("Start pulling the '" + MODEL + " ' generative ... would take several minutes ..."); ollamaContainer.execInContainer("ollama", "pull", MODEL); logger.info(MODEL + " pulling competed!"); baseUrl = "http://" + ollamaContainer.getHost() + ":" + ollamaContainer.getMappedPort(11434); } @Autowired private OllamaChatClient client; @Test void roleTest() { 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")); UserMessage userMessage = new UserMessage("Tell me about 5 famous pirates from the Golden Age of Piracy."); // portable/generic options var portableOptions = ChatOptionsBuilder.builder().withTemperature(0.7f).build(); Prompt prompt = new Prompt(List.of(userMessage, systemMessage), portableOptions); ChatResponse response = client.call(prompt); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); // ollama specific options var ollamaOptions = new OllamaOptions().withLowVRAM(true); response = client.call(new Prompt(List.of(userMessage, systemMessage), ollamaOptions)); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); } @Test void outputParser() { DefaultConversionService conversionService = new DefaultConversionService(); ListOutputParser outputParser = new ListOutputParser(conversionService); String format = outputParser.getFormat(); String template = """ List five {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "ice cream flavors.", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = this.client.call(prompt).getResult(); List<String> list = outputParser.parse(generation.getOutput().getContent()); assertThat(list).hasSize(5); } @Test void mapOutputParser() { MapOutputParser outputParser = new MapOutputParser(); String format = outputParser.getFormat(); String template = """ Remove Markdown code blocks from the output. Provide me a List of {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); Map<String, Object> result = outputParser.parse(generation.getOutput().getContent()); assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); } record ActorsFilmsRecord(String actor, List<String> movies) { } @Test void beanOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent()); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Test void beanStreamOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove Markdown code blocks from the output. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); String generationTextFromStream = client.stream(prompt) .collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @SpringBootConfiguration public static class TestConfiguration { @Bean public OllamaApi ollamaApi() { return new OllamaApi(baseUrl); } @Bean public OllamaChatClient ollamaChat(OllamaApi ollamaApi) { return new OllamaChatClient(ollamaApi).withModel(MODEL) .withDefaultOptions(OllamaOptions.create().withModel(MODEL).withTemperature(0.9f)); } } }
[ "org.springframework.ai.ollama.api.OllamaOptions.create", "org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder" ]
[((3672, 3730), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((3672, 3722), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((7650, 7711), 'org.springframework.ai.ollama.api.OllamaOptions.create'), ((7650, 7689), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.mistralai; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletion; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionChunk; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionFinishReason; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.Role; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest; import org.springframework.ai.mistralai.api.MistralAiApi.Embedding; import org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingList; import org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingRequest; import org.springframework.ai.retry.RetryUtils; import org.springframework.ai.retry.TransientAiException; import org.springframework.http.ResponseEntity; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; import org.springframework.retry.support.RetryTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; /** * @author Christian Tzolov */ @SuppressWarnings("unchecked") @ExtendWith(MockitoExtension.class) public class MistralAiRetryTests { private class TestRetryListener implements RetryListener { int onErrorRetryCount = 0; int onSuccessRetryCount = 0; @Override public <T, E extends Throwable> void onSuccess(RetryContext context, RetryCallback<T, E> callback, T result) { onSuccessRetryCount = context.getRetryCount(); } @Override public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) { onErrorRetryCount = context.getRetryCount(); } } private TestRetryListener retryListener; private RetryTemplate retryTemplate; private @Mock MistralAiApi mistralAiApi; private MistralAiChatClient chatClient; private MistralAiEmbeddingClient embeddingClient; @BeforeEach public void beforeEach() { retryTemplate = RetryUtils.DEFAULT_RETRY_TEMPLATE; retryListener = new TestRetryListener(); retryTemplate.registerListener(retryListener); chatClient = new MistralAiChatClient(mistralAiApi, MistralAiChatOptions.builder() .withTemperature(0.7f) .withTopP(1f) .withSafePrompt(false) .withModel(MistralAiApi.ChatModel.TINY.getValue()) .build(), null, retryTemplate); embeddingClient = new MistralAiEmbeddingClient(mistralAiApi, MetadataMode.EMBED, MistralAiEmbeddingOptions.builder().withModel(MistralAiApi.EmbeddingModel.EMBED.getValue()).build(), retryTemplate); } @Test public void mistralAiChatTransientError() { var choice = new ChatCompletion.Choice(0, new ChatCompletionMessage("Response", Role.ASSISTANT), ChatCompletionFinishReason.STOP); ChatCompletion expectedChatCompletion = new ChatCompletion("id", "chat.completion", 789l, "model", List.of(choice), new MistralAiApi.Usage(10, 10, 10)); when(mistralAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedChatCompletion))); var result = chatClient.call(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void mistralAiChatNonTransientError() { when(mistralAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.call(new Prompt("text"))); } @Test public void mistralAiChatStreamTransientError() { var choice = new ChatCompletionChunk.ChunkChoice(0, new ChatCompletionMessage("Response", Role.ASSISTANT), ChatCompletionFinishReason.STOP); ChatCompletionChunk expectedChatCompletion = new ChatCompletionChunk("id", "chat.completion.chunk", 789l, "model", List.of(choice)); when(mistralAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(Flux.just(expectedChatCompletion)); var result = chatClient.stream(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.collectList().block().get(0).getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void mistralAiChatStreamNonTransientError() { when(mistralAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.stream(new Prompt("text"))); } @Test public void mistralAiEmbeddingTransientError() { EmbeddingList<Embedding> expectedEmbeddings = new EmbeddingList<>("list", List.of(new Embedding(0, List.of(9.9, 8.8))), "model", new MistralAiApi.Usage(10, 10, 10)); when(mistralAiApi.embeddings(isA(EmbeddingRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedEmbeddings))); var result = embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null)); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput()).isEqualTo(List.of(9.9, 8.8)); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void mistralAiEmbeddingNonTransientError() { when(mistralAiApi.embeddings(isA(EmbeddingRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null))); } }
[ "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue", "org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue" ]
[((3594, 3632), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue'), ((3808, 3852), 'org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.openai.tool; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration; import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".*") public class FunctionCallbackInPromptIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallbackInPromptIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.openai.apiKey=" + System.getenv("OPENAI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, OpenAiAutoConfiguration.class)); @Test void functionCallTest() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); var promptOptions = OpenAiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("CurrentWeatherService") .withDescription("Get the weather in location") .withResponseConverter((response) -> "" + response.temp() + response.unit()) .build())) .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30.0", "10.0", "15.0"); }); } @Test void streamingFunctionCallTest() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); var promptOptions = OpenAiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("CurrentWeatherService") .withDescription("Get the weather in location") .withResponseConverter((response) -> "" + response.temp() + response.unit()) .build())) .build(); Flux<ChatResponse> response = chatClient.stream(new Prompt(List.of(userMessage), promptOptions)); String content = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", content); assertThat(content).containsAnyOf("30.0", "30"); assertThat(content).containsAnyOf("10.0", "10"); assertThat(content).containsAnyOf("15.0", "15"); }); } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder" ]
[((2715, 3039), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2715, 3026), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2778, 3024), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2778, 3010), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2778, 2928), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2778, 2875), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3648, 3972), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3648, 3959), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3711, 3957), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3711, 3943), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3711, 3861), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3711, 3808), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.mistralai.tool; import java.util.List; import java.util.Map; import java.util.function.Function; import com.fasterxml.jackson.annotation.JsonProperty; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.mistralai.MistralAiAutoConfiguration; import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.mistralai.MistralAiChatClient; import org.springframework.ai.mistralai.MistralAiChatOptions; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".*") public class PaymentStatusPromptIT { private final Logger logger = LoggerFactory.getLogger(WeatherServicePromptIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.mistralai.apiKey=" + System.getenv("MISTRAL_AI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, MistralAiAutoConfiguration.class)); public record Transaction(@JsonProperty(required = true, value = "transaction_id") String id) { } public record Status(@JsonProperty(required = true, value = "status") String status) { } record StatusDate(String status, String date) { } // Assuming we have the following payment data. public static final Map<Transaction, StatusDate> DATA = Map.of(new Transaction("T1001"), new StatusDate("Paid", "2021-10-05"), new Transaction("T1002"), new StatusDate("Unpaid", "2021-10-06"), new Transaction("T1003"), new StatusDate("Paid", "2021-10-07"), new Transaction("T1004"), new StatusDate("Paid", "2021-10-05"), new Transaction("T1005"), new StatusDate("Pending", "2021-10-08")); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.mistralai.chat.options.model=" + MistralAiApi.ChatModel.SMALL.getValue()) .run(context -> { MistralAiChatClient chatClient = context.getBean(MistralAiChatClient.class); UserMessage userMessage = new UserMessage("What's the status of my transaction with id T1001?"); var promptOptions = MistralAiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new Function<Transaction, Status>() { public Status apply(Transaction transaction) { return new Status(DATA.get(transaction).status()); } }) .withName("retrievePaymentStatus") .withDescription("Get payment status of a transaction") .build())) .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("T1001"); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("paid"); }); } }
[ "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue", "org.springframework.ai.mistralai.MistralAiChatOptions.builder" ]
[((3188, 3227), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.SMALL.getValue'), ((3459, 3856), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((3459, 3842), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((3526, 3840), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3526, 3825), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3526, 3763), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.jurassic2.api; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatRequest; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatResponse; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class Ai21Jurassic2ChatBedrockApiIT { Ai21Jurassic2ChatBedrockApi api = new Ai21Jurassic2ChatBedrockApi(Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id(), Region.US_EAST_1.id()); @Test public void chatCompletion() { Ai21Jurassic2ChatRequest request = new Ai21Jurassic2ChatRequest("Give me the names of 3 famous pirates?", 0.9f, 0.9f, 100, null, // List.of("END"), new Ai21Jurassic2ChatRequest.IntegerScalePenalty(1, true, true, true, true, true), new Ai21Jurassic2ChatRequest.FloatScalePenalty(0.5f, true, true, true, true, true), new Ai21Jurassic2ChatRequest.IntegerScalePenalty(1, true, true, true, true, true)); Ai21Jurassic2ChatResponse response = api.chatCompletion(request); assertThat(response).isNotNull(); assertThat(response.completions()).isNotEmpty(); assertThat(response.amazonBedrockInvocationMetrics()).isNull(); String responseContent = response.completions() .stream() .map(c -> c.data().text()) .collect(Collectors.joining(System.lineSeparator())); assertThat(responseContent).contains("Blackbeard"); } // Note: Ai21Jurassic2 doesn't support streaming yet! }
[ "org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id" ]
[((1542, 1586), 'org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatModel.AI21_J2_ULTRA_V1.id'), ((1591, 1612), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.azure.tool; import java.util.List; import java.util.function.Function; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.azure.openai.AzureOpenAiAutoConfiguration; import org.springframework.ai.azure.openai.AzureOpenAiChatClient; import org.springframework.ai.azure.openai.AzureOpenAiChatOptions; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+") @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+") class FunctionCallWithFunctionBeanIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withPropertyValues( // @formatter:off "spring.ai.azure.openai.api-key=" + System.getenv("AZURE_OPENAI_API_KEY"), "spring.ai.azure.openai.endpoint=" + System.getenv("AZURE_OPENAI_ENDPOINT")) // @formatter:onn .withConfiguration(AutoConfigurations.of(AzureOpenAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner.withPropertyValues("spring.ai.azure.openai.chat.options.model=gpt-4-0125-preview") .run(context -> { ChatClient chatClient = context.getBean(AzureOpenAiChatClient.class); UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, Paris and in Tokyo? Use Multi-turn function calling."); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), AzureOpenAiChatOptions.builder().withFunction("weatherFunction").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); response = chatClient.call(new Prompt(List.of(userMessage), AzureOpenAiChatOptions.builder().withFunction("weatherFunction3").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } @Configuration static class Config { @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction() { return new MockWeatherService(); } // Relies on the Request's JsonClassDescription annotation to provide the // function description. @Bean public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction3() { MockWeatherService weatherService = new MockWeatherService(); return (weatherService::apply); } } }
[ "org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder" ]
[((2882, 2954), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2882, 2946), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3164, 3237), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3164, 3229), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.vertexai.palm2; import org.junit.jupiter.api.Test; import org.springframework.ai.chat.prompt.ChatOptions; import org.springframework.ai.chat.prompt.ChatOptionsBuilder; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.vertexai.palm2.api.VertexAiPaLm2Api; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class VertexAiPaLm2ChatRequestTests { VertexAiPaLm2ChatClient client = new VertexAiPaLm2ChatClient(new VertexAiPaLm2Api("bla")); @Test public void createRequestWithDefaultOptions() { var request = client.createRequest(new Prompt("Test message content")); assertThat(request.prompt().messages()).hasSize(1); assertThat(request.candidateCount()).isEqualTo(1); assertThat(request.temperature()).isEqualTo(0.7f); assertThat(request.topK()).isEqualTo(20); assertThat(request.topP()).isNull(); } @Test public void createRequestWithPromptVertexAiOptions() { // Runtime options should override the default options. VertexAiPaLm2ChatOptions promptOptions = VertexAiPaLm2ChatOptions.builder() .withTemperature(0.8f) .withTopP(0.5f) .withTopK(99) // .withCandidateCount(2) .build(); var request = client.createRequest(new Prompt("Test message content", promptOptions)); assertThat(request.prompt().messages()).hasSize(1); assertThat(request.candidateCount()).isEqualTo(1); assertThat(request.temperature()).isEqualTo(0.8f); assertThat(request.topK()).isEqualTo(99); assertThat(request.topP()).isEqualTo(0.5f); } @Test public void createRequestWithPromptPortableChatOptions() { // runtime options. ChatOptions portablePromptOptions = ChatOptionsBuilder.builder() .withTemperature(0.9f) .withTopK(100) .withTopP(0.6f) .build(); var request = client.createRequest(new Prompt("Test message content", portablePromptOptions)); assertThat(request.prompt().messages()).hasSize(1); assertThat(request.candidateCount()).isEqualTo(1); assertThat(request.temperature()).isEqualTo(0.9f); assertThat(request.topK()).isEqualTo(100); assertThat(request.topP()).isEqualTo(0.6f); } }
[ "org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder" ]
[((2330, 2433), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2330, 2421), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2330, 2402), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((2330, 2384), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder')]
package org.springframework.ai.aot.test.openai; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonClassDescription; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.OpenAiEmbeddingClient; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Description; import org.springframework.context.annotation.ImportRuntimeHints; @SpringBootApplication @ImportRuntimeHints(OpenaiAotDemoApplication.MockWeatherServiceRuntimeHints.class) public class OpenaiAotDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(OpenaiAotDemoApplication.class) .web(WebApplicationType.NONE) .run(args); } @Bean ApplicationRunner applicationRunner(OpenAiChatClient chatClient, OpenAiEmbeddingClient embeddingClient) { return args -> { System.out.println("ChatClient: " + chatClient.getClass().getName()); System.out.println("EmbeddingClient: " + embeddingClient.getClass().getName()); // Synchronous Chat Client String response = chatClient.call("Tell me a joke."); System.out.println("SYNC RESPONSE: " + response); // Streaming Chat Client Flux<ChatResponse> flux = chatClient.stream(new Prompt("Tell me a joke.")); String fluxResponse = flux.collectList().block().stream().map(r -> r.getResult().getOutput().getContent()) .collect(Collectors.joining()); System.out.println("ASYNC RESPONSE: " + fluxResponse); // Embedding Client List<List<Double>> embeddings = embeddingClient.embed(List.of("Hello", "World")); System.out.println("EMBEDDINGS SIZE: " + embeddings.size()); // Function calling ChatResponse weatherResponse = chatClient.call(new Prompt("What is the weather in Amsterdam, Netherlands?", OpenAiChatOptions.builder().withFunction("weatherInfo").build())); System.out.println("WEATHER RESPONSE: " + weatherResponse.getResult().getOutput().getContent()); }; } @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherInfo() { return new MockWeatherService(); } public static class MockWeatherService implements Function<MockWeatherService.Request, MockWeatherService.Response> { @JsonInclude(Include.NON_NULL) @JsonClassDescription("Weather API request") public record Request( @JsonProperty(required = true, value = "location") @JsonPropertyDescription("The city and state e.g. San Francisco, CA") String location, @JsonProperty(required = true, value = "lat") @JsonPropertyDescription("The city latitude") double lat, @JsonProperty(required = true, value = "lon") @JsonPropertyDescription("The city longitude") double lon, @JsonProperty(required = true, value = "unit") @JsonPropertyDescription("Temperature unit") Unit unit) { } public enum Unit { C, F; } @JsonInclude(Include.NON_NULL) public record Response(double temperature, double feels_like, double temp_min, double temp_max, int pressure, int humidity, Unit unit) { } @Override public Response apply(Request request) { System.out.println("Weather request: " + request); return new Response(11, 15, 20, 2, 53, 45, Unit.C); } } public static class MockWeatherServiceRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { // Register method for reflection var mcs = MemberCategory.values(); hints.reflection().registerType(MockWeatherService.Request.class, mcs); hints.reflection().registerType(MockWeatherService.Response.class, mcs); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((2890, 2953), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2890, 2945), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.audio.speech; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.openai.OpenAiAudioSpeechOptions; import org.springframework.ai.openai.OpenAiTestConfiguration; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.metadata.audio.OpenAiAudioSpeechResponseMetadata; import org.springframework.ai.openai.testutils.AbstractIT; import org.springframework.boot.test.context.SpringBootTest; import reactor.core.publisher.Flux; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = OpenAiTestConfiguration.class) @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") class OpenAiSpeechClientIT extends AbstractIT { private static final Float SPEED = 1.0f; @Test void shouldSuccessfullyStreamAudioBytesForEmptyMessage() { Flux<byte[]> response = openAiAudioSpeechClient .stream("Today is a wonderful day to build something people love!"); assertThat(response).isNotNull(); assertThat(response.collectList().block()).isNotNull(); System.out.println(response.collectList().block()); } @Test void shouldProduceAudioBytesDirectlyFromMessage() { byte[] audioBytes = openAiAudioSpeechClient.call("Today is a wonderful day to build something people love!"); assertThat(audioBytes).hasSizeGreaterThan(0); } @Test void shouldGenerateNonEmptyMp3AudioFromSpeechPrompt() { OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .withModel(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); SpeechPrompt speechPrompt = new SpeechPrompt("Today is a wonderful day to build something people love!", speechOptions); SpeechResponse response = openAiAudioSpeechClient.call(speechPrompt); byte[] audioBytes = response.getResult().getOutput(); assertThat(response.getResults()).hasSize(1); assertThat(response.getResults().get(0).getOutput()).isNotEmpty(); assertThat(audioBytes).hasSizeGreaterThan(0); } @Test void speechRateLimitTest() { OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .withModel(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); SpeechPrompt speechPrompt = new SpeechPrompt("Today is a wonderful day to build something people love!", speechOptions); SpeechResponse response = openAiAudioSpeechClient.call(speechPrompt); OpenAiAudioSpeechResponseMetadata metadata = response.getMetadata(); assertThat(metadata).isNotNull(); assertThat(metadata.getRateLimit()).isNotNull(); assertThat(metadata.getRateLimit().getRequestsLimit()).isPositive(); assertThat(metadata.getRateLimit().getRequestsLimit()).isPositive(); } @Test void shouldStreamNonEmptyResponsesForValidSpeechPrompts() { OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .withModel(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); SpeechPrompt speechPrompt = new SpeechPrompt("Today is a wonderful day to build something people love!", speechOptions); Flux<SpeechResponse> responseFlux = openAiAudioSpeechClient.stream(speechPrompt); assertThat(responseFlux).isNotNull(); List<SpeechResponse> responses = responseFlux.collectList().block(); assertThat(responses).isNotNull(); responses.forEach(response -> { System.out.println("Audio data chunk size: " + response.getResult().getOutput().length); assertThat(response.getResult().getOutput()).isNotEmpty(); }); } }
[ "org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder" ]
[((2180, 2431), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2419), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2368), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2291), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2180, 2270), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3189), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3177), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3126), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3049), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2938, 3028), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 4058), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 4046), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 3995), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 3918), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3807, 3897), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.titan; 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.autoconfigure.bedrock.BedrockAwsConnectionProperties; import org.springframework.ai.bedrock.titan.BedrockTitanEmbeddingClient; import org.springframework.ai.bedrock.titan.BedrockTitanEmbeddingClient.InputType; import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.core.io.DefaultResourceLoader; 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 BedrockTitanEmbeddingAutoConfigurationIT { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.titan.embedding.enabled=true", "spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"), "spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"), "spring.ai.bedrock.aws.region=" + Region.US_EAST_1.id(), "spring.ai.bedrock.titan.embedding.model=" + TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id()) .withConfiguration(AutoConfigurations.of(BedrockTitanEmbeddingAutoConfiguration.class)); @Test public void singleTextEmbedding() { contextRunner.withPropertyValues("spring.ai.bedrock.titan.embedding.inputType=TEXT").run(context -> { BedrockTitanEmbeddingClient embeddingClient = context.getBean(BedrockTitanEmbeddingClient.class); assertThat(embeddingClient).isNotNull(); EmbeddingResponse embeddingResponse = embeddingClient.embedForResponse(List.of("Hello World")); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty(); assertThat(embeddingClient.dimensions()).isEqualTo(1024); }); } @Test public void singleImageEmbedding() { contextRunner.withPropertyValues("spring.ai.bedrock.titan.embedding.inputType=IMAGE").run(context -> { BedrockTitanEmbeddingClient embeddingClient = context.getBean(BedrockTitanEmbeddingClient.class); assertThat(embeddingClient).isNotNull(); byte[] image = new DefaultResourceLoader().getResource("classpath:/spring_framework.png") .getContentAsByteArray(); var base64Image = Base64.getEncoder().encodeToString(image); EmbeddingResponse embeddingResponse = embeddingClient.embedForResponse(List.of(base64Image)); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty(); assertThat(embeddingClient.dimensions()).isEqualTo(1024); }); } @Test public void propertiesTest() { new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.titan.embedding.enabled=true", "spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY", "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), "spring.ai.bedrock.titan.embedding.model=MODEL_XYZ", "spring.ai.bedrock.titan.embedding.inputType=TEXT") .withConfiguration(AutoConfigurations.of(BedrockTitanEmbeddingAutoConfiguration.class)) .run(context -> { var properties = context.getBean(BedrockTitanEmbeddingProperties.class); var awsProperties = context.getBean(BedrockAwsConnectionProperties.class); assertThat(properties.isEnabled()).isTrue(); assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id()); assertThat(properties.getModel()).isEqualTo("MODEL_XYZ"); assertThat(properties.getInputType()).isEqualTo(InputType.TEXT); assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY"); assertThat(awsProperties.getSecretKey()).isEqualTo("SECRET_KEY"); }); } @Test public void embeddingDisabled() { // It is disabled by default new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BedrockTitanEmbeddingAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockTitanEmbeddingProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockTitanEmbeddingClient.class)).isEmpty(); }); // Explicitly enable the embedding auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.titan.embedding.enabled=true") .withConfiguration(AutoConfigurations.of(BedrockTitanEmbeddingAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockTitanEmbeddingProperties.class)).isNotEmpty(); assertThat(context.getBeansOfType(BedrockTitanEmbeddingClient.class)).isNotEmpty(); }); // Explicitly disable the embedding auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.titan.embedding.enabled=false") .withConfiguration(AutoConfigurations.of(BedrockTitanEmbeddingAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockTitanEmbeddingProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockTitanEmbeddingClient.class)).isEmpty(); }); } }
[ "org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id" ]
[((2155, 2176), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2227, 2272), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id'), ((3407, 3448), 'java.util.Base64.getEncoder'), ((4035, 4059), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((4540, 4564), '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.testcontainers.service.connection.weaviate; import org.junit.jupiter.api.Test; import org.springframework.ai.autoconfigure.vectorstore.weaviate.WeaviateVectorStoreAutoConfiguration; import org.springframework.ai.autoconfigure.vectorstore.weaviate.WeaviateVectorStoreProperties; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.ai.vectorstore.WeaviateVectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.weaviate.WeaviateContainer; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @SpringJUnitConfig @Testcontainers @TestPropertySource(properties = { "spring.ai.vectorstore.weaviate.filter-field.country=TEXT", "spring.ai.vectorstore.weaviate.filter-field.year=NUMBER", "spring.ai.vectorstore.weaviate.filter-field.active=BOOLEAN", "spring.ai.vectorstore.weaviate.filter-field.price=NUMBER" }) class WeaviateContainerConnectionDetailsFactoryTest { @Container @ServiceConnection static WeaviateContainer weaviateContainer = new WeaviateContainer("semitechnologies/weaviate:1.22.4"); @Autowired private WeaviateVectorStoreProperties properties; @Autowired private VectorStore vectorStore; @Test public void addAndSearchWithFilters() { assertThat(properties.getFilterField()).hasSize(4); assertThat(properties.getFilterField().get("country")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.TEXT); assertThat(properties.getFilterField().get("year")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.NUMBER); assertThat(properties.getFilterField().get("active")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.BOOLEAN); assertThat(properties.getFilterField().get("price")) .isEqualTo(WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField.Type.NUMBER); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Bulgaria", "price", 3.14, "active", true, "year", 2020)); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Netherlands", "price", 1.57, "active", false, "year", 2023)); vectorStore.add(List.of(bgDocument, nlDocument)); var request = SearchRequest.query("The World").withTopK(5); List<Document> results = vectorStore.similaritySearch(request); assertThat(results).hasSize(2); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("country == 'Bulgaria'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("country == 'Netherlands'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("price > 1.57 && active == true")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("year in [2020, 2023]")); assertThat(results).hasSize(2); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("year > 2020 && year <= 2023")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); // Remove all documents from the store vectorStore.delete(List.of(bgDocument, nlDocument).stream().map(doc -> doc.getId()).toList()); } @Configuration(proxyBeanMethods = false) @ImportAutoConfiguration(WeaviateVectorStoreAutoConfiguration.class) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3730, 3774), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5055, 5128), 'java.util.List.of'), ((5055, 5119), 'java.util.List.of'), ((5055, 5095), 'java.util.List.of')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.mistralai.tool; import java.util.List; import java.util.function.Function; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; 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.mistralai.tool.WeatherServicePromptIT.MyWeatherService.Request; import org.springframework.ai.autoconfigure.mistralai.tool.WeatherServicePromptIT.MyWeatherService.Response; import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.mistralai.MistralAiChatClient; import org.springframework.ai.mistralai.MistralAiChatOptions; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest.ToolChoice; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov * @since 0.8.1 */ @EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".*") public class WeatherServicePromptIT { private final Logger logger = LoggerFactory.getLogger(WeatherServicePromptIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.mistralai.api-key=" + System.getenv("MISTRAL_AI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, MistralAiAutoConfiguration.class)); @Test void promptFunctionCall() { contextRunner .withPropertyValues("spring.ai.mistralai.chat.options.model=" + MistralAiApi.ChatModel.LARGE.getValue()) .run(context -> { MistralAiChatClient chatClient = context.getBean(MistralAiChatClient.class); UserMessage userMessage = new UserMessage("What's the weather like in Paris?"); // UserMessage userMessage = new UserMessage("What's the weather like in // San Francisco, Tokyo, and // Paris?"); var promptOptions = MistralAiChatOptions.builder() .withToolChoice(ToolChoice.AUTO) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MyWeatherService()) .withName("CurrentWeatherService") .withDescription("Get the current weather in requested location") .build())) .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15", "15.0"); // assertThat(response.getResult().getOutput().getContent()).contains("30.0", // "10.0", "15.0"); }); } public static class MyWeatherService implements Function<Request, Response> { // @formatter:off public enum Unit { C, F } @JsonInclude(Include.NON_NULL) public record Request( @JsonProperty(required = true, value = "location") String location, @JsonProperty(required = true, value = "unit") Unit unit) {} public record Response(double temperature, Unit unit) {} // @formatter:on @Override public Response apply(Request request) { if (request.location().contains("Paris")) { return new Response(15, request.unit()); } else if (request.location().contains("Tokyo")) { return new Response(10, request.unit()); } else if (request.location().contains("San Francisco")) { return new Response(30, request.unit()); } throw new IllegalArgumentException("Invalid request: " + request); } } }
[ "org.springframework.ai.mistralai.MistralAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue" ]
[((2949, 2988), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue'), ((3330, 3634), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((3330, 3620), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((3330, 3398), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((3435, 3618), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3435, 3603), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3435, 3531), '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.vertexai.gemini.function; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.google.cloud.vertexai.VertexAI; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.ai.model.function.FunctionCallbackWrapper.Builder.SchemaType; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.TransportType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*") public class VertexAiGeminiChatClientFunctionCallingIT { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private VertexAiGeminiChatClient vertexGeminiClient; @AfterEach public void afterEach() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void functionCallExplicitOpenApiSchema() { UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, in Paris and in Tokyo, Japan? Use Multi-turn function calling. Provide answer for all requested locations."); List<Message> messages = new ArrayList<>(List.of(userMessage)); String openApiSchema = """ { "type": "OBJECT", "properties": { "location": { "type": "STRING", "description": "The city and state e.g. San Francisco, CA" }, "unit" : { "type" : "STRING", "enum" : [ "C", "F" ], "description" : "Temperature unit" } }, "required": ["location", "unit"] } """; var promptOptions = VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("getCurrentWeather") .withDescription("Get the current weather in a given location") .withInputTypeSchema(openApiSchema) .build())) .build(); ChatResponse response = vertexGeminiClient.call(new Prompt(messages, promptOptions)); logger.info("Response: {}", response); // System.out.println(response.getResult().getOutput().getContent()); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", "10"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15.0", "15"); } @Test public void functionCallTestInferredOpenApiSchema() { // UserMessage userMessage = new UserMessage("What's the weather like in San // Francisco, Paris and Tokyo?"); UserMessage userMessage = new UserMessage("What's the weather like in Paris?"); List<Message> messages = new ArrayList<>(List.of(userMessage)); var promptOptions = VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withSchemaType(SchemaType.OPEN_API_SCHEMA) .withName("getCurrentWeather") .withDescription("Get the current weather in a given location") .build())) .build(); ChatResponse response = vertexGeminiClient.call(new Prompt(messages, promptOptions)); logger.info("Response: {}", response); // System.out.println(response.getResult().getOutput().getContent()); // assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", // "30"); // assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", // "10"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15.0", "15"); } @Test public void functionCallTestInferredOpenApiSchemaStream() { UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, in Paris and in Tokyo? Use Multi-turn function calling."); List<Message> messages = new ArrayList<>(List.of(userMessage)); var promptOptions = VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withSchemaType(SchemaType.OPEN_API_SCHEMA) .withName("getCurrentWeather") .withDescription("Get the current weather in a given location") .build())) .build(); Flux<ChatResponse> response = vertexGeminiClient.stream(new Prompt(messages, promptOptions)); String responseString = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", responseString); assertThat(responseString).containsAnyOf("15.0", "15"); assertThat(responseString).containsAnyOf("30.0", "30"); assertThat(responseString).containsAnyOf("10.0", "10"); } @SpringBootConfiguration public static class TestConfiguration { @Bean public VertexAI vertexAiApi() { String projectId = System.getenv("VERTEX_AI_GEMINI_PROJECT_ID"); String location = System.getenv("VERTEX_AI_GEMINI_LOCATION"); return new VertexAI(projectId, location); } @Bean public VertexAiGeminiChatClient vertexAiEmbedding(VertexAI vertexAi) { return new VertexAiGeminiChatClient(vertexAi, VertexAiGeminiChatOptions.builder() .withModel(VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .withTemperature(0.9f) .withTransportType(TransportType.REST) .build()); } } }
[ "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder" ]
[((3304, 3673), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3304, 3661), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3304, 3411), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3354, 3410), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((3446, 3659), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3446, 3646), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3446, 3606), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3446, 3538), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4501, 4878), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4501, 4866), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4501, 4608), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4551, 4607), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((4643, 4864), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4643, 4851), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4643, 4783), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((4643, 4748), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5682, 6059), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5682, 6047), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5682, 5789), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5732, 5788), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((5824, 6045), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5824, 6032), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5824, 5964), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((5824, 5929), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7053, 7252), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7053, 7237), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7053, 7192), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7053, 7163), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((7106, 7162), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue')]
package com.kousenit.springaiexamples.rag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.reader.JsonReader; import org.springframework.ai.transformer.splitter.TextSplitter; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import java.io.File; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class RagService { private static final Logger logger = LoggerFactory.getLogger(RagService.class); @Value("classpath:/data/bikes.json") private Resource bikesResource; @Value("classpath:/prompts/system-qa.st") private Resource systemBikePrompt; private final ChatClient aiClient; private final EmbeddingClient embeddingClient; @Autowired public RagService(@Qualifier("openAiChatClient") ChatClient aiClient, @Qualifier("openAiEmbeddingClient") EmbeddingClient embeddingClient) { this.aiClient = aiClient; this.embeddingClient = embeddingClient; } public Generation retrieve(String message) { SimpleVectorStore vectorStore = new SimpleVectorStore(embeddingClient); File bikeVectorStore = new File("src/main/resources/data/bikeVectorStore.json"); if (bikeVectorStore.exists()) { vectorStore.load(bikeVectorStore); } else { // Step 1 - Load JSON document as Documents logger.info("Loading JSON as Documents"); JsonReader jsonReader = new JsonReader(bikesResource, "name", "price", "shortDescription", "description"); List<Document> documents = jsonReader.get(); logger.info("Loading JSON as Documents"); TextSplitter splitter = new TokenTextSplitter(); List<Document> splitDocuments = splitter.apply(documents); // Step 2 - Create embeddings and save to vector store logger.info("Creating Embeddings..."); vectorStore.add(splitDocuments); logger.info("Embeddings created."); vectorStore.save(bikeVectorStore); } // Step 3 retrieve related documents to query logger.info("Retrieving relevant documents"); List<Document> similarDocuments = vectorStore.similaritySearch( SearchRequest.query(message).withTopK(4)); logger.info(String.format("Found %s relevant documents.", similarDocuments.size())); // Step 4 Embed documents into SystemMessage with the `system-qa.st` prompt template Message systemMessage = getSystemMessage(similarDocuments); UserMessage userMessage = new UserMessage(message); // Step 5 - Ask the AI model logger.info("Asking AI model to reply to question."); Prompt prompt = new Prompt(List.of(systemMessage, userMessage)); logger.info(prompt.toString()); ChatResponse response = aiClient.call(prompt); logger.info("AI responded."); logger.info(response.getResult().toString()); return response.getResult(); } private Message getSystemMessage(List<Document> similarDocuments) { String documents = similarDocuments.stream() .map(Document::getContent) .collect(Collectors.joining("\n")); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemBikePrompt); return systemPromptTemplate.createMessage(Map.of("documents", documents)); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3128, 3168), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package habuma.springaiimagegen; import org.springframework.ai.image.ImageClient; import org.springframework.ai.image.ImageOptions; import org.springframework.ai.image.ImageOptionsBuilder; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @Controller public class ImageGenController { private final ImageClient imageClient; public ImageGenController(ImageClient imageClient) { this.imageClient = imageClient; } @PostMapping("/imagegen") public String imageGen(@RequestBody ImageGenRequest request) { ImageOptions options = ImageOptionsBuilder.builder() .withModel("dall-e-3") .build(); ImagePrompt imagePrompt = new ImagePrompt(request.prompt(), options); ImageResponse response = imageClient.call(imagePrompt); String imageUrl = response.getResult().getOutput().getUrl(); return "redirect:" + imageUrl; } }
[ "org.springframework.ai.image.ImageOptionsBuilder.builder" ]
[((784, 877), 'org.springframework.ai.image.ImageOptionsBuilder.builder'), ((784, 852), 'org.springframework.ai.image.ImageOptionsBuilder.builder')]
package org.example.springai.retriever; import java.util.List; import java.util.Objects; import java.util.Optional; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentRetriever; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; /** * spring-ai 에서 삭제된 클래스 들고옴 * 아래는 해당 커밋메시지 * b35c71061ed1560241a4e3708775cd703acf2553 */ public class VectorStoreRetriever implements DocumentRetriever { private VectorStore vectorStore; int k; Optional<Double> threshold = Optional.empty(); public VectorStoreRetriever(VectorStore vectorStore) { this(vectorStore, 4); } public VectorStoreRetriever(VectorStore vectorStore, int k) { Objects.requireNonNull(vectorStore, "VectorStore must not be null"); this.vectorStore = vectorStore; this.k = k; } public VectorStoreRetriever(VectorStore vectorStore, int k, double threshold) { Objects.requireNonNull(vectorStore, "VectorStore must not be null"); this.vectorStore = vectorStore; this.k = k; this.threshold = Optional.of(threshold); } public VectorStore getVectorStore() { return vectorStore; } public int getK() { return k; } public Optional<Double> getThreshold() { return threshold; } @Override public List<Document> retrieve(String query) { SearchRequest request = SearchRequest.query(query).withTopK(this.k); if (threshold.isPresent()) { request.withSimilarityThreshold(this.threshold.get()); } return this.vectorStore.similaritySearch(request); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1529, 1572), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package ai.ssudikon.springai; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.PagePdfDocumentReader; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @SpringBootApplication public class SpringAiExpApplication { public static void main(String[] args) { SpringApplication.run(SpringAiExpApplication.class, args); } @Component static class AlexPopeAiClient { private final VectorStore vectorStore; private final ChatClient chatClient; AlexPopeAiClient(VectorStore vectorStore, ChatClient chatClient) { this.vectorStore = vectorStore; this.chatClient = chatClient; } public String chat(String query) { var prompt = """ You're assisting with questions about alexander pope. Alexander Pope (1688–1744) was an English poet, translator, and satirist known for his significant contributions to 18th-century English literature. He is renowned for works like "The Rape of the Lock," "The Dunciad," and "An Essay on Criticism." Pope's writing style often featured satire and discursive poetry, and his translations of Homer were also notable. Use the information from the DOCUMENTS section to provide accurate answers but act as if you knew this information innately. If unsure, simply state that you don't know. DOCUMENTS: {documents} """; var listOfSimilarDocs = vectorStore.similaritySearch(query); var docs = listOfSimilarDocs.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator())); var systemMessage = new SystemPromptTemplate(prompt).createMessage(Map.of("documents", docs)); var userMessage = new UserMessage(query); var promptList = new Prompt(List.of(systemMessage, userMessage)); var aiResponse = chatClient.call(promptList); return aiResponse.getResult().getOutput().getContent(); } } @Bean ApplicationRunner applicationRunner(VectorStore vectorStore, @Value("file:/Users/sudikonda/Developer/Java/IdeaProjects/spring-ai-exp/src/main/resources/AlexanderPope-Wikipedia.pdf") Resource resource, JdbcTemplate jdbcTemplate, ChatClient chatClient, AlexPopeAiClient alexPopeAiClient) { return args -> { init(vectorStore, resource, jdbcTemplate); String chatResponse = alexPopeAiClient.chat("Who is Alexander Pope"); System.out.println("chatResponse = " + chatResponse); }; } private static void init(VectorStore vectorStore, Resource resource, JdbcTemplate jdbcTemplate) { jdbcTemplate.update("DELETE FROM vector_store"); PdfDocumentReaderConfig config = PdfDocumentReaderConfig.builder().withPageExtractedTextFormatter(new ExtractedTextFormatter.Builder().withNumberOfBottomTextLinesToDelete(3).withNumberOfTopPagesToSkipBeforeDelete(1).build()).withPagesPerDocument(1).build(); PagePdfDocumentReader pagePdfDocumentReader = new PagePdfDocumentReader(resource, config); TokenTextSplitter tokenTextSplitter = new TokenTextSplitter(); List<Document> docs = tokenTextSplitter.apply(pagePdfDocumentReader.get()); vectorStore.accept(docs); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder" ]
[((3902, 4125), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3902, 4117), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3902, 4093), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')]
package com.thehecklers.aiaiai00800; 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.*; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.Map; @RestController public class Ai080Controller { private final AzureOpenAiChatClient chatClient; private final List<Message> buffer = new ArrayList<>(); public Ai080Controller(AzureOpenAiChatClient chatClient) { this.chatClient = chatClient; } @GetMapping public ChatResponse generate(@RequestParam(defaultValue = "Tell me a joke") String message, @RequestParam(required = false) String celebrity) { List<Message> promptMessages = new ArrayList<>(buffer); // Add the user's message promptMessages.add(new ChatMessage(MessageType.USER, message)); if (null != celebrity) { // Add a system message to guide the AI's generation var sysTemplate = new SystemPromptTemplate("You respond in the style of {celebrity}."); Message sysMessage = sysTemplate.createMessage(Map.of("celebrity", celebrity)); promptMessages.add(sysMessage); } ChatResponse response = chatClient.call(new Prompt(promptMessages)); /* //Use this in cases where you wish/need to request multiple generations response.getResults().forEach(g -> { System.out.println(" Message Request: " + message); System.out.println(" Celebrity Voice: " + celebrity); System.out.println(" Content:"); System.out.println(" " + g.getOutput().getContent()); buffer.add(g.getOutput()); }); */ buffer.add(response.getResult().getOutput()); return response; } @GetMapping("/template") public String generateUsingTemplate(@RequestParam String typeOfRequest, @RequestParam String topicOfRequest) { PromptTemplate template = new PromptTemplate("Tell me a {type} about {topic}"); Prompt prompt = template.create(Map.of("type", typeOfRequest, "topic", topicOfRequest)); return chatClient.call(prompt).getResult().getOutput().getContent(); } @GetMapping("/weather") public AssistantMessage generateWeather(@RequestParam(defaultValue = "New York City") String location) { return chatClient.call(new Prompt(new UserMessage("What is the weather in " + location), AzureOpenAiChatOptions.builder() .withFunction("weatherFunction").build())) .getResult() .getOutput(); } @GetMapping("/about") public String generateAbout(@RequestParam(defaultValue = "What are some recommended activities?") String message, @RequestParam(defaultValue = "Chicago") String location) { var assistantMessage = generateWeather(location); PromptTemplate template = new PromptTemplate("{message} in {location}?"); Message userMessage = template.createMessage(Map.of("message", message, "location", location)); return chatClient.call(new Prompt(List.of(assistantMessage, userMessage))) .getResult() .getOutput() .getContent(); } }
[ "org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder" ]
[((2921, 3018), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2921, 3010), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder')]
package com.example.springaioutputparserdemo; import com.example.springaioutputparserdemo.entity.ActorsFilms; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.image.*; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class OutputParserController { @Autowired private ChatClient chatClient; @Autowired private ImageClient openAImageClient; @GetMapping("/ai/output") public ActorsFilms generate(@RequestParam(value = "actor", defaultValue = "Jeff Bridges") String actor) { var outputParser = new BeanOutputParser<>(ActorsFilms.class); String userMessage = """ Generate the filmography for the actor {actor}. {format} """; PromptTemplate promptTemplate = new PromptTemplate(userMessage, Map.of("actor", actor, "format", outputParser.getFormat() )); Prompt prompt = promptTemplate.create(); Generation generation = chatClient.call(prompt).getResult(); ActorsFilms actorsFilms = outputParser.parse(generation.getOutput().getContent()); return actorsFilms; } @GetMapping("/image") public Image getImage(){ ImageResponse response = openAImageClient.call( new ImagePrompt("Give me clear and HD image of a" + " football player on ground", OpenAiImageOptions.builder() .withQuality("hd") .withN(4) .withHeight(1024) .withWidth(1024).build()) ); //return response.getResult().getOutput().toString(); return response.getResult().getOutput(); } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((1895, 2115), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2107), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2060), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2012), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 1972), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
package com.thomasvitale.ai.spring; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Service class ChatService { private final ChatClient chatClient; private final SimpleVectorStore vectorStore; ChatService(ChatClient chatClient, SimpleVectorStore vectorStore) { this.chatClient = chatClient; this.vectorStore = vectorStore; } AssistantMessage chatWithDocument(String message) { var systemPromptTemplate = new SystemPromptTemplate(""" You're assisting with questions about products in a bicycle catalog. Answer questions given the context information below (DOCUMENTS section) and no prior knowledge, but act as if you knew this information innately. If the answer is not found in the DOCUMENTS section, simply state that you don't know the answer. DOCUMENTS: {documents} """); List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2)); String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator())); Map<String,Object> model = Map.of("documents", documents); var systemMessage = systemPromptTemplate.createMessage(model); var userMessage = new UserMessage(message); var prompt = new Prompt(List.of(systemMessage, userMessage)); var chatResponse = chatClient.call(prompt); return chatResponse.getResult().getOutput(); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1539, 1579), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package com.alok.ai.spring.ollama; import com.alok.ai.spring.model.Message; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/ollama/chat") @RestController public class OllamaChatController { private final OllamaApi ollamaApi; private final String model; private final OllamaApi.Message geographyTeacherRoleContextMessage = OllamaApi.Message.builder(OllamaApi.Message.Role.ASSISTANT) .withContent("You are geography teacher. You are talking to a student.") .build(); private final OllamaApi.Message historyTeacherRoleContextMessage = OllamaApi.Message.builder(OllamaApi.Message.Role.ASSISTANT) .withContent("You are history teacher. You are talking to a student.") .build(); @Autowired public OllamaChatController(OllamaApi ollamaApi, @Value("${spring.ai.ollama.chat.model}") String model) { this.ollamaApi = ollamaApi; this.model = model; } @PostMapping(value = "/teacher/geography") public ResponseEntity<OllamaApi.Message> chatWithGeographyTeacher( @RequestBody Message message ) { return ResponseEntity.ok(ollamaApi.chat(OllamaApi.ChatRequest.builder(model) .withStream(false) // not streaming .withMessages(List.of( geographyTeacherRoleContextMessage, OllamaApi.Message.builder(OllamaApi.Message.Role.USER) .withContent(message.question()) .build() ) ) .withOptions(OllamaOptions.create().withTemperature(0.9f)) .build()).message()); } @PostMapping(value = "/teacher/history") public ResponseEntity<OllamaApi.Message> chatWithHistoryTeacher( @RequestBody Message message ) { return ResponseEntity.ok(ollamaApi.chat(OllamaApi.ChatRequest.builder(model) .withStream(false) // not streaming .withMessages(List.of( historyTeacherRoleContextMessage, OllamaApi.Message.builder(OllamaApi.Message.Role.USER) .withContent(message.question()) .build() ) ) .withOptions(OllamaOptions.create().withTemperature(0.9f)) .build()).message()); } }
[ "org.springframework.ai.ollama.api.OllamaApi.Message.builder", "org.springframework.ai.ollama.api.OllamaOptions.create", "org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder" ]
[((661, 826), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((661, 805), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((661, 720), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 1063), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 1042), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 959), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1477, 1993), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1968), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1893), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1548), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1513), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1689, 1849), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1689, 1808), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1689, 1743), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1923, 1967), 'org.springframework.ai.ollama.api.OllamaOptions.create'), ((2225, 2771), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2746), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2671), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2296), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2261), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2451, 2627), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2451, 2578), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2451, 2505), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2701, 2745), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
package com.example.springaivectorsearchqueryjson.services; import org.springframework.ai.document.Document; import org.springframework.ai.reader.JsonMetadataGenerator; import org.springframework.ai.reader.JsonReader; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class VectorService { @Autowired VectorStore vectorStore; @Value("classpath:/data/bikes.json") Resource bikesResouce; public List<Document> queryJSONVector(String query){ // read json file JsonReader jsonReader = new JsonReader(bikesResouce, new ProductMetadataGenerator(), "name","shortDescription", "description", "price","tags"); // create document object List<Document> documents = jsonReader.get(); // add to vectorstore vectorStore.add(documents); // query vector search List<Document> results = vectorStore.similaritySearch( SearchRequest.defaults() .withQuery(query) .withTopK(1) ); return results ; } public class ProductMetadataGenerator implements JsonMetadataGenerator { @Override public Map<String, Object> generate(Map<String, Object> jsonMap) { return Map.of("name", jsonMap.get("name"), "shortDescription", jsonMap.get("shortDescription")); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.defaults" ]
[((1301, 1406), 'org.springframework.ai.vectorstore.SearchRequest.defaults'), ((1301, 1368), 'org.springframework.ai.vectorstore.SearchRequest.defaults')]
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.openai; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Profile("openai") @Configuration public class OpenAiClientConfig { @Value("${ai-client.openai.api-key}") private String openAiApiKey; @Value("${ai-client.openai.chat.model}") private String openAiModelName; @Value("#{T(Float).parseFloat('${ai-client.openai.chat.temperature}')}") private float openAiTemperature; @Value("${ai-client.openai.chat.max-tokens}") private int openAiMaxTokens; @Bean public OpenAiApi openAiChatApi() { return new OpenAiApi(openAiApiKey); } @Bean OpenAiChatClient openAiChatClient(OpenAiApi openAiApi) { return new OpenAiChatClient(openAiApi, OpenAiChatOptions.builder() .withModel(openAiModelName) .withTemperature(openAiTemperature) .withMaxTokens(openAiMaxTokens) .build()) ; } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((1124, 1352), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1319), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1263), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1203), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
package com.thomasvitale.ai.spring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import static org.springframework.ai.reader.pdf.PagePdfDocumentReader.*; @Service class ChatService { private static final Logger log = LoggerFactory.getLogger(ChatService.class); private final ChatClient chatClient; private final SimpleVectorStore vectorStore; ChatService(ChatClient chatClient, SimpleVectorStore vectorStore) { this.chatClient = chatClient; this.vectorStore = vectorStore; } AssistantMessage chatWithDocument(String message) { var systemPromptTemplate = new SystemPromptTemplate(""" Answer questions given the context information below (DOCUMENTS section) and no prior knowledge, but act as if you knew this information innately. If the answer is not found in the DOCUMENTS section, simply state that you don't know the answer. In the answer, include the source file name from which the context information is extracted from. DOCUMENTS: {documents} """); List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2)); logDocumentMetadata(similarDocuments); String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator())); Map<String,Object> model = Map.of("documents", documents); var systemMessage = systemPromptTemplate.createMessage(model); var userMessage = new UserMessage(message); var prompt = new Prompt(List.of(systemMessage, userMessage)); var chatResponse = chatClient.call(prompt); return chatResponse.getResult().getOutput(); } private void logDocumentMetadata(List<Document> documents) { log.info("Similar documents retrieved to answer your question:"); documents.forEach(document -> { var metadata = Map.of( "fileName", document.getMetadata().get(METADATA_FILE_NAME), "startPageNumber", document.getMetadata().get(METADATA_START_PAGE_NUMBER), "endPageNumber", Objects.requireNonNullElse(document.getMetadata().get(METADATA_END_PAGE_NUMBER), "-") ); log.info("Metadata: " + metadata); }); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1841, 1881), '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; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.StreamingChatClient; import org.springframework.ai.chat.metadata.ChatGenerationMetadata; import org.springframework.ai.chat.metadata.RateLimit; import org.springframework.ai.chat.prompt.ChatOptions; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.ai.model.function.AbstractFunctionCallSupport; import org.springframework.ai.model.function.FunctionCallbackContext; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletion; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletion.Choice; 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.ChatCompletionMessage.ToolCall; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionRequest; import org.springframework.ai.openai.metadata.OpenAiChatResponseMetadata; import org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor; import org.springframework.ai.retry.RetryUtils; import org.springframework.http.ResponseEntity; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * {@link ChatClient} and {@link StreamingChatClient} implementation for {@literal OpenAI} * backed by {@link OpenAiApi}. * * @author Mark Pollack * @author Christian Tzolov * @author Ueibin Kim * @author John Blum * @author Josh Long * @author Jemin Huh * @see ChatClient * @see StreamingChatClient * @see OpenAiApi */ public class OpenAiChatClient extends AbstractFunctionCallSupport<ChatCompletionMessage, OpenAiApi.ChatCompletionRequest, ResponseEntity<ChatCompletion>> implements ChatClient, StreamingChatClient { private static final Logger logger = LoggerFactory.getLogger(OpenAiChatClient.class); /** * The default options used for the chat completion requests. */ private OpenAiChatOptions defaultOptions; /** * The retry template used to retry the OpenAI API calls. */ public final RetryTemplate retryTemplate; /** * Low-level access to the OpenAI API. */ private final OpenAiApi openAiApi; /** * Creates an instance of the OpenAiChatClient. * @param openAiApi The OpenAiApi instance to be used for interacting with the OpenAI * Chat API. * @throws IllegalArgumentException if openAiApi is null */ public OpenAiChatClient(OpenAiApi openAiApi) { this(openAiApi, OpenAiChatOptions.builder().withModel(OpenAiApi.DEFAULT_CHAT_MODEL).withTemperature(0.7f).build()); } /** * Initializes an instance of the OpenAiChatClient. * @param openAiApi The OpenAiApi instance to be used for interacting with the OpenAI * Chat API. * @param options The OpenAiChatOptions to configure the chat client. */ public OpenAiChatClient(OpenAiApi openAiApi, OpenAiChatOptions options) { this(openAiApi, options, null, RetryUtils.DEFAULT_RETRY_TEMPLATE); } /** * Initializes a new instance of the OpenAiChatClient. * @param openAiApi The OpenAiApi instance to be used for interacting with the OpenAI * Chat API. * @param options The OpenAiChatOptions to configure the chat client. * @param functionCallbackContext The function callback context. * @param retryTemplate The retry template. */ public OpenAiChatClient(OpenAiApi openAiApi, OpenAiChatOptions options, FunctionCallbackContext functionCallbackContext, RetryTemplate retryTemplate) { super(functionCallbackContext); Assert.notNull(openAiApi, "OpenAiApi must not be null"); Assert.notNull(options, "Options must not be null"); Assert.notNull(retryTemplate, "RetryTemplate must not be null"); this.openAiApi = openAiApi; this.defaultOptions = options; this.retryTemplate = retryTemplate; } @Override public ChatResponse call(Prompt prompt) { ChatCompletionRequest request = createRequest(prompt, false); return this.retryTemplate.execute(ctx -> { ResponseEntity<ChatCompletion> completionEntity = this.callWithFunctionSupport(request); var chatCompletion = completionEntity.getBody(); if (chatCompletion == null) { logger.warn("No chat completion returned for prompt: {}", prompt); return new ChatResponse(List.of()); } RateLimit rateLimits = OpenAiResponseHeaderExtractor.extractAiResponseHeaders(completionEntity); List<Generation> generations = chatCompletion.choices().stream().map(choice -> { return new Generation(choice.message().content(), toMap(chatCompletion.id(), choice)) .withGenerationMetadata(ChatGenerationMetadata.from(choice.finishReason().name(), null)); }).toList(); return new ChatResponse(generations, OpenAiChatResponseMetadata.from(completionEntity.getBody()).withRateLimit(rateLimits)); }); } private Map<String, Object> toMap(String id, ChatCompletion.Choice choice) { Map<String, Object> map = new HashMap<>(); var message = choice.message(); if (message.role() != null) { map.put("role", message.role().name()); } if (choice.finishReason() != null) { map.put("finishReason", choice.finishReason().name()); } map.put("id", id); return map; } @Override public Flux<ChatResponse> stream(Prompt prompt) { ChatCompletionRequest request = createRequest(prompt, true); return this.retryTemplate.execute(ctx -> { Flux<OpenAiApi.ChatCompletionChunk> completionChunks = this.openAiApi.chatCompletionStream(request); // For chunked responses, only the first chunk contains the choice role. // The rest of the chunks with same ID share the same role. ConcurrentHashMap<String, String> roleMap = new ConcurrentHashMap<>(); // Convert the ChatCompletionChunk into a ChatCompletion to be able to reuse // the function call handling logic. return completionChunks.map(chunk -> chunkToChatCompletion(chunk)).map(chatCompletion -> { try { chatCompletion = handleFunctionCallOrReturn(request, ResponseEntity.of(Optional.of(chatCompletion))) .getBody(); @SuppressWarnings("null") String id = chatCompletion.id(); List<Generation> generations = chatCompletion.choices().stream().map(choice -> { if (choice.message().role() != null) { roleMap.putIfAbsent(id, choice.message().role().name()); } String finish = (choice.finishReason() != null ? choice.finishReason().name() : ""); var generation = new Generation(choice.message().content(), Map.of("id", id, "role", roleMap.get(id), "finishReason", finish)); if (choice.finishReason() != null) { generation = generation.withGenerationMetadata( ChatGenerationMetadata.from(choice.finishReason().name(), null)); } return generation; }).toList(); return new ChatResponse(generations); } catch (Exception e) { logger.error("Error processing chat completion", e); return new ChatResponse(List.of()); } }); }); } /** * Convert the ChatCompletionChunk into a ChatCompletion. The Usage is set to null. * @param chunk the ChatCompletionChunk to convert * @return the ChatCompletion */ private OpenAiApi.ChatCompletion chunkToChatCompletion(OpenAiApi.ChatCompletionChunk chunk) { List<Choice> choices = chunk.choices() .stream() .map(cc -> new Choice(cc.finishReason(), cc.index(), cc.delta(), cc.logprobs())) .toList(); return new OpenAiApi.ChatCompletion(chunk.id(), choices, chunk.created(), chunk.model(), chunk.systemFingerprint(), "chat.completion", null); } /** * Accessible for testing. */ ChatCompletionRequest createRequest(Prompt prompt, boolean stream) { Set<String> functionsForThisRequest = new HashSet<>(); List<ChatCompletionMessage> chatCompletionMessages = prompt.getInstructions() .stream() .map(m -> new ChatCompletionMessage(m.getContent(), ChatCompletionMessage.Role.valueOf(m.getMessageType().name()))) .toList(); ChatCompletionRequest request = new ChatCompletionRequest(chatCompletionMessages, stream); if (prompt.getOptions() != null) { if (prompt.getOptions() instanceof ChatOptions runtimeOptions) { OpenAiChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions, ChatOptions.class, OpenAiChatOptions.class); Set<String> promptEnabledFunctions = this.handleFunctionCallbackConfigurations(updatedRuntimeOptions, IS_RUNTIME_CALL); functionsForThisRequest.addAll(promptEnabledFunctions); request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, ChatCompletionRequest.class); } else { throw new IllegalArgumentException("Prompt options are not of type ChatOptions: " + prompt.getOptions().getClass().getSimpleName()); } } if (this.defaultOptions != null) { Set<String> defaultEnabledFunctions = this.handleFunctionCallbackConfigurations(this.defaultOptions, !IS_RUNTIME_CALL); functionsForThisRequest.addAll(defaultEnabledFunctions); request = ModelOptionsUtils.merge(request, this.defaultOptions, ChatCompletionRequest.class); } // Add the enabled functions definitions to the request's tools parameter. if (!CollectionUtils.isEmpty(functionsForThisRequest)) { request = ModelOptionsUtils.merge( OpenAiChatOptions.builder().withTools(this.getFunctionTools(functionsForThisRequest)).build(), request, ChatCompletionRequest.class); } return request; } private List<OpenAiApi.FunctionTool> getFunctionTools(Set<String> functionNames) { return this.resolveFunctionCallbacks(functionNames).stream().map(functionCallback -> { var function = new OpenAiApi.FunctionTool.Function(functionCallback.getDescription(), functionCallback.getName(), functionCallback.getInputTypeSchema()); return new OpenAiApi.FunctionTool(function); }).toList(); } @Override protected ChatCompletionRequest doCreateToolResponseRequest(ChatCompletionRequest previousRequest, ChatCompletionMessage responseMessage, List<ChatCompletionMessage> conversationHistory) { // Every tool-call item requires a separate function call and a response (TOOL) // message. for (ToolCall toolCall : responseMessage.toolCalls()) { var functionName = toolCall.function().name(); String functionArguments = toolCall.function().arguments(); if (!this.functionCallbackRegister.containsKey(functionName)) { throw new IllegalStateException("No function callback found for function name: " + functionName); } String functionResponse = this.functionCallbackRegister.get(functionName).call(functionArguments); // Add the function response to the conversation. conversationHistory .add(new ChatCompletionMessage(functionResponse, Role.TOOL, functionName, toolCall.id(), null)); } // Recursively call chatCompletionWithTools until the model doesn't call a // functions anymore. ChatCompletionRequest newRequest = new ChatCompletionRequest(conversationHistory, false); newRequest = ModelOptionsUtils.merge(newRequest, previousRequest, ChatCompletionRequest.class); return newRequest; } @Override protected List<ChatCompletionMessage> doGetUserMessages(ChatCompletionRequest request) { return request.messages(); } @Override protected ChatCompletionMessage doGetToolResponseMessage(ResponseEntity<ChatCompletion> chatCompletion) { return chatCompletion.getBody().choices().iterator().next().message(); } @Override protected ResponseEntity<ChatCompletion> doChatCompletion(ChatCompletionRequest request) { return this.openAiApi.chatCompletionEntity(request); } @Override protected boolean isToolFunctionCall(ResponseEntity<ChatCompletion> chatCompletion) { var body = chatCompletion.getBody(); if (body == null) { return false; } var choices = body.choices(); if (CollectionUtils.isEmpty(choices)) { return false; } var choice = choices.get(0); return !CollectionUtils.isEmpty(choice.message().toolCalls()) && choice.finishReason() == ChatCompletionFinishReason.TOOL_CALLS; } }
[ "org.springframework.ai.openai.api.OpenAiApi.ChatCompletionMessage.Role.valueOf", "org.springframework.ai.openai.metadata.OpenAiChatResponseMetadata.from" ]
[((5994, 6079), 'org.springframework.ai.openai.metadata.OpenAiChatResponseMetadata.from'), ((9137, 9198), 'org.springframework.ai.openai.api.OpenAiApi.ChatCompletionMessage.Role.valueOf')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.mistralai; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.StreamingChatClient; import org.springframework.ai.chat.metadata.ChatGenerationMetadata; import org.springframework.ai.chat.prompt.ChatOptions; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletion; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletion.Choice; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionChunk; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.ToolCall; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.ai.model.function.AbstractFunctionCallSupport; import org.springframework.ai.model.function.FunctionCallbackContext; import org.springframework.ai.retry.RetryUtils; import org.springframework.http.ResponseEntity; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * @author Ricken Bazolo * @author Christian Tzolov * @since 0.8.1 */ public class MistralAiChatClient extends AbstractFunctionCallSupport<MistralAiApi.ChatCompletionMessage, MistralAiApi.ChatCompletionRequest, ResponseEntity<MistralAiApi.ChatCompletion>> implements ChatClient, StreamingChatClient { private final Logger log = LoggerFactory.getLogger(getClass()); /** * The default options used for the chat completion requests. */ private MistralAiChatOptions defaultOptions; /** * Low-level access to the OpenAI API. */ private final MistralAiApi mistralAiApi; private final RetryTemplate retryTemplate; public MistralAiChatClient(MistralAiApi mistralAiApi) { this(mistralAiApi, MistralAiChatOptions.builder() .withTemperature(0.7f) .withTopP(1f) .withSafePrompt(false) .withModel(MistralAiApi.ChatModel.TINY.getValue()) .build()); } public MistralAiChatClient(MistralAiApi mistralAiApi, MistralAiChatOptions options) { this(mistralAiApi, options, null, RetryUtils.DEFAULT_RETRY_TEMPLATE); } public MistralAiChatClient(MistralAiApi mistralAiApi, MistralAiChatOptions options, FunctionCallbackContext functionCallbackContext, RetryTemplate retryTemplate) { super(functionCallbackContext); Assert.notNull(mistralAiApi, "MistralAiApi must not be null"); Assert.notNull(options, "Options must not be null"); Assert.notNull(retryTemplate, "RetryTemplate must not be null"); this.mistralAiApi = mistralAiApi; this.defaultOptions = options; this.retryTemplate = retryTemplate; } @Override public ChatResponse call(Prompt prompt) { var request = createRequest(prompt, false); return retryTemplate.execute(ctx -> { ResponseEntity<ChatCompletion> completionEntity = this.callWithFunctionSupport(request); var chatCompletion = completionEntity.getBody(); if (chatCompletion == null) { log.warn("No chat completion returned for prompt: {}", prompt); return new ChatResponse(List.of()); } List<Generation> generations = chatCompletion.choices() .stream() .map(choice -> new Generation(choice.message().content(), toMap(chatCompletion.id(), choice)) .withGenerationMetadata(ChatGenerationMetadata.from(choice.finishReason().name(), null))) .toList(); return new ChatResponse(generations); }); } private Map<String, Object> toMap(String id, ChatCompletion.Choice choice) { Map<String, Object> map = new HashMap<>(); var message = choice.message(); if (message.role() != null) { map.put("role", message.role().name()); } if (choice.finishReason() != null) { map.put("finishReason", choice.finishReason().name()); } map.put("id", id); return map; } @Override public Flux<ChatResponse> stream(Prompt prompt) { var request = createRequest(prompt, true); return retryTemplate.execute(ctx -> { var completionChunks = this.mistralAiApi.chatCompletionStream(request); // For chunked responses, only the first chunk contains the choice role. // The rest of the chunks with same ID share the same role. ConcurrentHashMap<String, String> roleMap = new ConcurrentHashMap<>(); return completionChunks.map(chunk -> toChatCompletion(chunk)).map(chatCompletion -> { chatCompletion = handleFunctionCallOrReturn(request, ResponseEntity.of(Optional.of(chatCompletion))) .getBody(); @SuppressWarnings("null") String id = chatCompletion.id(); List<Generation> generations = chatCompletion.choices().stream().map(choice -> { if (choice.message().role() != null) { roleMap.putIfAbsent(id, choice.message().role().name()); } String finish = (choice.finishReason() != null ? choice.finishReason().name() : ""); var generation = new Generation(choice.message().content(), Map.of("id", id, "role", roleMap.get(id), "finishReason", finish)); if (choice.finishReason() != null) { generation = generation .withGenerationMetadata(ChatGenerationMetadata.from(choice.finishReason().name(), null)); } return generation; }).toList(); return new ChatResponse(generations); }); }); } private ChatCompletion toChatCompletion(ChatCompletionChunk chunk) { List<Choice> choices = chunk.choices() .stream() .map(cc -> new Choice(cc.index(), cc.delta(), cc.finishReason())) .toList(); return new ChatCompletion(chunk.id(), "chat.completion", chunk.created(), chunk.model(), choices, null); } /** * Accessible for testing. */ MistralAiApi.ChatCompletionRequest createRequest(Prompt prompt, boolean stream) { Set<String> functionsForThisRequest = new HashSet<>(); var chatCompletionMessages = prompt.getInstructions() .stream() .map(m -> new MistralAiApi.ChatCompletionMessage(m.getContent(), MistralAiApi.ChatCompletionMessage.Role.valueOf(m.getMessageType().name()))) .toList(); var request = new MistralAiApi.ChatCompletionRequest(chatCompletionMessages, stream); if (this.defaultOptions != null) { Set<String> defaultEnabledFunctions = this.handleFunctionCallbackConfigurations(this.defaultOptions, !IS_RUNTIME_CALL); functionsForThisRequest.addAll(defaultEnabledFunctions); request = ModelOptionsUtils.merge(request, this.defaultOptions, MistralAiApi.ChatCompletionRequest.class); } if (prompt.getOptions() != null) { if (prompt.getOptions() instanceof ChatOptions runtimeOptions) { var updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions, ChatOptions.class, MistralAiChatOptions.class); Set<String> promptEnabledFunctions = this.handleFunctionCallbackConfigurations(updatedRuntimeOptions, IS_RUNTIME_CALL); functionsForThisRequest.addAll(promptEnabledFunctions); request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, MistralAiApi.ChatCompletionRequest.class); } else { throw new IllegalArgumentException("Prompt options are not of type ChatOptions: " + prompt.getOptions().getClass().getSimpleName()); } } // Add the enabled functions definitions to the request's tools parameter. if (!CollectionUtils.isEmpty(functionsForThisRequest)) { request = ModelOptionsUtils.merge( MistralAiChatOptions.builder().withTools(this.getFunctionTools(functionsForThisRequest)).build(), request, ChatCompletionRequest.class); } return request; } private List<MistralAiApi.FunctionTool> getFunctionTools(Set<String> functionNames) { return this.resolveFunctionCallbacks(functionNames).stream().map(functionCallback -> { var function = new MistralAiApi.FunctionTool.Function(functionCallback.getDescription(), functionCallback.getName(), functionCallback.getInputTypeSchema()); return new MistralAiApi.FunctionTool(function); }).toList(); } // // Function Calling Support // @Override protected ChatCompletionRequest doCreateToolResponseRequest(ChatCompletionRequest previousRequest, ChatCompletionMessage responseMessage, List<ChatCompletionMessage> conversationHistory) { // Every tool-call item requires a separate function call and a response (TOOL) // message. for (ToolCall toolCall : responseMessage.toolCalls()) { var functionName = toolCall.function().name(); String functionArguments = toolCall.function().arguments(); if (!this.functionCallbackRegister.containsKey(functionName)) { throw new IllegalStateException("No function callback found for function name: " + functionName); } String functionResponse = this.functionCallbackRegister.get(functionName).call(functionArguments); // Add the function response to the conversation. conversationHistory .add(new ChatCompletionMessage(functionResponse, ChatCompletionMessage.Role.TOOL, functionName, null)); } // Recursively call chatCompletionWithTools until the model doesn't call a // functions anymore. ChatCompletionRequest newRequest = new ChatCompletionRequest(conversationHistory, false); newRequest = ModelOptionsUtils.merge(newRequest, previousRequest, ChatCompletionRequest.class); return newRequest; } @Override protected List<ChatCompletionMessage> doGetUserMessages(ChatCompletionRequest request) { return request.messages(); } @SuppressWarnings("null") @Override protected ChatCompletionMessage doGetToolResponseMessage(ResponseEntity<ChatCompletion> chatCompletion) { return chatCompletion.getBody().choices().iterator().next().message(); } @Override protected ResponseEntity<ChatCompletion> doChatCompletion(ChatCompletionRequest request) { return this.mistralAiApi.chatCompletionEntity(request); } @Override protected boolean isToolFunctionCall(ResponseEntity<ChatCompletion> chatCompletion) { var body = chatCompletion.getBody(); if (body == null) { return false; } var choices = body.choices(); if (CollectionUtils.isEmpty(choices)) { return false; } return !CollectionUtils.isEmpty(choices.get(0).message().toolCalls()); } }
[ "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue", "org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.Role.valueOf" ]
[((3142, 3180), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.TINY.getValue'), ((7075, 7149), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.Role.valueOf')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.openai; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * OpenAI Image autoconfiguration properties. * * @author Thomas Vitale * @since 0.8.0 */ @ConfigurationProperties(OpenAiImageProperties.CONFIG_PREFIX) public class OpenAiImageProperties extends OpenAiParentProperties { public static final String CONFIG_PREFIX = "spring.ai.openai.image"; /** * Enable OpenAI Image client. */ private boolean enabled = true; /** * Options for OpenAI Image API. */ @NestedConfigurationProperty private OpenAiImageOptions options = OpenAiImageOptions.builder().build(); public OpenAiImageOptions getOptions() { return options; } public void setOptions(OpenAiImageOptions options) { this.options = options; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((1375, 1411), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
package com.example.springaiimagegenerator.controller; import org.springframework.ai.image.Image; import org.springframework.ai.image.ImageClient; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ImageGeneratorController { @Autowired private ImageClient openAiImageClient; @GetMapping("/image") public Image getImage(@RequestParam String imagePrompt){ ImageResponse response = openAiImageClient.call( new ImagePrompt(imagePrompt, OpenAiImageOptions.builder() .withQuality("hd") .withN(4) .withHeight(1024) .withWidth(1024).build()) ); return response.getResult().getOutput(); } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((945, 1173), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((945, 1165), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((945, 1116), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((945, 1066), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((945, 1024), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.metadata.RateLimit; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.AudioResponseFormat; import org.springframework.ai.openai.api.common.OpenAiApiException; import org.springframework.ai.openai.audio.speech.*; import org.springframework.ai.openai.metadata.audio.OpenAiAudioSpeechResponseMetadata; import org.springframework.ai.openai.metadata.support.OpenAiResponseHeaderExtractor; import org.springframework.http.ResponseEntity; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.Assert; import reactor.core.publisher.Flux; import java.time.Duration; /** * OpenAI audio speech client implementation for backed by {@link OpenAiAudioApi}. * * @author Ahmed Yousri * @see OpenAiAudioApi * @since 1.0.0-M1 */ public class OpenAiAudioSpeechClient implements SpeechClient, StreamingSpeechClient { private final Logger logger = LoggerFactory.getLogger(getClass()); private final OpenAiAudioSpeechOptions defaultOptions; private static final Float SPEED = 1.0f; public final RetryTemplate retryTemplate = RetryTemplate.builder() .maxAttempts(10) .retryOn(OpenAiApiException.class) .exponentialBackoff(Duration.ofMillis(2000), 5, Duration.ofMillis(3 * 60000)) .build(); private final OpenAiAudioApi audioApi; /** * Initializes a new instance of the OpenAiAudioSpeechClient class with the provided * OpenAiAudioApi. It uses the model tts-1, response format mp3, voice alloy, and the * default speed of 1.0. * @param audioApi The OpenAiAudioApi to use for speech synthesis. */ public OpenAiAudioSpeechClient(OpenAiAudioApi audioApi) { this(audioApi, OpenAiAudioSpeechOptions.builder() .withModel(OpenAiAudioApi.TtsModel.TTS_1.getValue()) .withResponseFormat(AudioResponseFormat.MP3) .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .build()); } /** * Initializes a new instance of the OpenAiAudioSpeechClient class with the provided * OpenAiAudioApi and options. * @param audioApi The OpenAiAudioApi to use for speech synthesis. * @param options The OpenAiAudioSpeechOptions containing the speech synthesis * options. */ public OpenAiAudioSpeechClient(OpenAiAudioApi audioApi, OpenAiAudioSpeechOptions options) { Assert.notNull(audioApi, "OpenAiAudioApi must not be null"); Assert.notNull(options, "OpenAiSpeechOptions must not be null"); this.audioApi = audioApi; this.defaultOptions = options; } @Override public byte[] call(String text) { SpeechPrompt speechRequest = new SpeechPrompt(text); return call(speechRequest).getResult().getOutput(); } @Override public SpeechResponse call(SpeechPrompt speechPrompt) { return this.retryTemplate.execute(ctx -> { OpenAiAudioApi.SpeechRequest speechRequest = createRequestBody(speechPrompt); ResponseEntity<byte[]> speechEntity = this.audioApi.createSpeech(speechRequest); var speech = speechEntity.getBody(); if (speech == null) { logger.warn("No speech response returned for speechRequest: {}", speechRequest); return new SpeechResponse(new Speech(new byte[0])); } RateLimit rateLimits = OpenAiResponseHeaderExtractor.extractAiResponseHeaders(speechEntity); return new SpeechResponse(new Speech(speech), new OpenAiAudioSpeechResponseMetadata(rateLimits)); }); } /** * Streams the audio response for the given speech prompt. * @param prompt The speech prompt containing the text and options for speech * synthesis. * @return A Flux of SpeechResponse objects containing the streamed audio and * metadata. */ @Override public Flux<SpeechResponse> stream(SpeechPrompt prompt) { return this.audioApi.stream(this.createRequestBody(prompt)) .map(entity -> new SpeechResponse(new Speech(entity.getBody()), new OpenAiAudioSpeechResponseMetadata( OpenAiResponseHeaderExtractor.extractAiResponseHeaders(entity)))); } private OpenAiAudioApi.SpeechRequest createRequestBody(SpeechPrompt request) { OpenAiAudioSpeechOptions options = this.defaultOptions; if (request.getOptions() != null) { if (request.getOptions() instanceof OpenAiAudioSpeechOptions runtimeOptions) { options = this.merge(options, runtimeOptions); } else { throw new IllegalArgumentException("Prompt options are not of type SpeechOptions: " + request.getOptions().getClass().getSimpleName()); } } String input = StringUtils.isNotBlank(options.getInput()) ? options.getInput() : request.getInstructions().getText(); OpenAiAudioApi.SpeechRequest.Builder requestBuilder = OpenAiAudioApi.SpeechRequest.builder() .withModel(options.getModel()) .withInput(input) .withVoice(options.getVoice()) .withResponseFormat(options.getResponseFormat()) .withSpeed(options.getSpeed()); return requestBuilder.build(); } private OpenAiAudioSpeechOptions merge(OpenAiAudioSpeechOptions source, OpenAiAudioSpeechOptions target) { OpenAiAudioSpeechOptions.Builder mergedBuilder = OpenAiAudioSpeechOptions.builder(); mergedBuilder.withModel(source.getModel() != null ? source.getModel() : target.getModel()); mergedBuilder.withInput(source.getInput() != null ? source.getInput() : target.getInput()); mergedBuilder.withVoice(source.getVoice() != null ? source.getVoice() : target.getVoice()); mergedBuilder.withResponseFormat( source.getResponseFormat() != null ? source.getResponseFormat() : target.getResponseFormat()); mergedBuilder.withSpeed(source.getSpeed() != null ? source.getSpeed() : target.getSpeed()); return mergedBuilder.build(); } }
[ "org.springframework.ai.openai.api.OpenAiAudioApi.TtsModel.TTS_1.getValue", "org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder" ]
[((1927, 2097), 'org.springframework.retry.support.RetryTemplate.builder'), ((1927, 2086), 'org.springframework.retry.support.RetryTemplate.builder'), ((1927, 2006), 'org.springframework.retry.support.RetryTemplate.builder'), ((1927, 1969), 'org.springframework.retry.support.RetryTemplate.builder'), ((2549, 2589), 'org.springframework.ai.openai.api.OpenAiAudioApi.TtsModel.TTS_1.getValue'), ((5414, 5627), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((5414, 5593), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((5414, 5541), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((5414, 5507), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((5414, 5486), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((5414, 5452), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.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.transformer; import java.util.ArrayList; import java.util.List; import org.springframework.ai.document.ContentFormatter; import org.springframework.ai.document.DefaultContentFormatter; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentTransformer; /** * @author Christian Tzolov */ public class ContentFormatTransformer implements DocumentTransformer { /** * Disable the content-formatter template rewrite. */ private boolean disableTemplateRewrite = false; private ContentFormatter contentFormatter; public ContentFormatTransformer(ContentFormatter contentFormatter) { this(contentFormatter, false); } public ContentFormatTransformer(ContentFormatter contentFormatter, boolean disableTemplateRewrite) { this.contentFormatter = contentFormatter; this.disableTemplateRewrite = disableTemplateRewrite; } /** * Post process documents chunked from loader. Allows extractors to be chained. * @param documents to post process. * @return */ public List<Document> apply(List<Document> documents) { if (this.contentFormatter != null) { documents.forEach(document -> { // Update formatter if (document.getContentFormatter() instanceof DefaultContentFormatter && this.contentFormatter instanceof DefaultContentFormatter) { DefaultContentFormatter docFormatter = (DefaultContentFormatter) document.getContentFormatter(); DefaultContentFormatter toUpdateFormatter = (DefaultContentFormatter) this.contentFormatter; var updatedEmbedExcludeKeys = new ArrayList<>(docFormatter.getExcludedEmbedMetadataKeys()); updatedEmbedExcludeKeys.addAll(toUpdateFormatter.getExcludedEmbedMetadataKeys()); var updatedInterfaceExcludeKeys = new ArrayList<>(docFormatter.getExcludedInferenceMetadataKeys()); updatedInterfaceExcludeKeys.addAll(toUpdateFormatter.getExcludedInferenceMetadataKeys()); var builder = DefaultContentFormatter.builder() .withExcludedEmbedMetadataKeys(updatedEmbedExcludeKeys) .withExcludedInferenceMetadataKeys(updatedInterfaceExcludeKeys) .withMetadataTemplate(docFormatter.getMetadataTemplate()) .withMetadataSeparator(docFormatter.getMetadataSeparator()); if (!this.disableTemplateRewrite) { builder.withTextTemplate(docFormatter.getTextTemplate()); } document.setContentFormatter(builder.build()); } else { // Override formatter document.setContentFormatter(this.contentFormatter); } }); } return documents; } }
[ "org.springframework.ai.document.DefaultContentFormatter.builder" ]
[((2573, 2868), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((2573, 2802), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((2573, 2738), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((2573, 2668), '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.openai.audio.speech; import org.springframework.ai.model.ModelOptions; import org.springframework.ai.model.ModelRequest; import org.springframework.ai.openai.OpenAiAudioSpeechOptions; import java.util.Collections; import java.util.List; import java.util.Objects; /** * The {@link SpeechPrompt} class represents a request to the OpenAI Text-to-Speech (TTS) * API. It contains a list of {@link SpeechMessage} objects, each representing a piece of * text to be converted to speech. * * @author Ahmed Yousri * @since 1.0.0-M1 */ public class SpeechPrompt implements ModelRequest<SpeechMessage> { private OpenAiAudioSpeechOptions speechOptions; private final SpeechMessage message; public SpeechPrompt(String instructions) { this(new SpeechMessage(instructions), OpenAiAudioSpeechOptions.builder().build()); } public SpeechPrompt(String instructions, OpenAiAudioSpeechOptions speechOptions) { this(new SpeechMessage(instructions), speechOptions); } public SpeechPrompt(SpeechMessage speechMessage) { this(speechMessage, OpenAiAudioSpeechOptions.builder().build()); } public SpeechPrompt(SpeechMessage speechMessage, OpenAiAudioSpeechOptions speechOptions) { this.message = speechMessage; this.speechOptions = speechOptions; } @Override public SpeechMessage getInstructions() { return this.message; } @Override public ModelOptions getOptions() { return speechOptions; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SpeechPrompt that)) return false; return Objects.equals(speechOptions, that.speechOptions) && Objects.equals(message, that.message); } @Override public int hashCode() { return Objects.hash(speechOptions, message); } }
[ "org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder" ]
[((1426, 1468), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((1693, 1735), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.jurrasic2; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionConfiguration; import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties; import org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatClient; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; /** * {@link AutoConfiguration Auto-configuration} for Bedrock Jurassic2 Chat Client. * * @author Ahmed Yousri * @since 1.0.0 */ @AutoConfiguration @ConditionalOnClass(Ai21Jurassic2ChatBedrockApi.class) @EnableConfigurationProperties({ BedrockAi21Jurassic2ChatProperties.class, BedrockAwsConnectionProperties.class }) @ConditionalOnProperty(prefix = BedrockAi21Jurassic2ChatProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true") @Import(BedrockAwsConnectionConfiguration.class) public class BedrockAi21Jurassic2ChatAutoConfiguration { @Bean @ConditionalOnMissingBean public Ai21Jurassic2ChatBedrockApi ai21Jurassic2ChatBedrockApi(AwsCredentialsProvider credentialsProvider, BedrockAi21Jurassic2ChatProperties properties, BedrockAwsConnectionProperties awsProperties) { return new Ai21Jurassic2ChatBedrockApi(properties.getModel(), credentialsProvider, awsProperties.getRegion(), new ObjectMapper()); } @Bean public BedrockAi21Jurassic2ChatClient jurassic2ChatClient(Ai21Jurassic2ChatBedrockApi ai21Jurassic2ChatBedrockApi, BedrockAi21Jurassic2ChatProperties properties) { return BedrockAi21Jurassic2ChatClient.builder(ai21Jurassic2ChatBedrockApi) .withOptions(properties.getOptions()) .build(); } }
[ "org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatClient.builder" ]
[((2751, 2871), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatClient.builder'), ((2751, 2859), 'org.springframework.ai.bedrock.jurassic2.BedrockAi21Jurassic2ChatClient.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.jurassic2; import org.springframework.ai.bedrock.MessageToPromptConverter; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi; import org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatRequest; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.metadata.ChatGenerationMetadata; import org.springframework.ai.chat.prompt.ChatOptions; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.util.Assert; /** * Java {@link ChatClient} for the Bedrock Jurassic2 chat generative model. * * @author Ahmed Yousri * @since 1.0.0 */ public class BedrockAi21Jurassic2ChatClient implements ChatClient { private final Ai21Jurassic2ChatBedrockApi chatApi; private final BedrockAi21Jurassic2ChatOptions defaultOptions; public BedrockAi21Jurassic2ChatClient(Ai21Jurassic2ChatBedrockApi chatApi, BedrockAi21Jurassic2ChatOptions options) { Assert.notNull(chatApi, "Ai21Jurassic2ChatBedrockApi must not be null"); Assert.notNull(options, "BedrockAi21Jurassic2ChatOptions must not be null"); this.chatApi = chatApi; this.defaultOptions = options; } public BedrockAi21Jurassic2ChatClient(Ai21Jurassic2ChatBedrockApi chatApi) { this(chatApi, BedrockAi21Jurassic2ChatOptions.builder() .withTemperature(0.8f) .withTopP(0.9f) .withMaxTokens(100) .build()); } @Override public ChatResponse call(Prompt prompt) { var request = createRequest(prompt); var response = this.chatApi.chatCompletion(request); return new ChatResponse(response.completions() .stream() .map(completion -> new Generation(completion.data().text()) .withGenerationMetadata(ChatGenerationMetadata.from(completion.finishReason().reason(), null))) .toList()); } private Ai21Jurassic2ChatRequest createRequest(Prompt prompt) { final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions()); Ai21Jurassic2ChatRequest request = Ai21Jurassic2ChatRequest.builder(promptValue).build(); if (prompt.getOptions() != null) { if (prompt.getOptions() instanceof ChatOptions runtimeOptions) { BedrockAi21Jurassic2ChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions, ChatOptions.class, BedrockAi21Jurassic2ChatOptions.class); request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, Ai21Jurassic2ChatRequest.class); } else { throw new IllegalArgumentException("Prompt options are not of type ChatOptions: " + prompt.getOptions().getClass().getSimpleName()); } } if (this.defaultOptions != null) { request = ModelOptionsUtils.merge(request, this.defaultOptions, Ai21Jurassic2ChatRequest.class); } return request; } public static Builder builder(Ai21Jurassic2ChatBedrockApi chatApi) { return new Builder(chatApi); } public static class Builder { private final Ai21Jurassic2ChatBedrockApi chatApi; private BedrockAi21Jurassic2ChatOptions options; public Builder(Ai21Jurassic2ChatBedrockApi chatApi) { this.chatApi = chatApi; } public Builder withOptions(BedrockAi21Jurassic2ChatOptions options) { this.options = options; return this; } public BedrockAi21Jurassic2ChatClient build() { return new BedrockAi21Jurassic2ChatClient(chatApi, options != null ? options : BedrockAi21Jurassic2ChatOptions.builder().build()); } } }
[ "org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatRequest.builder", "org.springframework.ai.bedrock.MessageToPromptConverter.create" ]
[((2709, 2777), 'org.springframework.ai.bedrock.MessageToPromptConverter.create'), ((2817, 2870), 'org.springframework.ai.bedrock.jurassic2.api.Ai21Jurassic2ChatBedrockApi.Ai21Jurassic2ChatRequest.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.cohere; import org.springframework.ai.bedrock.cohere.BedrockCohereEmbeddingOptions; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingRequest; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingRequest.InputType; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * Bedrock Cohere Embedding autoconfiguration properties. * * @author Christian Tzolov * @since 0.8.0 */ @ConfigurationProperties(BedrockCohereEmbeddingProperties.CONFIG_PREFIX) public class BedrockCohereEmbeddingProperties { public static final String CONFIG_PREFIX = "spring.ai.bedrock.cohere.embedding"; /** * Enable Bedrock Cohere Embedding Client. False by default. */ private boolean enabled = false; /** * Bedrock Cohere Embedding generative name. Defaults to * 'cohere.embed-multilingual-v3'. */ private String model = CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id(); @NestedConfigurationProperty private BedrockCohereEmbeddingOptions options = BedrockCohereEmbeddingOptions.builder() .withInputType(InputType.SEARCH_DOCUMENT) .withTruncate(CohereEmbeddingRequest.Truncate.NONE) .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 BedrockCohereEmbeddingOptions getOptions() { return this.options; } public void setOptions(BedrockCohereEmbeddingOptions options) { this.options = options; } }
[ "org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id", "org.springframework.ai.bedrock.cohere.BedrockCohereEmbeddingOptions.builder" ]
[((1772, 1826), 'org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id'), ((1908, 2056), 'org.springframework.ai.bedrock.cohere.BedrockCohereEmbeddingOptions.builder'), ((1908, 2045), 'org.springframework.ai.bedrock.cohere.BedrockCohereEmbeddingOptions.builder'), ((1908, 1991), 'org.springframework.ai.bedrock.cohere.BedrockCohereEmbeddingOptions.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.pinecone; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.PineconeVectorStore; import org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; /** * @author Christian Tzolov */ @AutoConfiguration @ConditionalOnClass({ PineconeVectorStore.class, EmbeddingClient.class }) @EnableConfigurationProperties(PineconeVectorStoreProperties.class) public class PineconeVectorStoreAutoConfiguration { @Bean @ConditionalOnMissingBean public PineconeVectorStore vectorStore(EmbeddingClient embeddingClient, PineconeVectorStoreProperties properties) { var config = PineconeVectorStoreConfig.builder() .withApiKey(properties.getApiKey()) .withEnvironment(properties.getEnvironment()) .withProjectId(properties.getProjectId()) .withIndexName(properties.getIndexName()) .withNamespace(properties.getNamespace()) .withServerSideTimeout(properties.getServerSideTimeout()) .build(); return new PineconeVectorStore(config, embeddingClient); } }
[ "org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder" ]
[((1671, 2002), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((1671, 1990), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((1671, 1929), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((1671, 1884), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((1671, 1839), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((1671, 1794), 'org.springframework.ai.vectorstore.PineconeVectorStore.PineconeVectorStoreConfig.builder'), ((1671, 1745), '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.autoconfigure.vertexai.palm2; import org.springframework.ai.vertexai.palm2.VertexAiPaLm2ChatOptions; import org.springframework.ai.vertexai.palm2.api.VertexAiPaLm2Api; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(VertexAiPlam2ChatProperties.CONFIG_PREFIX) public class VertexAiPlam2ChatProperties { public static final String CONFIG_PREFIX = "spring.ai.vertex.ai.chat"; /** * Enable Vertex AI PaLM API chat client. */ private boolean enabled = true; /** * Vertex AI PaLM API generative name. Defaults to chat-bison-001 */ private String model = VertexAiPaLm2Api.DEFAULT_GENERATE_MODEL; /** * Vertex AI PaLM API generative options. */ private VertexAiPaLm2ChatOptions options = VertexAiPaLm2ChatOptions.builder() .withTemperature(0.7f) .withTopP(null) .withCandidateCount(1) .withTopK(20) .build(); public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public VertexAiPaLm2ChatOptions getOptions() { return this.options; } public void setOptions(VertexAiPaLm2ChatOptions options) { this.options = options; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
[ "org.springframework.ai.vertexai.palm2.VertexAiPaLm2ChatOptions.builder" ]
[((1408, 1537), 'org.springframework.ai.vertexai.palm2.VertexAiPaLm2ChatOptions.builder'), ((1408, 1526), 'org.springframework.ai.vertexai.palm2.VertexAiPaLm2ChatOptions.builder'), ((1408, 1510), 'org.springframework.ai.vertexai.palm2.VertexAiPaLm2ChatOptions.builder'), ((1408, 1485), 'org.springframework.ai.vertexai.palm2.VertexAiPaLm2ChatOptions.builder'), ((1408, 1467), 'org.springframework.ai.vertexai.palm2.VertexAiPaLm2ChatOptions.builder')]
package org.springframework.ai.dashcope.image; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.dashcope.DashCopeTestConfiguration; import org.springframework.ai.image.ImageClient; import org.springframework.ai.image.ImageOptions; import org.springframework.ai.image.ImageOptionsBuilder; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest(classes = {DashCopeTestConfiguration.class}) public class QWenImageClientIT { private final Logger logger = LoggerFactory.getLogger(QWenImageClientIT.class); @Autowired private ImageClient qwenImageClient; @Test public void imageAsUrlTest() { ImageOptions options = ImageOptionsBuilder.builder().withHeight(1024).withWidth(1024).build(); String instructions = """ A light cream colored mini golden doodle with a sign that contains the message "I'm on my way to BARCADE!". """; ImagePrompt imagePrompt = new ImagePrompt(instructions, options); ImageResponse imageResponse = qwenImageClient.call(imagePrompt); imageResponse.getResults().forEach(result -> { logger.info("URL:{}",result.getOutput().getUrl()); }); } }
[ "org.springframework.ai.image.ImageOptionsBuilder.builder" ]
[((882, 952), 'org.springframework.ai.image.ImageOptionsBuilder.builder'), ((882, 944), 'org.springframework.ai.image.ImageOptionsBuilder.builder'), ((882, 928), 'org.springframework.ai.image.ImageOptionsBuilder.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.postgresml; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.ai.embedding.EmbeddingOptions; import org.springframework.ai.embedding.EmbeddingRequest; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.ai.postgresml.PostgresMlEmbeddingClient.VectorType; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.ai.document.Document; import org.springframework.ai.document.MetadataMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.jdbc.core.JdbcTemplate; import static org.assertj.core.api.Assertions.assertThat; /** * @author Toshiaki Maki */ @JdbcTest(properties = "logging.level.sql=TRACE") @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @Testcontainers @Disabled("Disabled from automatic execution, as it requires an excessive amount of memory (over 9GB)!") class PostgresMlEmbeddingClientIT { @Container @ServiceConnection static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>( DockerImageName.parse("ghcr.io/postgresml/postgresml:2.8.1").asCompatibleSubstituteFor("postgres")) .withCommand("sleep", "infinity") .withLabel("org.springframework.boot.service-connection", "postgres") .withUsername("postgresml") .withPassword("postgresml") .withDatabaseName("postgresml") .waitingFor(new LogMessageWaitStrategy().withRegEx(".*Starting dashboard.*\\s") .withStartupTimeout(Duration.of(60, ChronoUnit.SECONDS))); @Autowired JdbcTemplate jdbcTemplate; @AfterEach void dropPgmlExtension() { this.jdbcTemplate.execute("DROP EXTENSION IF EXISTS pgml"); } @Test void embed() { PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(this.jdbcTemplate); embeddingClient.afterPropertiesSet(); List<Double> embed = embeddingClient.embed("Hello World!"); assertThat(embed).hasSize(768); } @Test void embedWithPgVector() { PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(this.jdbcTemplate, PostgresMlEmbeddingOptions.builder() .withTransformer("distilbert-base-uncased") .withVectorType(PostgresMlEmbeddingClient.VectorType.PG_VECTOR) .build()); embeddingClient.afterPropertiesSet(); List<Double> embed = embeddingClient.embed(new Document("Hello World!")); assertThat(embed).hasSize(768); } @Test void embedWithDifferentModel() { PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(this.jdbcTemplate, PostgresMlEmbeddingOptions.builder().withTransformer("intfloat/e5-small").build()); embeddingClient.afterPropertiesSet(); List<Double> embed = embeddingClient.embed(new Document("Hello World!")); assertThat(embed).hasSize(384); } @Test void embedWithKwargs() { PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(this.jdbcTemplate, PostgresMlEmbeddingOptions.builder() .withTransformer("distilbert-base-uncased") .withVectorType(PostgresMlEmbeddingClient.VectorType.PG_ARRAY) .withKwargs(Map.of("device", "cpu")) .withMetadataMode(MetadataMode.EMBED) .build()); embeddingClient.afterPropertiesSet(); List<Double> embed = embeddingClient.embed(new Document("Hello World!")); assertThat(embed).hasSize(768); } @ParameterizedTest @ValueSource(strings = { "PG_ARRAY", "PG_VECTOR" }) void embedForResponse(String vectorType) { PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(this.jdbcTemplate, PostgresMlEmbeddingOptions.builder() .withTransformer("distilbert-base-uncased") .withVectorType(VectorType.valueOf(vectorType)) .build()); embeddingClient.afterPropertiesSet(); EmbeddingResponse embeddingResponse = embeddingClient .embedForResponse(List.of("Hello World!", "Spring AI!", "LLM!")); assertThat(embeddingResponse).isNotNull(); assertThat(embeddingResponse.getResults()).hasSize(3); assertThat(embeddingResponse.getMetadata()).containsExactlyInAnyOrderEntriesOf( Map.of("transformer", "distilbert-base-uncased", "vector-type", vectorType, "kwargs", "{}")); assertThat(embeddingResponse.getResults().get(0).getIndex()).isEqualTo(0); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(768); assertThat(embeddingResponse.getResults().get(1).getIndex()).isEqualTo(1); assertThat(embeddingResponse.getResults().get(1).getOutput()).hasSize(768); assertThat(embeddingResponse.getResults().get(2).getIndex()).isEqualTo(2); assertThat(embeddingResponse.getResults().get(2).getOutput()).hasSize(768); } @Test void embedCallWithRequestOptionsOverride() { PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(this.jdbcTemplate, PostgresMlEmbeddingOptions.builder() .withTransformer("distilbert-base-uncased") .withVectorType(VectorType.PG_VECTOR) .build()); embeddingClient.afterPropertiesSet(); var request1 = new EmbeddingRequest(List.of("Hello World!", "Spring AI!", "LLM!"), EmbeddingOptions.EMPTY); EmbeddingResponse embeddingResponse = embeddingClient.call(request1); assertThat(embeddingResponse).isNotNull(); assertThat(embeddingResponse.getResults()).hasSize(3); assertThat(embeddingResponse.getMetadata()).containsExactlyInAnyOrderEntriesOf(Map.of("transformer", "distilbert-base-uncased", "vector-type", VectorType.PG_VECTOR.name(), "kwargs", "{}")); assertThat(embeddingResponse.getResults().get(0).getIndex()).isEqualTo(0); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(768); assertThat(embeddingResponse.getResults().get(1).getIndex()).isEqualTo(1); assertThat(embeddingResponse.getResults().get(1).getOutput()).hasSize(768); assertThat(embeddingResponse.getResults().get(2).getIndex()).isEqualTo(2); assertThat(embeddingResponse.getResults().get(2).getOutput()).hasSize(768); // Override the default options in the request var request2 = new EmbeddingRequest(List.of("Hello World!", "Spring AI!", "LLM!"), PostgresMlEmbeddingOptions.builder() .withTransformer("intfloat/e5-small") .withVectorType(VectorType.PG_ARRAY) .withMetadataMode(MetadataMode.EMBED) .withKwargs(Map.of("device", "cpu")) .build()); embeddingResponse = embeddingClient.call(request2); assertThat(embeddingResponse).isNotNull(); assertThat(embeddingResponse.getResults()).hasSize(3); assertThat(embeddingResponse.getMetadata()).containsExactlyInAnyOrderEntriesOf(Map.of("transformer", "intfloat/e5-small", "vector-type", VectorType.PG_ARRAY.name(), "kwargs", "{\"device\":\"cpu\"}")); assertThat(embeddingResponse.getResults().get(0).getIndex()).isEqualTo(0); assertThat(embeddingResponse.getResults().get(0).getOutput()).hasSize(384); assertThat(embeddingResponse.getResults().get(1).getIndex()).isEqualTo(1); assertThat(embeddingResponse.getResults().get(1).getOutput()).hasSize(384); assertThat(embeddingResponse.getResults().get(2).getIndex()).isEqualTo(2); assertThat(embeddingResponse.getResults().get(2).getOutput()).hasSize(384); } @Test void dimensions() { PostgresMlEmbeddingClient embeddingClient = new PostgresMlEmbeddingClient(this.jdbcTemplate); embeddingClient.afterPropertiesSet(); Assertions.assertThat(embeddingClient.dimensions()).isEqualTo(768); // cached Assertions.assertThat(embeddingClient.dimensions()).isEqualTo(768); } @SpringBootApplication public static class TestApplication { } }
[ "org.springframework.ai.postgresml.PostgresMlEmbeddingClient.VectorType.PG_ARRAY.name", "org.springframework.ai.postgresml.PostgresMlEmbeddingClient.VectorType.PG_VECTOR.name" ]
[((2582, 2680), 'org.testcontainers.utility.DockerImageName.parse'), ((6884, 6911), 'org.springframework.ai.postgresml.PostgresMlEmbeddingClient.VectorType.PG_VECTOR.name'), ((8059, 8085), 'org.springframework.ai.postgresml.PostgresMlEmbeddingClient.VectorType.PG_ARRAY.name'), ((8759, 8825), 'org.assertj.core.api.Assertions.assertThat'), ((8841, 8907), 'org.assertj.core.api.Assertions.assertThat')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.vectorstore.azure; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import com.azure.core.credential.AzureKeyCredential; import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.indexes.SearchIndexClientBuilder; import org.awaitility.Awaitility; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.ai.vectorstore.azure.AzureVectorStore.MetadataField; 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 = "AZURE_AI_SEARCH_API_KEY", matches = ".+") @EnabledIfEnvironmentVariable(named = "AZURE_AI_SEARCH_ENDPOINT", matches = ".+") public class AzureVectorStoreIT { List<Document> documents = List.of( new Document("1", getText("classpath:/test/data/spring.ai.txt"), Map.of("meta1", "meta1")), new Document("2", getText("classpath:/test/data/time.shelter.txt"), Map.of()), new Document("3", getText("classpath:/test/data/great.depression.txt"), Map.of("meta2", "meta2"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(Config.class); @BeforeAll public static void beforeAll() { Awaitility.setDefaultPollInterval(2, TimeUnit.SECONDS); Awaitility.setDefaultPollDelay(Duration.ZERO); Awaitility.setDefaultTimeout(Duration.ofMinutes(1)); } @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 searchWithFilters() throws InterruptedException { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); var bgDocument = new Document("1", "The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2020, "activationDate", new Date(1000))); var nlDocument = new Document("2", "The World is Big and Salvation Lurks Around the Corner", Map.of("country", "NL", "activationDate", new Date(2000))); var bgDocument2 = new Document("3", "The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2023, "activationDate", new Date(3000))); vectorStore.add(List.of(bgDocument, nlDocument, bgDocument2)); Awaitility.await().until(() -> { return vectorStore.similaritySearch(SearchRequest.query("The World").withTopK(5)); }, hasSize(3)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'NL'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG'")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG' && year == 2020")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country in ['BG']")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country in ['BG','NL']")); assertThat(results).hasSize(3); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country not in ['BG']")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("NOT(country not in ['BG'])")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); // List<Document> results = // vectorStore.similaritySearch(SearchRequest.query("The World") // .withTopK(5) // .withSimilarityThresholdAll() // .withFilterExpression("activationDate > '1970-01-01T00:00:02Z'")); // assertThat(results).hasSize(1); // assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); vectorStore.delete(List.of(bgDocument.getId(), nlDocument.getId(), bgDocument2.getId())); }); } @Test public void documentUpdateTest() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); Document document = new Document(UUID.randomUUID().toString(), "Spring AI rocks!!", Collections.singletonMap("meta1", "meta1")); vectorStore.add(List.of(document)); SearchRequest springSearchRequest = SearchRequest.query("Spring").withTopK(5); Awaitility.await().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 Config { @Bean public SearchIndexClient searchIndexClient() { return new SearchIndexClientBuilder().endpoint(System.getenv("AZURE_AI_SEARCH_ENDPOINT")) .credential(new AzureKeyCredential(System.getenv("AZURE_AI_SEARCH_API_KEY"))) .buildClient(); } @Bean public VectorStore vectorStore(SearchIndexClient searchIndexClient, EmbeddingClient embeddingClient) { var filterableMetaFields = List.of(MetadataField.text("country"), MetadataField.int64("year"), MetadataField.date("activationDate")); return new AzureVectorStore(searchIndexClient, embeddingClient, filterableMetaFields); } @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } private 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); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3193, 3337), 'org.awaitility.Awaitility.await'), ((3266, 3317), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3397, 3448), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4004, 4137), 'org.awaitility.Awaitility.await'), ((4077, 4117), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4902, 5039), 'org.awaitility.Awaitility.await'), ((4975, 5019), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5099, 5227), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5099, 5182), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5099, 5148), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5377, 5505), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5377, 5460), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5377, 5426), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5757, 5901), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5757, 5840), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5757, 5806), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6052, 6182), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6052, 6135), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6052, 6101), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6434, 6569), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6434, 6517), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6434, 6483), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6651, 6785), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6651, 6734), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6651, 6700), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6936, 7075), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6936, 7019), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6936, 6985), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((7907, 7935), 'java.util.UUID.randomUUID'), ((8088, 8129), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((8135, 8247), 'org.awaitility.Awaitility.await'), ((8922, 8963), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((8969, 9156), 'org.awaitility.Awaitility.await'), ((9680, 9792), 'org.awaitility.Awaitility.await'), ((9985, 10159), 'org.awaitility.Awaitility.await'), ((10064, 10139), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((10064, 10110), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((10227, 10301), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((10227, 10272), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((10582, 10666), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((10582, 10627), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((11170, 11303), 'org.awaitility.Awaitility.await'), ((11243, 11283), '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.titan; 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.titan.BedrockTitanChatClient; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel; 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 BedrockTitanChatAutoConfigurationIT { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.titan.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.titan.chat.model=" + TitanChatModel.TITAN_TEXT_EXPRESS_V1.id(), "spring.ai.bedrock.titan.chat.options.temperature=0.5", "spring.ai.bedrock.titan.chat.options.maxTokenCount=500") .withConfiguration(AutoConfigurations.of(BedrockTitanChatAutoConfiguration.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 -> { BedrockTitanChatClient chatClient = context.getBean(BedrockTitanChatClient.class); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage, systemMessage))); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); }); } @Test public void chatCompletionStreaming() { contextRunner.run(context -> { BedrockTitanChatClient chatClient = context.getBean(BedrockTitanChatClient.class); Flux<ChatResponse> response = chatClient.stream(new Prompt(List.of(userMessage, systemMessage))); List<ChatResponse> responses = response.collectList().block(); assertThat(responses.size()).isGreaterThan(1); 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.titan.chat.enabled=true", "spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY", "spring.ai.bedrock.titan.chat.model=MODEL_XYZ", "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), "spring.ai.bedrock.titan.chat.options.temperature=0.55", "spring.ai.bedrock.titan.chat.options.topP=0.55", "spring.ai.bedrock.titan.chat.options.stopSequences=END1,END2", "spring.ai.bedrock.titan.chat.options.maxTokenCount=123") .withConfiguration(AutoConfigurations.of(BedrockTitanChatAutoConfiguration.class)) .run(context -> { var chatProperties = context.getBean(BedrockTitanChatProperties.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().getStopSequences()).isEqualTo(List.of("END1", "END2")); assertThat(chatProperties.getOptions().getMaxTokenCount()).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(BedrockTitanChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockTitanChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockTitanChatClient.class)).isEmpty(); }); // Explicitly enable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.titan.chat.enabled=true") .withConfiguration(AutoConfigurations.of(BedrockTitanChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockTitanChatProperties.class)).isNotEmpty(); assertThat(context.getBeansOfType(BedrockTitanChatClient.class)).isNotEmpty(); }); // Explicitly disable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.titan.chat.enabled=false") .withConfiguration(AutoConfigurations.of(BedrockTitanChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockTitanChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockTitanChatClient.class)).isEmpty(); }); } }
[ "org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id" ]
[((2381, 2402), 'software.amazon.awssdk.regions.Region.US_EAST_1.id'), ((2448, 2489), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id'), ((4578, 4602), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((5221, 5245), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.weaviate; 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.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig.MetadataField; 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 WeaviateVectorStoreAutoConfigurationTests { @Container static GenericContainer<?> weaviateContainer = new GenericContainer<>("semitechnologies/weaviate:1.22.4") .withEnv("AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED", "true") .withEnv("PERSISTENCE_DATA_PATH", "/var/lib/weaviate") .withEnv("QUERY_DEFAULTS_LIMIT", "25") .withEnv("DEFAULT_VECTORIZER_MODULE", "none") .withEnv("CLUSTER_HOSTNAME", "node1") .withExposedPorts(8080); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WeaviateVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.weaviate.scheme=http", "spring.ai.vectorstore.weaviate.host=localhost:" + weaviateContainer.getMappedPort(8080), "spring.ai.vectorstore.weaviate.filter-field.country=TEXT", "spring.ai.vectorstore.weaviate.filter-field.year=NUMBER", "spring.ai.vectorstore.weaviate.filter-field.active=BOOLEAN", "spring.ai.vectorstore.weaviate.filter-field.price=NUMBER"); @Test public void addAndSearchWithFilters() { contextRunner.run(context -> { WeaviateVectorStoreProperties properties = context.getBean(WeaviateVectorStoreProperties.class); assertThat(properties.getFilterField()).hasSize(4); assertThat(properties.getFilterField().get("country")).isEqualTo(MetadataField.Type.TEXT); assertThat(properties.getFilterField().get("year")).isEqualTo(MetadataField.Type.NUMBER); assertThat(properties.getFilterField().get("active")).isEqualTo(MetadataField.Type.BOOLEAN); assertThat(properties.getFilterField().get("price")).isEqualTo(MetadataField.Type.NUMBER); VectorStore vectorStore = context.getBean(VectorStore.class); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Bulgaria", "price", 3.14, "active", true, "year", 2020)); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Netherlands", "price", 1.57, "active", false, "year", 2023)); vectorStore.add(List.of(bgDocument, nlDocument)); var request = SearchRequest.query("The World").withTopK(5); List<Document> results = vectorStore.similaritySearch(request); assertThat(results).hasSize(2); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("country == 'Bulgaria'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("country == 'Netherlands'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("price > 1.57 && active == true")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("year in [2020, 2023]")); assertThat(results).hasSize(2); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("year > 2020 && year <= 2023")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); // Remove all documents from the store vectorStore.delete(List.of(bgDocument, nlDocument).stream().map(doc -> doc.getId()).toList()); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3887, 3931), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((5237, 5310), 'java.util.List.of'), ((5237, 5301), 'java.util.List.of'), ((5237, 5277), 'java.util.List.of')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.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.FunctionCallbackWrapper; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+") @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+") public class FunctionCallWithPromptFunctionIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithPromptFunctionIT.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)); @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, in Paris and in Tokyo? Use Multi-turn function calling."); var promptOptions = AzureOpenAiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("CurrentWeatherService") .withDescription("Get the weather in location") .build())) .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } }
[ "org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder" ]
[((2627, 2879), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2627, 2865), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2696, 2863), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2696, 2848), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((2696, 2794), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.audio.api; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest; import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest; import org.springframework.ai.openai.api.OpenAiAudioApi.StructuredResponse; import org.springframework.ai.openai.api.OpenAiAudioApi.TranslationRequest; import org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.Voice; import org.springframework.ai.openai.api.OpenAiAudioApi.TtsModel; import org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") public class OpenAiAudioApiIT { OpenAiAudioApi audioApi = new OpenAiAudioApi(System.getenv("OPENAI_API_KEY")); @SuppressWarnings("null") @Test void speechTranscriptionAndTranslation() throws IOException { byte[] speech = audioApi .createSpeech(SpeechRequest.builder() .withModel(TtsModel.TTS_1_HD.getValue()) .withInput("Hello, my name is Chris and I love Spring A.I.") .withVoice(Voice.ONYX) .build()) .getBody(); assertThat(speech).isNotEmpty(); FileCopyUtils.copy(speech, new File("target/speech.mp3")); StructuredResponse translation = audioApi .createTranslation( TranslationRequest.builder().withModel(WhisperModel.WHISPER_1.getValue()).withFile(speech).build(), StructuredResponse.class) .getBody(); assertThat(translation.text().replaceAll(",", "")).isEqualTo("Hello my name is Chris and I love Spring AI."); StructuredResponse transcriptionEnglish = audioApi.createTranscription( TranscriptionRequest.builder().withModel(WhisperModel.WHISPER_1.getValue()).withFile(speech).build(), StructuredResponse.class) .getBody(); assertThat(transcriptionEnglish.text().replaceAll(",", "")) .isEqualTo("Hello my name is Chris and I love Spring AI."); StructuredResponse transcriptionDutch = audioApi .createTranscription(TranscriptionRequest.builder().withFile(speech).withLanguage("nl").build(), StructuredResponse.class) .getBody(); assertThat(transcriptionDutch.text()).isEqualTo("Hallo, mijn naam is Chris en ik hou van Spring AI."); } }
[ "org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel.WHISPER_1.getValue", "org.springframework.ai.openai.api.OpenAiAudioApi.TranslationRequest.builder", "org.springframework.ai.openai.api.OpenAiAudioApi.TtsModel.TTS_1_HD.getValue", "org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder", "org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder" ]
[((1866, 2039), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((1866, 2026), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((1866, 1999), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((1866, 1934), 'org.springframework.ai.openai.api.OpenAiAudioApi.SpeechRequest.builder'), ((1905, 1933), 'org.springframework.ai.openai.api.OpenAiAudioApi.TtsModel.TTS_1_HD.getValue'), ((2227, 2325), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranslationRequest.builder'), ((2227, 2317), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranslationRequest.builder'), ((2227, 2300), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranslationRequest.builder'), ((2266, 2299), 'org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel.WHISPER_1.getValue'), ((2565, 2665), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((2565, 2657), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((2565, 2640), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((2606, 2639), 'org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel.WHISPER_1.getValue'), ((2914, 2988), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((2914, 2980), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder'), ((2914, 2961), 'org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.llama2; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel; import org.springframework.ai.chat.prompt.Prompt; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class BedrockLlama2CreateRequestTests { private Llama2ChatBedrockApi api = new Llama2ChatBedrockApi(Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); @Test public void createRequestWithChatOptions() { var client = new BedrockLlama2ChatClient(api, BedrockLlama2ChatOptions.builder().withTemperature(66.6f).withMaxGenLen(666).withTopP(0.66f).build()); var request = client.createRequest(new Prompt("Test message content")); assertThat(request.prompt()).isNotEmpty(); assertThat(request.temperature()).isEqualTo(66.6f); assertThat(request.topP()).isEqualTo(0.66f); assertThat(request.maxGenLen()).isEqualTo(666); request = client.createRequest(new Prompt("Test message content", BedrockLlama2ChatOptions.builder().withTemperature(99.9f).withMaxGenLen(999).withTopP(0.99f).build())); assertThat(request.prompt()).isNotEmpty(); assertThat(request.temperature()).isEqualTo(99.9f); assertThat(request.topP()).isEqualTo(0.99f); assertThat(request.maxGenLen()).isEqualTo(999); } }
[ "org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id" ]
[((1301, 1340), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id'), ((1394, 1415), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.mistralai; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.util.StringUtils; @SpringBootConfiguration public class MistralAiTestConfiguration { @Bean public MistralAiApi mistralAiApi() { var apiKey = System.getenv("MISTRAL_AI_API_KEY"); if (!StringUtils.hasText(apiKey)) { throw new IllegalArgumentException( "Missing MISTRAL_AI_API_KEY environment variable. Please set it to your Mistral AI API key."); } return new MistralAiApi(apiKey); } @Bean public EmbeddingClient mistralAiEmbeddingClient(MistralAiApi api) { return new MistralAiEmbeddingClient(api, MistralAiEmbeddingOptions.builder().withModel(MistralAiApi.EmbeddingModel.EMBED.getValue()).build()); } @Bean public MistralAiChatClient mistralAiChatClient(MistralAiApi mistralAiApi) { return new MistralAiChatClient(mistralAiApi, MistralAiChatOptions.builder().withModel(MistralAiApi.ChatModel.MIXTRAL.getValue()).build()); } }
[ "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.MIXTRAL.getValue", "org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue" ]
[((1486, 1530), 'org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue'), ((1722, 1763), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.MIXTRAL.getValue')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.anthropic3; 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; 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.Media; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.ai.parser.ListOutputParser; import org.springframework.ai.parser.MapOutputParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.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.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.MimeTypeUtils; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") class BedrockAnthropic3ChatClientIT { private static final Logger logger = LoggerFactory.getLogger(BedrockAnthropic3ChatClientIT.class); @Autowired private BedrockAnthropic3ChatClient client; @Value("classpath:/prompts/system-message.st") private Resource systemResource; @Test void roleTest() { UserMessage userMessage = new UserMessage( "Tell me about 3 famous pirates from the Golden Age of Piracy and why they did."); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource); Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Bob", "voice", "pirate")); Prompt prompt = new Prompt(List.of(userMessage, systemMessage)); ChatResponse response = client.call(prompt); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); } @Test void outputParser() { DefaultConversionService conversionService = new DefaultConversionService(); ListOutputParser outputParser = new ListOutputParser(conversionService); String format = outputParser.getFormat(); String template = """ List five {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "ice cream flavors.", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = this.client.call(prompt).getResult(); List<String> list = outputParser.parse(generation.getOutput().getContent()); assertThat(list).hasSize(5); } @Test void mapOutputParser() { MapOutputParser outputParser = new MapOutputParser(); String format = outputParser.getFormat(); String template = """ Provide me a List of {subject} {format} Remove the ```json code blocks from the output. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); Map<String, Object> result = outputParser.parse(generation.getOutput().getContent()); assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); } record ActorsFilmsRecord(String actor, List<String> movies) { } @Test void beanOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. Remove non JSON tex blocks from the output. {format} Provide your answer in the JSON format with the feature names as the keys. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent()); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Test void beanStreamOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove Markdown code blocks from the output. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); String generationTextFromStream = client.stream(prompt) .collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream); logger.info("" + actorsFilms); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Test void multiModalityTest() throws IOException { byte[] imageData = new ClassPathResource("/test.png").getContentAsByteArray(); var userMessage = new UserMessage("Explain what do you see o this picture?", List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData))); ChatResponse response = client.call(new Prompt(List.of(userMessage))); logger.info(response.getResult().getOutput().getContent()); assertThat(response.getResult().getOutput().getContent()).contains("bananas", "apple", "basket"); } @SpringBootConfiguration public static class TestConfiguration { @Bean public Anthropic3ChatBedrockApi anthropicApi() { return new Anthropic3ChatBedrockApi(Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V3_SONNET.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); } @Bean public BedrockAnthropic3ChatClient anthropicChatClient(Anthropic3ChatBedrockApi anthropicApi) { return new BedrockAnthropic3ChatClient(anthropicApi); } } }
[ "org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V3_SONNET.id" ]
[((7441, 7506), 'org.springframework.ai.bedrock.anthropic3.api.Anthropic3ChatBedrockApi.AnthropicChatModel.CLAUDE_V3_SONNET.id'), ((7562, 7583), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
package org.springframework.ai.memory; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.MessageType; import org.springframework.ai.chat.messages.UserMessage; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ConversationBufferMemory implements Memory { private String humanPrefix = MessageType.USER.getValue(); private String aiPrefix = MessageType.ASSISTANT.getValue(); private List<Message> messages = new ArrayList<>(); private String memoryKey = "history"; public void setMemoryKey(String memoryKey) { this.memoryKey = memoryKey; } @Override public List<String> getKeys() { return List.of(memoryKey); } public List<Message> getMessages() { return messages; } @Override public Map<String, Object> load(Map<String, Object> inputs) { return Map.of(memoryKey, getBufferAsString()); } @Override public void save(Map<String, Object> inputs, Map<String, Object> outputs) { String promptInputKey = inputs.keySet().iterator().next(); messages.add(new UserMessage(inputs.get(promptInputKey).toString())); String promptOutputKey = outputs.keySet().iterator().next(); messages.add(new AssistantMessage(outputs.get(promptOutputKey).toString())); } public void clear() { messages.clear(); } private String getBufferAsString() { List<String> stringMessages = new ArrayList<>(); getMessages().forEach(message -> { String role = message.getMessageType().getValue(); if (role.equals(MessageType.USER.getValue())) { role = humanPrefix; } else if (role.equals(MessageType.ASSISTANT.getValue())) { role = aiPrefix; } stringMessages.add(String.format("%s: %s", role, message.getContent())); }); return String.join("\n", stringMessages); } }
[ "org.springframework.ai.chat.messages.MessageType.USER.getValue", "org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue" ]
[((433, 460), 'org.springframework.ai.chat.messages.MessageType.USER.getValue'), ((490, 522), 'org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue'), ((1578, 1605), 'org.springframework.ai.chat.messages.MessageType.USER.getValue'), ((1663, 1695), 'org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue')]
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package services.web; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.parser.BeanOutputParser; import org.springframework.ai.vertexai.gemini.MimeTypeDetector; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Description; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.fasterxml.jackson.annotation.JsonClassDescription; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonInclude.Include; import reactor.core.publisher.Flux; import services.actuator.StartupCheck; import services.ai.VertexAIClient; import services.ai.VertexModels; import services.domain.BooksService; import services.domain.CloudStorageService; import services.domain.FirestoreService; import services.web.data.BookRequest; @RestController @RequestMapping("/geminianalysis") public class BookAnalysisGeminiController { private static final Logger logger = LoggerFactory.getLogger(BookAnalysisGeminiController.class); private final FirestoreService eventService; private BooksService booksService; private VertexAIClient vertexAIClient; private Environment environment; private CloudStorageService cloudStorageService; private VertexAiGeminiChatClient chatSpringClient; @Value("${prompts.bookanalysis}") private String prompt; public BookAnalysisGeminiController(FirestoreService eventService, BooksService booksService, VertexAIClient vertexAIClient, Environment environment, CloudStorageService cloudStorageService, VertexAiGeminiChatClient chatSpringClient) { this.eventService = eventService; this.booksService = booksService; this.vertexAIClient = vertexAIClient; this.environment = environment; this.cloudStorageService = cloudStorageService; this.chatSpringClient = chatSpringClient; } @PostConstruct public void init() { logger.info("BookImagesApplication: BookAnalysisController Post Construct Initializer " + new SimpleDateFormat("HH:mm:ss.SSS").format(new Date(System.currentTimeMillis()))); logger.info("BookImagesApplication: BookAnalysisController Post Construct - StartupCheck can be enabled"); StartupCheck.up(); } @PostMapping("") public ResponseEntity<String> processUserRequest(@RequestBody BookRequest bookRequest, @RequestParam(name = "contentCharactersLimit", defaultValue = "6000") Integer contentCharactersLimit) throws IOException{ long start = System.currentTimeMillis(); prompt = "Extract the main ideas from the book The Jungle Book by Rudyard Kipling"; ChatResponse chatResponse = chatSpringClient.call(new Prompt(prompt, VertexAiGeminiChatOptions.builder() .withTemperature(0.4f) .withModel(VertexModels.GEMINI_PRO) .build()) ); System.out.println("Elapsed time: " + (System.currentTimeMillis() - start) + "ms"); System.out.println("SYNC RESPONSE: " + chatResponse.getResult().getOutput().getContent()); System.out.println("Starting ASYNC call..."); Flux<ChatResponse> flux = chatSpringClient.stream(new Prompt(prompt)); String fluxResponse = flux.collectList().block().stream().map(r -> r.getResult().getOutput().getContent()) .collect(Collectors.joining()); System.out.println("ASYNC RESPONSE: " + fluxResponse); String imageURL = "gs://library_next24_images/TheJungleBook.jpg"; var multiModalUserMessage = new UserMessage("Extract the author and title from the book cover. Return the response as a Map, remove the markdown annotations", List.of(new MediaData(MimeTypeDetector.getMimeType(imageURL), imageURL))); ChatResponse multiModalResponse = chatSpringClient.call(new Prompt(List.of(multiModalUserMessage), VertexAiGeminiChatOptions.builder().withModel(VertexModels.GEMINI_PRO_VISION).build())); System.out.println("MULTI-MODAL RESPONSE: " + multiModalResponse.getResult().getOutput().getContent()); String response = removeMarkdownTags(multiModalResponse.getResult().getOutput().getContent()); System.out.println("Response without Markdown: " + response); var outputParser = new BeanOutputParser<>(BookData.class); BookData bookData = outputParser.parse(response); System.out.println("Book title: " + bookData.title()); System.out.println("Book author: " + bookData.author()); // 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 = chatSpringClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("weatherInfo").build())); System.out.println("WEATHER RESPONSE: " + weatherResponse.getResult().getOutput().getContent()); return new ResponseEntity<String>(chatResponse.getResult().getOutput().getContent(), HttpStatus.OK); } /* //----------------------- // @PostMapping("") // public ResponseEntity<String> processUserRequest(@RequestBody BookRequest bookRequest, // @RequestParam(name = "contentCharactersLimit", defaultValue = "6000") Integer contentCharactersLimit) throws IOException{ // ChatLanguageModel visionModel = VertexAiGeminiChatModel.builder() // .project(CloudConfig.projectID) // .location(CloudConfig.zone) // .modelName("gemini-pro-vision") // .build(); // // byte[] image = cloudStorageService.readFileAsByteString("library_next24_images", "TheJungleBook.jpg"); // UserMessage userMessage = UserMessage.from( // // ImageContent.from(Base64.getEncoder().encodeToString(image)), // ImageContent.from("gs://vision-optimize-serverless-apps/TheJungleBook.jpg"), // TextContent.from("Extract the author and title from the book cover, return as map, remove all markdown annotations") // ); // // when // Response<AiMessage> response = visionModel.generate(userMessage); // String outputString = response.content().text(); // System.out.println(outputString); // return new ResponseEntity<String>(outputString, HttpStatus.OK); // } */ public static String removeMarkdownTags(String text) { // String response = text.replaceAll("```json", " "); // return response = response.replaceAll("```", " "); return text.replaceAll("```json", "").replaceAll("```", "").replace("'", "\""); } public record BookData(String author, String title) { } @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); } } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder" ]
[((4473, 4750), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4473, 4683), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((4473, 4589), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5724, 5809), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((5724, 5801), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((6822, 6893), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((6822, 6885), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder')]
package com.demo.stl.aijokes.ask; import com.demo.stl.aijokes.JokeController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.openai.OpenAiEmbeddingClient; import org.springframework.ai.openai.OpenAiEmbeddingOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.reader.tika.TikaDocumentReader; import org.springframework.ai.transformer.splitter.TextSplitter; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.PathResource; import org.springframework.core.io.Resource; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; @Configuration public class Config { Logger logger = LoggerFactory.getLogger(Config.class); @Value("${app.vectorstore.path:/tmp/vectorstore.json}") private String vectorStorePath; @Value("${app.documentResource}") private String documentResource; @Value("${spring.ai.openai.api-key}") private String OPENAI_API_KEY; @Value("${app.documentResource}") private Resource resource; @Bean public EmbeddingClient embeddingClient(){ OpenAiApi openAiApi = new OpenAiApi(OPENAI_API_KEY); return new OpenAiEmbeddingClient(openAiApi) .withDefaultOptions(OpenAiEmbeddingOptions.builder().withModel("text-embedding-3-small").build()); } @Bean public SimpleVectorStore simpleVectorStore(EmbeddingClient embeddingClient) throws IOException, URISyntaxException { SimpleVectorStore simpleVectorStore = new SimpleVectorStore(embeddingClient); File vectorStoreFile = new File (vectorStorePath); resource.getFilename(); if (vectorStoreFile.exists()){ logger.info("vectorStoreFile exists, reusing existing " + vectorStoreFile.getAbsolutePath()); simpleVectorStore.load(vectorStoreFile); }else { logger.info("generating new vectorStoreFile from resource " + resource.getURI()); TikaDocumentReader documentReader = new TikaDocumentReader(resource); List<Document> documents = documentReader.get(); TextSplitter textSplitter = new TokenTextSplitter(); List<Document> splitDocuments = textSplitter.apply(documents); simpleVectorStore.add(splitDocuments); simpleVectorStore.save(vectorStoreFile); } return simpleVectorStore; } }
[ "org.springframework.ai.openai.OpenAiEmbeddingOptions.builder" ]
[((1695, 1771), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((1695, 1763), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder')]
package com.example.springbootaiintegration.mongoRepos.dtos; import lombok.Data; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.MessageType; import org.springframework.ai.chat.messages.UserMessage; @Data public class MessageDto { private String content; private String type; public MessageDto() { } public MessageDto(Message message) { this.content = message.getContent(); this.type = message.getMessageType().getValue(); } public MessageDto(String content, String type) { this.content = content; this.type = type; } public MessageDto(String response) { this.content = response; this.type = MessageType.ASSISTANT.getValue(); } public Message convert() { if (type.equals(MessageType.USER.getValue())) { return new UserMessage(this.content); } return new AssistantMessage(this.content); } }
[ "org.springframework.ai.chat.messages.MessageType.USER.getValue", "org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue" ]
[((793, 825), 'org.springframework.ai.chat.messages.MessageType.ASSISTANT.getValue'), ((889, 916), 'org.springframework.ai.chat.messages.MessageType.USER.getValue')]
package com.example.thehealingmeal.gpt; import com.example.thehealingmeal.gpt.dto.AiResDto; import com.example.thehealingmeal.gpt.responseRepository.GPTResponse; import com.example.thehealingmeal.gpt.responseRepository.ResponseRepository; import com.example.thehealingmeal.member.domain.User; import com.example.thehealingmeal.member.repository.UserRepository; import com.example.thehealingmeal.menu.api.dto.MenuResponseDto; import com.example.thehealingmeal.menu.api.dto.SnackOrTeaResponseDto; import com.example.thehealingmeal.menu.domain.Meals; import com.example.thehealingmeal.menu.service.MenuProvider; import lombok.RequiredArgsConstructor; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @RequiredArgsConstructor public class GPTService { private final ChatClient chatClient; private final MenuProvider menuProvider; private final UserRepository userRepository; private final ResponseRepository responseRepository; private ChatResponse callChat(String menu) { return chatClient.call( new Prompt( menu + "을 먹는다고 했을 때 섭취하는 사람에게 어떤 효능이 있을까? 위 아래 문단의 잡설은 하지 말고, 각 음식에 대해 번호 리스트로 짧은 분량의 내용을 보여줘.", OpenAiChatOptions.builder() .withTemperature(0.4F) .withFrequencyPenalty(0.7F) .withModel("gpt-3.5-turbo") .build() )); } //request answer to openai. public AiResDto getAnswer(long user_id, Meals meals) { MenuResponseDto menu = menuProvider.provide(user_id, meals); List<String> names = List.of(menu.getMain_dish(), menu.getRice(), menu.getSideDishForUserMenu().toString()); StringBuilder sentence = new StringBuilder(); for (String name : names) { sentence.append(name); if (names.iterator().hasNext()) { sentence.append(", "); } } ChatResponse response = callChat(sentence.toString()); if (response == null) { response = callChat(sentence.toString()); } return new AiResDto(response.getResult().getOutput().getContent()); } public AiResDto getAnswerSnackOrTea(long user_id, Meals meals) { SnackOrTeaResponseDto menu = menuProvider.provideSnackOrTea(user_id, meals); String multiChat = callChat(menu.getSnack_or_tea()).getResult().getOutput().getContent(); if (multiChat == null || multiChat.isBlank() || multiChat.isEmpty()) { multiChat = callChat(menu.getSnack_or_tea()).getResult().getOutput().getContent(); } return new AiResDto(multiChat); } @Transactional public void saveResponse(String response, long user_id, Meals meals) { User id = userRepository.findById(user_id).orElseThrow(() -> new IllegalArgumentException("Not Found User Data In Database.")); GPTResponse gptResponse = GPTResponse.builder() .gptAnswer(response) .user(id) .meals(meals) .build(); responseRepository.save(gptResponse); } @Transactional(readOnly = true) public AiResDto provideResponse(long user_id, Meals meals) { try { GPTResponse gptResponse = responseRepository.findByMealsAndUserId(meals, user_id); return new AiResDto(gptResponse.getGptAnswer()); } catch (Exception e) { throw new IllegalArgumentException("Not Found Response Data In Database."); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((1615, 1858), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1615, 1817), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1615, 1757), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1615, 1697), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3387, 3526), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder'), ((3387, 3501), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder'), ((3387, 3471), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder'), ((3387, 3445), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder')]
/** * Authored by jayxu @2023 */ package com.jayxu.playground.spring.mvc; import java.util.Collections; import java.util.List; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.OpenAiImageClient; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.jayxu.openai4j.OpenAiService; import com.jayxu.openai4j.model.Model; import com.jayxu.openai4j.model.ModelList; import lombok.SneakyThrows; import reactor.core.publisher.Flux; /** * @author jayxu */ @RestController @RequestMapping("/openai") public class OpenAiController { @Autowired private OpenAiService service; @Autowired private OpenAiChatClient client; @Autowired private OpenAiImageClient imageClient; @GetMapping("/models") @SneakyThrows public List<String> getModels() { ModelList body = this.service.listModels().execute().body(); return body == null ? Collections.EMPTY_LIST : body.getData().stream().map(Model::getId).sorted().toList(); } @SneakyThrows @PostMapping(path = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> createChat(@RequestBody String prompt, @RequestParam ModelType model, @RequestParam(defaultValue = "false") boolean stream) { var p = new Prompt(prompt, OpenAiChatOptions.builder().withModel(model.value()).build()); if (stream) { return this.client.stream(p) .mapNotNull(r -> r.getResult().getOutput().getContent()); } return Flux .just(this.client.call(p).getResult().getOutput().getContent()); } // @SneakyThrows // @PostMapping(path = "/completions", // produces = MediaType.TEXT_EVENT_STREAM_VALUE) // public Flux<String> createCompletions(@RequestBody List<String> prompt, // @RequestParam ModelType model, // @RequestParam(defaultValue = "false") boolean stream) { // var req = CompletionRequest.builder().model(model.value()) // .prompt(prompt).stream(stream).build(); // // if (stream) { // return this.streamService.createCompletions(req) // .mapNotNull(r -> r.getChoices().get(0).getText()); // } // // CompletionResponse body = this.service.createCompletions(req).execute() // .body(); // return body == null ? Flux.empty() // : Flux.just(body.getChoices().get(0).getText()); // } @SneakyThrows @PostMapping("/image/create") public Flux<String> createImage(@RequestBody String prompt, @RequestParam ModelType model, @RequestParam(defaultValue = "1024") int width, @RequestParam(defaultValue = "1024") int height, @RequestParam(defaultValue = "natural") String style, @RequestParam(defaultValue = "1") int n) { var p = new ImagePrompt(prompt, OpenAiImageOptions.builder().withModel(model.value()) .withHeight(height).withWidth(width).withQuality("hd") .withStyle(style).withN(n).build()); ImageResponse body = this.imageClient.call(p); return body == null ? Flux.empty() : Flux.fromStream(body.getResults().stream()) .mapNotNull(r -> r.getOutput().getUrl()); } enum ModelType { GPT_35_TURBO("gpt-3.5-turbo"), TEXT_DAVINCI_003("text-davinci-003"), DALL_E_2("dall-e-2"), DALL_E_3("dall-e-3"); private final String value; ModelType(String value) { this.value = value; } public String value() { return this.value; } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((2033, 2093), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2033, 2085), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3636, 3811), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((3636, 3803), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((3636, 3794), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((3636, 3760), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((3636, 3742), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((3636, 3725), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((3636, 3689), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((3926, 4026), 'reactor.core.publisher.Flux.fromStream')]
/* * 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.List; import reactor.core.publisher.Flux; import org.springframework.ai.bedrock.MessageToPromptConverter; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatResponse; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.prompt.ChatOptions; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.StreamingChatClient; import org.springframework.ai.chat.metadata.ChatGenerationMetadata; import org.springframework.ai.chat.metadata.Usage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.util.Assert; /** * Java {@link ChatClient} and {@link StreamingChatClient} for the Bedrock Llama2 chat * generative. * * @author Christian Tzolov * @since 0.8.0 */ public class BedrockLlama2ChatClient implements ChatClient, StreamingChatClient { private final Llama2ChatBedrockApi chatApi; private final BedrockLlama2ChatOptions defaultOptions; public BedrockLlama2ChatClient(Llama2ChatBedrockApi chatApi) { this(chatApi, BedrockLlama2ChatOptions.builder().withTemperature(0.8f).withTopP(0.9f).withMaxGenLen(100).build()); } public BedrockLlama2ChatClient(Llama2ChatBedrockApi chatApi, BedrockLlama2ChatOptions options) { Assert.notNull(chatApi, "Llama2ChatBedrockApi must not be null"); Assert.notNull(options, "BedrockLlama2ChatOptions must not be null"); this.chatApi = chatApi; this.defaultOptions = options; } @Override public ChatResponse call(Prompt prompt) { var request = createRequest(prompt); Llama2ChatResponse response = this.chatApi.chatCompletion(request); return new ChatResponse(List.of(new Generation(response.generation()).withGenerationMetadata( ChatGenerationMetadata.from(response.stopReason().name(), extractUsage(response))))); } @Override public Flux<ChatResponse> stream(Prompt prompt) { var request = createRequest(prompt); Flux<Llama2ChatResponse> fluxResponse = this.chatApi.chatCompletionStream(request); return fluxResponse.map(response -> { String stopReason = response.stopReason() != null ? response.stopReason().name() : null; return new ChatResponse(List.of(new Generation(response.generation()) .withGenerationMetadata(ChatGenerationMetadata.from(stopReason, extractUsage(response))))); }); } private Usage extractUsage(Llama2ChatResponse response) { return new Usage() { @Override public Long getPromptTokens() { return response.promptTokenCount().longValue(); } @Override public Long getGenerationTokens() { return response.generationTokenCount().longValue(); } }; } /** * Accessible for testing. */ Llama2ChatRequest createRequest(Prompt prompt) { final String promptValue = MessageToPromptConverter.create().toPrompt(prompt.getInstructions()); Llama2ChatRequest request = Llama2ChatRequest.builder(promptValue).build(); if (this.defaultOptions != null) { request = ModelOptionsUtils.merge(request, this.defaultOptions, Llama2ChatRequest.class); } if (prompt.getOptions() != null) { if (prompt.getOptions() instanceof ChatOptions runtimeOptions) { BedrockLlama2ChatOptions updatedRuntimeOptions = ModelOptionsUtils.copyToTarget(runtimeOptions, ChatOptions.class, BedrockLlama2ChatOptions.class); request = ModelOptionsUtils.merge(updatedRuntimeOptions, request, Llama2ChatRequest.class); } else { throw new IllegalArgumentException("Prompt options are not of type ChatOptions: " + prompt.getOptions().getClass().getSimpleName()); } } return request; } }
[ "org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest.builder", "org.springframework.ai.bedrock.MessageToPromptConverter.create" ]
[((3681, 3749), 'org.springframework.ai.bedrock.MessageToPromptConverter.create'), ((3782, 3828), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatRequest.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.postgresml; import java.util.Map; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.postgresml.PostgresMlEmbeddingClient; import org.springframework.ai.postgresml.PostgresMlEmbeddingOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.util.Assert; /** * Configuration properties for Postgres ML. * * @author Utkarsh Srivastava * @author Christian Tzolov */ @ConfigurationProperties(PostgresMlEmbeddingProperties.CONFIG_PREFIX) public class PostgresMlEmbeddingProperties { public static final String CONFIG_PREFIX = "spring.ai.postgresml.embedding"; /** * Enable Postgres ML embedding client. */ private boolean enabled = true; @NestedConfigurationProperty private PostgresMlEmbeddingOptions options = PostgresMlEmbeddingOptions.builder() .withTransformer(PostgresMlEmbeddingClient.DEFAULT_TRANSFORMER_MODEL) .withVectorType(PostgresMlEmbeddingClient.VectorType.PG_ARRAY) .withKwargs(Map.of()) .withMetadataMode(MetadataMode.EMBED) .build(); public PostgresMlEmbeddingOptions getOptions() { return this.options; } public void setOptions(PostgresMlEmbeddingOptions options) { Assert.notNull(options, "options must not be null."); Assert.notNull(options.getTransformer(), "transformer must not be null."); Assert.notNull(options.getVectorType(), "vectorType must not be null."); Assert.notNull(options.getKwargs(), "kwargs must not be null."); Assert.notNull(options.getMetadataMode(), "metadataMode must not be null."); this.options = options; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
[ "org.springframework.ai.postgresml.PostgresMlEmbeddingOptions.builder" ]
[((1557, 1805), 'org.springframework.ai.postgresml.PostgresMlEmbeddingOptions.builder'), ((1557, 1794), 'org.springframework.ai.postgresml.PostgresMlEmbeddingOptions.builder'), ((1557, 1754), 'org.springframework.ai.postgresml.PostgresMlEmbeddingOptions.builder'), ((1557, 1730), 'org.springframework.ai.postgresml.PostgresMlEmbeddingOptions.builder'), ((1557, 1665), 'org.springframework.ai.postgresml.PostgresMlEmbeddingOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.llama2; import org.springframework.ai.bedrock.llama2.BedrockLlama2ChatOptions; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * Configuration properties for Bedrock Llama2. * * @author Christian Tzolov * @since 0.8.0 */ @ConfigurationProperties(BedrockLlama2ChatProperties.CONFIG_PREFIX) public class BedrockLlama2ChatProperties { public static final String CONFIG_PREFIX = "spring.ai.bedrock.llama2.chat"; /** * Enable Bedrock Llama2 chat client. Disabled by default. */ private boolean enabled = false; /** * The generative id to use. See the {@link Llama2ChatModel} for the supported models. */ private String model = Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(); @NestedConfigurationProperty private BedrockLlama2ChatOptions options = BedrockLlama2ChatOptions.builder() .withTemperature(0.7f) .withMaxGenLen(300) .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 BedrockLlama2ChatOptions getOptions() { return this.options; } public void setOptions(BedrockLlama2ChatOptions options) { this.options = options; } }
[ "org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id", "org.springframework.ai.bedrock.llama2.BedrockLlama2ChatOptions.builder" ]
[((1516, 1555), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id'), ((1632, 1724), 'org.springframework.ai.bedrock.llama2.BedrockLlama2ChatOptions.builder'), ((1632, 1713), 'org.springframework.ai.bedrock.llama2.BedrockLlama2ChatOptions.builder'), ((1632, 1691), 'org.springframework.ai.bedrock.llama2.BedrockLlama2ChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.openai; import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; @ConfigurationProperties(OpenAiAudioTranscriptionProperties.CONFIG_PREFIX) public class OpenAiAudioTranscriptionProperties extends OpenAiParentProperties { public static final String CONFIG_PREFIX = "spring.ai.openai.audio.transcription"; public static final String DEFAULT_TRANSCRIPTION_MODEL = OpenAiAudioApi.WhisperModel.WHISPER_1.getValue(); private static final Double DEFAULT_TEMPERATURE = 0.7; private static final OpenAiAudioApi.TranscriptResponseFormat DEFAULT_RESPONSE_FORMAT = OpenAiAudioApi.TranscriptResponseFormat.TEXT; @NestedConfigurationProperty private OpenAiAudioTranscriptionOptions options = OpenAiAudioTranscriptionOptions.builder() .withModel(DEFAULT_TRANSCRIPTION_MODEL) .withTemperature(DEFAULT_TEMPERATURE.floatValue()) .withResponseFormat(DEFAULT_RESPONSE_FORMAT) .build(); public OpenAiAudioTranscriptionOptions getOptions() { return options; } public void setOptions(OpenAiAudioTranscriptionOptions options) { this.options = options; } }
[ "org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder", "org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel.WHISPER_1.getValue" ]
[((1257, 1305), 'org.springframework.ai.openai.api.OpenAiAudioApi.WhisperModel.WHISPER_1.getValue'), ((1581, 1775), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((1581, 1764), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((1581, 1717), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((1581, 1664), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder')]
package biz.lci.springaidemos; import lombok.extern.slf4j.Slf4j; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.reader.JsonReader; import org.springframework.ai.transformer.splitter.TextSplitter; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.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; @Slf4j @Service public class RecommendationService { // 170:00 into Ken Kousen Spring AI O'Reilly video @Value("classpath:/prompts/products-system-message.st") protected Resource systemMessagePrompt; // @Value("classpath:/data/au2.json") @Value("classpath:/data/skus-all-en-us.json") protected Resource productDataJson; @Autowired protected ChatClient chatClient; @Autowired protected EmbeddingClient embeddingClient; public Generation recommend(String message) { log.info("recommend - message={}", message); SimpleVectorStore vectorStore = new SimpleVectorStore(embeddingClient); File productVectorStoreFile = new File("src/main/resources/data/productVectorStore.json"); if(productVectorStoreFile.exists()) { vectorStore.load(productVectorStoreFile); } else { log.debug("loading product json into vector store"); JsonReader jsonReader = new JsonReader(productDataJson, "brand", "sku", "productname", "form", "species", "breedsize", "productdesc", "searchdescription", "feedingguide", "nutrition", "howitworks", "howithelps", "additionalinformation", "ingredients", "productimageurl", "productpageurl", "packagedesc", "packagesize", "packageunits", "superfamily"); List<Document> documents = jsonReader.get(); TextSplitter textSplitter = new TokenTextSplitter(); List<Document> splitDocuments = textSplitter.apply(documents); log.debug("creating embeddings"); vectorStore.add(splitDocuments); log.debug("saving embeddings"); vectorStore.save(productVectorStoreFile); } log.debug("Finding similar documents"); List<Document> similarDocuments = vectorStore.similaritySearch( SearchRequest.query(message).withTopK(11)); log.debug("Found {} similar documents", similarDocuments.size()); similarDocuments.forEach(doc -> log.debug("doc: {}", doc)); Message systemMessage = getSystemMessage(similarDocuments); UserMessage userMessage = new UserMessage(message); log.debug("Asking AI model to reply to question."); Prompt prompt = new Prompt(List.of(userMessage, systemMessage)); log.debug("prompt: {}", prompt); ChatResponse chatResponse = chatClient.call(prompt); log.debug("chatResponse: {}", chatResponse.getResult().toString()); return chatResponse.getResult(); } protected Message getSystemMessage(List<Document> similarDocuments) { String documents = similarDocuments.stream() .map(Document::getContent) .collect(Collectors.joining("\n")); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemMessagePrompt); return systemPromptTemplate.createMessage(Map.of("petFood", documents)); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3386, 3427), '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.vertexai.gemini; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Configuration properties for Vertex AI Gemini Chat. * * @author Christian Tzolov * @since 0.8.0 */ @ConfigurationProperties(VertexAiGeminiChatProperties.CONFIG_PREFIX) public class VertexAiGeminiChatProperties { public static final String CONFIG_PREFIX = "spring.ai.vertex.ai.gemini.chat"; /** * Vertex AI Gemini API generative options. */ private VertexAiGeminiChatOptions options = VertexAiGeminiChatOptions.builder() .withTemperature(0.7f) .withCandidateCount(1) .build(); public VertexAiGeminiChatOptions getOptions() { return this.options; } public void setOptions(VertexAiGeminiChatOptions options) { this.options = options; } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder" ]
[((1236, 1332), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((1236, 1321), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((1236, 1296), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder')]
package org.springframework.ai.aot.test.azure.openai; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonClassDescription; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import reactor.core.publisher.Flux; import org.springframework.ai.azure.openai.AzureOpenAiChatClient; import org.springframework.ai.azure.openai.AzureOpenAiChatOptions; import org.springframework.ai.azure.openai.AzureOpenAiEmbeddingClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Description; import org.springframework.context.annotation.ImportRuntimeHints; @SpringBootApplication @ImportRuntimeHints(AzureOpenaiAotDemoApplication.MockWeatherServiceRuntimeHints.class) public class AzureOpenaiAotDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(AzureOpenaiAotDemoApplication.class) .web(WebApplicationType.NONE) .run(args); } @Bean ApplicationRunner applicationRunner(AzureOpenAiChatClient chatClient, AzureOpenAiEmbeddingClient embeddingClient) { return args -> { System.out.println("ChatClient: " + chatClient.getClass().getName()); System.out.println("EmbeddingClient: " + embeddingClient.getClass().getName()); // Synchronous Chat Client String response = chatClient.call("Tell me a joke."); System.out.println("SYNC RESPONSE: " + response); // Streaming Chat Client Flux<ChatResponse> flux = chatClient.stream(new Prompt("Tell me a joke.")); String fluxResponse = flux.collectList().block().stream().map(r -> r.getResult().getOutput().getContent()) .collect(Collectors.joining()); System.out.println("ASYNC RESPONSE: " + fluxResponse); // Embedding Client System.out.println(embeddingClient.embed("Hello, World!")); List<List<Double>> embeddings = embeddingClient.embed(List.of("Hello", "World")); System.out.println("EMBEDDINGS SIZE: " + embeddings.size()); // Function calling ChatResponse weatherResponse = chatClient.call(new Prompt("What is the weather in Amsterdam, Netherlands?", AzureOpenAiChatOptions.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); } } }
[ "org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder" ]
[((3026, 3094), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3026, 3086), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.cohere; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel; import org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingRequest.InputType; import org.springframework.ai.embedding.EmbeddingRequest; 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 static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") class BedrockCohereEmbeddingClientIT { @Autowired private BedrockCohereEmbeddingClient 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 batchEmbedding() { assertThat(embeddingClient).isNotNull(); EmbeddingResponse embeddingResponse = embeddingClient .embedForResponse(List.of("Hello World", "World is big and salvation is near")); assertThat(embeddingResponse.getResults()).hasSize(2); assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty(); assertThat(embeddingResponse.getResults().get(0).getIndex()).isEqualTo(0); assertThat(embeddingResponse.getResults().get(1).getOutput()).isNotEmpty(); assertThat(embeddingResponse.getResults().get(1).getIndex()).isEqualTo(1); assertThat(embeddingClient.dimensions()).isEqualTo(1024); } @Test void embeddingWthOptions() { assertThat(embeddingClient).isNotNull(); EmbeddingResponse embeddingResponse = embeddingClient .call(new EmbeddingRequest(List.of("Hello World", "World is big and salvation is near"), BedrockCohereEmbeddingOptions.builder().withInputType(InputType.SEARCH_DOCUMENT).build())); assertThat(embeddingResponse.getResults()).hasSize(2); assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty(); assertThat(embeddingResponse.getResults().get(0).getIndex()).isEqualTo(0); assertThat(embeddingResponse.getResults().get(1).getOutput()).isNotEmpty(); assertThat(embeddingResponse.getResults().get(1).getIndex()).isEqualTo(1); assertThat(embeddingClient.dimensions()).isEqualTo(1024); } @SpringBootConfiguration public static class TestConfiguration { @Bean public CohereEmbeddingBedrockApi cohereEmbeddingApi() { return new CohereEmbeddingBedrockApi(CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); } @Bean public BedrockCohereEmbeddingClient cohereAiEmbedding(CohereEmbeddingBedrockApi cohereEmbeddingApi) { return new BedrockCohereEmbeddingClient(cohereEmbeddingApi); } } }
[ "org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id" ]
[((3902, 3956), 'org.springframework.ai.bedrock.cohere.api.CohereEmbeddingBedrockApi.CohereEmbeddingModel.COHERE_EMBED_MULTILINGUAL_V1.id'), ((4012, 4033), '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.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 io.milvus.client.MilvusServiceClient; import io.milvus.param.ConnectParam; import io.milvus.param.IndexType; import io.milvus.param.MetricType; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; 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.openai.OpenAiEmbeddingClient; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.core.io.DefaultResourceLoader; import org.testcontainers.milvus.MilvusContainer; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov * @author Eddú Meléndez */ @Testcontainers @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") public class MilvusVectorStoreIT { @Container private static MilvusContainer milvusContainer = new MilvusContainer("milvusdb/milvus:v2.3.8"); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestApplication.class); List<Document> documents = List.of( new Document(getText("classpath:/test/data/spring.ai.txt"), Map.of("meta1", "meta1")), new Document(getText("classpath:/test/data/time.shelter.txt")), new Document(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 void resetCollection(VectorStore vectorStore) { ((MilvusVectorStore) vectorStore).dropCollection(); ((MilvusVectorStore) vectorStore).createCollection(); } @ParameterizedTest(name = "{0} : {displayName} ") @ValueSource(strings = { "COSINE", "L2", "IP" }) public void addAndSearch(String metricType) { contextRunner.withPropertyValues("test.spring.ai.vectorstore.milvus.metricType=" + metricType).run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); resetCollection(vectorStore); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).hasSize(2); assertThat(resultDoc.getMetadata()).containsKeys("meta1", "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); }); } @ParameterizedTest(name = "{0} : {displayName} ") @ValueSource(strings = { "COSINE" }) // @ValueSource(strings = { "COSINE", "IP", "L2" }) public void searchWithFilters(String metricType) throws InterruptedException { // https://milvus.io/docs/json_data_type.md contextRunner.withPropertyValues("test.spring.ai.vectorstore.milvus.metricType=" + metricType).run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); resetCollection(vectorStore); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2020)); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "NL")); var bgDocument2 = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "BG", "year", 2023)); vectorStore.add(List.of(bgDocument, nlDocument, bgDocument2)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("The World").withTopK(5)); assertThat(results).hasSize(3); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'NL'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG'")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(bgDocument.getId(), bgDocument2.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("country == 'BG' && year == 2020")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch(SearchRequest.query("The World") .withTopK(5) .withSimilarityThresholdAll() .withFilterExpression("NOT(country == 'BG' && year == 2020)")); assertThat(results).hasSize(2); assertThat(results.get(0).getId()).isIn(nlDocument.getId(), bgDocument2.getId()); assertThat(results.get(1).getId()).isIn(nlDocument.getId(), bgDocument2.getId()); }); } @ParameterizedTest(name = "{0} : {displayName} ") @ValueSource(strings = { "COSINE", "L2", "IP" }) public void documentUpdate(String metricType) { contextRunner.withPropertyValues("test.spring.ai.vectorstore.milvus.metricType=" + metricType).run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); resetCollection(vectorStore); Document document = new Document(UUID.randomUUID().toString(), "Spring AI rocks!!", Collections.singletonMap("meta1", "meta1")); vectorStore.add(List.of(document)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("Spring AI rocks!!"); assertThat(resultDoc.getMetadata()).containsKey("meta1"); assertThat(resultDoc.getMetadata()).containsKey("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)); results = vectorStore.similaritySearch(SearchRequest.query("FooBar").withTopK(5)); assertThat(results).hasSize(1); resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("The World is Big and Salvation Lurks Around the Corner"); assertThat(resultDoc.getMetadata()).containsKey("meta2"); assertThat(resultDoc.getMetadata()).containsKey("distance"); vectorStore.delete(List.of(document.getId())); }); } @ParameterizedTest(name = "{0} : {displayName} ") @ValueSource(strings = { "COSINE", "IP" }) public void searchWithThreshold(String metricType) { contextRunner.withPropertyValues("test.spring.ai.vectorstore.milvus.metricType=" + metricType).run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); resetCollection(vectorStore); vectorStore.add(documents); List<Document> fullResult = vectorStore .similaritySearch(SearchRequest.query("Spring").withTopK(5).withSimilarityThresholdAll()); List<Float> distances = fullResult.stream().map(doc -> (Float) doc.getMetadata().get("distance")).toList(); assertThat(distances).hasSize(3); float threshold = (distances.get(0) + distances.get(1)) / 2; List<Document> results = vectorStore .similaritySearch(SearchRequest.query("Spring").withTopK(5).withSimilarityThreshold(1 - threshold)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).containsKeys("meta1", "distance"); }); } @SpringBootConfiguration @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) public static class TestApplication { @Value("${test.spring.ai.vectorstore.milvus.metricType}") private MetricType metricType; @Bean public VectorStore vectorStore(MilvusServiceClient milvusClient, EmbeddingClient embeddingClient) { MilvusVectorStoreConfig config = MilvusVectorStoreConfig.builder() .withCollectionName("test_vector_store") .withDatabaseName("default") .withIndexType(IndexType.IVF_FLAT) .withMetricType(metricType) .build(); return new MilvusVectorStore(milvusClient, embeddingClient, config); } @Bean public MilvusServiceClient milvusClient() { return new MilvusServiceClient(ConnectParam.newBuilder() .withAuthorization("minioadmin", "minioadmin") .withUri(milvusContainer.getEndpoint()) .build()); } @Bean public EmbeddingClient embeddingClient() { return new OpenAiEmbeddingClient(new OpenAiApi(System.getenv("OPENAI_API_KEY"))); // return new OpenAiEmbeddingClient(new // OpenAiApi(System.getenv("OPENAI_API_KEY")), MetadataMode.EMBED, // OpenAiEmbeddingOptions.builder().withModel("text-embedding-ada-002").build()); } } }
[ "org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder" ]
[((7304, 7332), 'java.util.UUID.randomUUID'), ((10268, 10463), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((10268, 10450), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((10268, 10418), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((10268, 10379), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((10268, 10346), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((10630, 10763), 'io.milvus.param.ConnectParam.newBuilder'), ((10630, 10750), 'io.milvus.param.ConnectParam.newBuilder'), ((10630, 10706), 'io.milvus.param.ConnectParam.newBuilder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.audio.transcription; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions; import org.springframework.ai.openai.OpenAiTestConfiguration; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptResponseFormat; import org.springframework.ai.openai.testutils.AbstractIT; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.io.Resource; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = OpenAiTestConfiguration.class) @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") class OpenAiTranscriptionClientIT extends AbstractIT { @Value("classpath:/speech/jfk.flac") private Resource audioFile; @Test void transcriptionTest() { OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder() .withResponseFormat(TranscriptResponseFormat.TEXT) .withTemperature(0f) .build(); AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions); AudioTranscriptionResponse response = openAiTranscriptionClient.call(transcriptionRequest); assertThat(response.getResults()).hasSize(1); assertThat(response.getResults().get(0).getOutput().toLowerCase().contains("fellow")).isTrue(); } @Test void transcriptionTestWithOptions() { OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT; OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder() .withLanguage("en") .withPrompt("Ask not this, but ask that") .withTemperature(0f) .withResponseFormat(responseFormat) .build(); AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions); AudioTranscriptionResponse response = openAiTranscriptionClient.call(transcriptionRequest); assertThat(response.getResults()).hasSize(1); assertThat(response.getResults().get(0).getOutput().toLowerCase().contains("fellow")).isTrue(); } }
[ "org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder" ]
[((1684, 1815), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((1684, 1803), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((1684, 1779), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((2382, 2566), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((2382, 2554), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((2382, 2515), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((2382, 2491), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((2382, 2446), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.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.mistralai.api.tool; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletion; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.Role; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.ToolCall; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest.ToolChoice; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest; import org.springframework.ai.mistralai.api.MistralAiApi.FunctionTool.Type; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.http.ResponseEntity; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".+") @Disabled public class MistralAiApiToolFunctionCallIT { private final Logger logger = LoggerFactory.getLogger(MistralAiApiToolFunctionCallIT.class); MockWeatherService weatherService = new MockWeatherService(); static final String MISTRAL_AI_CHAT_MODEL = MistralAiApi.ChatModel.LARGE.getValue(); MistralAiApi completionApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY")); @Test @SuppressWarnings("null") public void toolFunctionCall() throws JsonProcessingException { // Step 1: send the conversation and available functions to the model var message = new ChatCompletionMessage( "What's the weather like in San Francisco, Tokyo, and Paris? Show the temperature in Celsius.", Role.USER); var functionTool = new MistralAiApi.FunctionTool(Type.FUNCTION, new MistralAiApi.FunctionTool.Function( "Get the weather in location. Return temperature in 30°F or 30°C format.", "getCurrentWeather", ModelOptionsUtils.jsonToMap(""" { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["C", "F"] } }, "required": ["location", "unit"] } """))); // Or you can use the // ModelOptionsUtils.getJsonSchema(FakeWeatherService.Request.class))) to // auto-generate the JSON schema like: // var functionTool = new MistralAiApi.FunctionTool(Type.FUNCTION, new // MistralAiApi.FunctionTool.Function( // "Get the weather in location. Return temperature in 30°F or 30°C format.", // "getCurrentWeather", // ModelOptionsUtils.getJsonSchema(MockWeatherService.Request.class))); List<ChatCompletionMessage> messages = new ArrayList<>(List.of(message)); ChatCompletionRequest chatCompletionRequest = new ChatCompletionRequest(messages, MISTRAL_AI_CHAT_MODEL, List.of(functionTool), ToolChoice.AUTO); System.out .println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(chatCompletionRequest)); ResponseEntity<ChatCompletion> chatCompletion = completionApi.chatCompletionEntity(chatCompletionRequest); assertThat(chatCompletion.getBody()).isNotNull(); assertThat(chatCompletion.getBody().choices()).isNotEmpty(); ChatCompletionMessage responseMessage = chatCompletion.getBody().choices().get(0).message(); assertThat(responseMessage.role()).isEqualTo(Role.ASSISTANT); assertThat(responseMessage.toolCalls()).isNotNull(); // Check if the model wanted to call a function if (responseMessage.toolCalls() != null) { // extend conversation with assistant's reply. messages.add(responseMessage); // Send the info for each function call and function response to the model. for (ToolCall toolCall : responseMessage.toolCalls()) { var functionName = toolCall.function().name(); if ("getCurrentWeather".equals(functionName)) { MockWeatherService.Request weatherRequest = fromJson(toolCall.function().arguments(), MockWeatherService.Request.class); MockWeatherService.Response weatherResponse = weatherService.apply(weatherRequest); // extend conversation with function response. messages.add(new ChatCompletionMessage("" + weatherResponse.temp() + weatherRequest.unit(), Role.TOOL, functionName, null)); } } var functionResponseRequest = new ChatCompletionRequest(messages, MISTRAL_AI_CHAT_MODEL, 0.8f); ResponseEntity<ChatCompletion> chatCompletion2 = completionApi .chatCompletionEntity(functionResponseRequest); logger.info("Final response: " + chatCompletion2.getBody()); assertThat(chatCompletion2.getBody().choices()).isNotEmpty(); assertThat(chatCompletion2.getBody().choices().get(0).message().role()).isEqualTo(Role.ASSISTANT); assertThat(chatCompletion2.getBody().choices().get(0).message().content()).contains("San Francisco") .containsAnyOf("30.0°C", "30°C"); assertThat(chatCompletion2.getBody().choices().get(0).message().content()).contains("Tokyo") .containsAnyOf("10.0°C", "10°C"); ; assertThat(chatCompletion2.getBody().choices().get(0).message().content()).contains("Paris") .containsAnyOf("15.0°C", "15°C"); ; } } private static <T> T fromJson(String json, Class<T> targetClass) { try { return new ObjectMapper().readValue(json, targetClass); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
[ "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue" ]
[((2203, 2242), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.anthropic; import java.util.List; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi; import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel; import org.springframework.ai.chat.prompt.Prompt; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class BedrockAnthropicCreateRequestTests { private AnthropicChatBedrockApi anthropicChatApi = new AnthropicChatBedrockApi(AnthropicChatModel.CLAUDE_V2.id(), Region.EU_CENTRAL_1.id()); @Test public void createRequestWithChatOptions() { var client = new BedrockAnthropicChatClient(anthropicChatApi, AnthropicChatOptions.builder() .withTemperature(66.6f) .withTopK(66) .withTopP(0.66f) .withMaxTokensToSample(666) .withAnthropicVersion("X.Y.Z") .withStopSequences(List.of("stop1", "stop2")) .build()); var request = client.createRequest(new Prompt("Test message content")); assertThat(request.prompt()).isNotEmpty(); assertThat(request.temperature()).isEqualTo(66.6f); assertThat(request.topK()).isEqualTo(66); assertThat(request.topP()).isEqualTo(0.66f); assertThat(request.maxTokensToSample()).isEqualTo(666); assertThat(request.anthropicVersion()).isEqualTo("X.Y.Z"); assertThat(request.stopSequences()).containsExactly("stop1", "stop2"); request = client.createRequest(new Prompt("Test message content", AnthropicChatOptions.builder() .withTemperature(99.9f) .withTopP(0.99f) .withMaxTokensToSample(999) .withAnthropicVersion("zzz") .withStopSequences(List.of("stop3", "stop4")) .build() )); assertThat(request.prompt()).isNotEmpty(); assertThat(request.temperature()).isEqualTo(99.9f); assertThat(request.topK()).as("unchanged from the default options").isEqualTo(66); assertThat(request.topP()).isEqualTo(0.99f); assertThat(request.maxTokensToSample()).isEqualTo(999); assertThat(request.anthropicVersion()).isEqualTo("zzz"); assertThat(request.stopSequences()).containsExactly("stop3", "stop4"); } }
[ "org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id" ]
[((1226, 1259), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((1264, 1288), '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.mistralai.api.tool; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; 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.mistralai.api.MistralAiApi; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletion; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.Role; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionMessage.ToolCall; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest; import org.springframework.ai.mistralai.api.MistralAiApi.ChatCompletionRequest.ToolChoice; import org.springframework.ai.mistralai.api.MistralAiApi.FunctionTool; import org.springframework.ai.mistralai.api.MistralAiApi.FunctionTool.Type; // import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.http.ResponseEntity; import static org.assertj.core.api.Assertions.assertThat; /** * Demonstrates how to use function calling suing Mistral AI Java API: * {@link MistralAiApi}. * * It is based on the <a href="https://docs.mistral.ai/guides/function-calling/">Mistral * AI Function Calling</a> guide. * * @author Christian Tzolov * @since 0.8.1 */ @EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".+") public class PaymentStatusFunctionCallingIT { private final Logger logger = LoggerFactory.getLogger(PaymentStatusFunctionCallingIT.class); // 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) { } 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) { } private static class RetrievePaymentStatus implements Function<Transaction, Status> { @Override public Status apply(Transaction paymentTransaction) { return new Status(DATA.get(paymentTransaction.transactionId).status); } } private static class RetrievePaymentDate implements Function<Transaction, Date> { @Override public Date apply(Transaction paymentTransaction) { return new Date(DATA.get(paymentTransaction.transactionId).date); } } static Map<String, Function<Transaction, ?>> functions = Map.of("retrieve_payment_status", new RetrievePaymentStatus(), "retrieve_payment_date", new RetrievePaymentDate()); @Test @SuppressWarnings("null") public void toolFunctionCall() throws JsonProcessingException { var transactionJsonSchema = """ { "type": "object", "properties": { "transaction_id": { "type": "string", "description": "The transaction id" } }, "required": ["transaction_id"] } """; // Alternatively, generate the JSON schema using the ModelOptionsUtils helper: // // var transactionJsonSchema = ModelOptionsUtils.getJsonSchema(Transaction.class, // false); var paymentStatusTool = new FunctionTool(Type.FUNCTION, new FunctionTool.Function( "Get payment status of a transaction", "retrieve_payment_status", transactionJsonSchema)); var paymentDateTool = new FunctionTool(Type.FUNCTION, new FunctionTool.Function( "Get payment date of a transaction", "retrieve_payment_date", transactionJsonSchema)); List<ChatCompletionMessage> messages = new ArrayList<>( List.of(new ChatCompletionMessage("What's the status of my transaction with id T1001?", Role.USER))); MistralAiApi mistralApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY")); ResponseEntity<ChatCompletion> response = mistralApi.chatCompletionEntity(new ChatCompletionRequest(messages, MistralAiApi.ChatModel.LARGE.getValue(), List.of(paymentStatusTool, paymentDateTool), ToolChoice.AUTO)); ChatCompletionMessage responseMessage = response.getBody().choices().get(0).message(); assertThat(responseMessage.role()).isEqualTo(Role.ASSISTANT); assertThat(responseMessage.toolCalls()).isNotNull(); // extend conversation with assistant's reply. messages.add(responseMessage); // Send the info for each function call and function response to the model. for (ToolCall toolCall : responseMessage.toolCalls()) { var functionName = toolCall.function().name(); // Map the function, JSON arguments into a Transaction object. Transaction transaction = jsonToObject(toolCall.function().arguments(), Transaction.class); // Call the target function with the transaction object. var result = functions.get(functionName).apply(transaction); // Extend conversation with function response. // The functionName is used to identify the function response! messages.add(new ChatCompletionMessage(result.toString(), Role.TOOL, functionName, null)); } response = mistralApi .chatCompletionEntity(new ChatCompletionRequest(messages, MistralAiApi.ChatModel.LARGE.getValue())); var responseContent = response.getBody().choices().get(0).message().content(); logger.info("Final response: " + responseContent); assertThat(responseContent).containsIgnoringCase("T1001"); assertThat(responseContent).containsIgnoringCase("Paid"); } private static <T> T jsonToObject(String json, Class<T> targetClass) { try { return new ObjectMapper().readValue(json, targetClass); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
[ "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue" ]
[((5057, 5096), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue'), ((6229, 6268), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.pgvector; 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.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.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration; 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 */ @Testcontainers public class PgVectorStoreAutoConfigurationIT { @Container static GenericContainer<?> postgresContainer = new GenericContainer<>("ankane/pgvector:v0.5.1") .withEnv("POSTGRES_USER", "postgres") .withEnv("POSTGRES_PASSWORD", "postgres") .withExposedPorts(5432); 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"))); public static String getText(String uri) { var resource = new DefaultResourceLoader().getResource(uri); try { return resource.getContentAsString(StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PgVectorStoreAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.pgvector.distanceType=COSINE_DISTANCE", // JdbcTemplate configuration String.format("spring.datasource.url=jdbc:postgresql://%s:%d/%s", postgresContainer.getHost(), postgresContainer.getMappedPort(5432), "postgres"), "spring.datasource.username=postgres", "spring.datasource.password=postgres"); @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); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3572, 3632), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4021, 4072), '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.milvus; import java.io.File; import java.time.Duration; import java.util.List; import java.util.Map; import java.util.UUID; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.testcontainers.containers.DockerComposeContainer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.junit.jupiter.Testcontainers; 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.springframework.util.FileSystemUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @Testcontainers public class MilvusVectorStoreAutoConfigurationIT { private static DockerComposeContainer milvusContainer; private static final File TEMP_FOLDER = new File("target/test-" + UUID.randomUUID().toString()); 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"))); @BeforeAll public static void beforeAll() { FileSystemUtils.deleteRecursively(TEMP_FOLDER); TEMP_FOLDER.mkdirs(); milvusContainer = new DockerComposeContainer(new File("src/test/resources/milvus/docker-compose.yml")) .withEnv("DOCKER_VOLUME_DIRECTORY", TEMP_FOLDER.getAbsolutePath()) .withExposedService("standalone", 19530) .withExposedService("standalone", 9091, Wait.forHttp("/healthz").forPort(9091).forStatusCode(200).forStatusCode(401)) .waitingFor("standalone", Wait.forLogMessage(".*Proxy successfully started.*\\s", 1) .withStartupTimeout(Duration.ofSeconds(100))); milvusContainer.start(); } @AfterAll public static void afterAll() { milvusContainer.stop(); FileSystemUtils.deleteRecursively(TEMP_FOLDER); } private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MilvusVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test public void addAndSearch() { contextRunner .withPropertyValues("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", "spring.ai.vectorstore.milvus.client.host=" + milvusContainer.getServiceHost("standalone", 19530), "spring.ai.vectorstore.milvus.client.port=" + milvusContainer.getServicePort("standalone", 19530)) .run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).hasSize(2); assertThat(resultDoc.getMetadata()).containsKeys("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) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2021, 2049), 'java.util.UUID.randomUUID'), ((2783, 2859), 'org.testcontainers.containers.wait.strategy.Wait.forHttp'), ((2783, 2840), 'org.testcontainers.containers.wait.strategy.Wait.forHttp'), ((2783, 2821), 'org.testcontainers.containers.wait.strategy.Wait.forHttp'), ((2890, 2997), 'org.testcontainers.containers.wait.strategy.Wait.forLogMessage'), ((4067, 4108), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4705, 4746), '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.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.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 static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*") public class FunctionCallWithPromptFunctionIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithPromptFunctionIT.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)); @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. """); UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, in Paris and in Tokyo?"); var promptOptions = VertexAiGeminiChatOptions.builder() .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("CurrentWeatherService") .withSchemaType(SchemaType.OPEN_API_SCHEMA) // IMPORTANT!! .withDescription("Get the weather in location") .build())) .build(); ChatResponse response = chatClient.call(new Prompt(List.of(systemMessage, userMessage), promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue" ]
[((2504, 2560), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((3049, 3369), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3049, 3355), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3121, 3353), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3121, 3338), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3121, 3269), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3121, 3219), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.titan; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi; import org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel; import org.springframework.ai.chat.prompt.Prompt; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ public class BedrockTitanChatCreateRequestTests { private TitanChatBedrockApi api = new TitanChatBedrockApi(TitanChatModel.TITAN_TEXT_EXPRESS_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); @Test public void createRequestWithChatOptions() { var client = new BedrockTitanChatClient(api, BedrockTitanChatOptions.builder() .withTemperature(66.6f) .withTopP(0.66f) .withMaxTokenCount(666) .withStopSequences(List.of("stop1", "stop2")) .build()); var request = client.createRequest(new Prompt("Test message content")); assertThat(request.inputText()).isNotEmpty(); assertThat(request.textGenerationConfig().temperature()).isEqualTo(66.6f); assertThat(request.textGenerationConfig().topP()).isEqualTo(0.66f); assertThat(request.textGenerationConfig().maxTokenCount()).isEqualTo(666); assertThat(request.textGenerationConfig().stopSequences()).containsExactly("stop1", "stop2"); request = client.createRequest(new Prompt("Test message content", BedrockTitanChatOptions.builder() .withTemperature(99.9f) .withTopP(0.99f) .withMaxTokenCount(999) .withStopSequences(List.of("stop3", "stop4")) .build() )); assertThat(request.inputText()).isNotEmpty(); assertThat(request.textGenerationConfig().temperature()).isEqualTo(99.9f); assertThat(request.textGenerationConfig().topP()).isEqualTo(0.99f); assertThat(request.textGenerationConfig().maxTokenCount()).isEqualTo(999); assertThat(request.textGenerationConfig().stopSequences()).containsExactly("stop3", "stop4"); } }
[ "org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id" ]
[((1320, 1361), 'org.springframework.ai.bedrock.titan.api.TitanChatBedrockApi.TitanChatModel.TITAN_TEXT_EXPRESS_V1.id'), ((1415, 1436), '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.pinecone; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import java.time.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.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.DefaultResourceLoader; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasSize; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "PINECONE_API_KEY", matches = ".+") public class PineconeVectorStoreAutoConfigurationIT { List<Document> documents = List.of( new Document("1", getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document("2", getText("classpath:/test/data/time.shelter.txt"), Map.of()), new Document("3", getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); public static String getText(String uri) { var resource = new DefaultResourceLoader().getResource(uri); try { return resource.getContentAsString(StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PineconeVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.pinecone.apiKey=" + System.getenv("PINECONE_API_KEY"), "spring.ai.vectorstore.pinecone.environment=gcp-starter", "spring.ai.vectorstore.pinecone.projectId=814621f", "spring.ai.vectorstore.pinecone.indexName=spring-ai-test-index"); @BeforeAll public static void beforeAll() { Awaitility.setDefaultPollInterval(2, TimeUnit.SECONDS); Awaitility.setDefaultPollDelay(Duration.ZERO); Awaitility.setDefaultTimeout(Duration.ofMinutes(1)); } @Test public void addAndSearchTest() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); Awaitility.await().until(() -> { return vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); }, hasSize(1)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).hasSize(2); assertThat(resultDoc.getMetadata()).containsKeys("spring", "distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); Awaitility.await().until(() -> { return vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); }, hasSize(0)); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3386, 3520), 'org.awaitility.Awaitility.await'), ((3459, 3500), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3580, 3621), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4169, 4303), 'org.awaitility.Awaitility.await'), ((4242, 4283), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.chat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.OpenAiTestConfiguration; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.api.tool.MockWeatherService; import org.springframework.ai.openai.testutils.AbstractIT; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.ai.parser.ListOutputParser; import org.springframework.ai.parser.MapOutputParser; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.io.Resource; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = OpenAiTestConfiguration.class) @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") class OpenAiChatClientIT extends AbstractIT { private static final Logger logger = LoggerFactory.getLogger(OpenAiChatClientIT.class); @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 = openAiChatClient.call(prompt); assertThat(response.getResults()).hasSize(1); assertThat(response.getResults().get(0).getOutput().getContent()).contains("Blackbeard"); // needs fine tuning... evaluateQuestionAndAnswer(request, response, false); } @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.openAiChatClient.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 = openAiChatClient.call(prompt).getResult(); Map<String, Object> result = outputParser.parse(generation.getOutput().getContent()); assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); } @Test void beanOutputParser() { BeanOutputParser<ActorsFilms> outputParser = new BeanOutputParser<>(ActorsFilms.class); String format = outputParser.getFormat(); String template = """ Generate the filmography for a random actor. {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = openAiChatClient.call(prompt).getResult(); ActorsFilms actorsFilms = outputParser.parse(generation.getOutput().getContent()); } record ActorsFilmsRecord(String actor, List<String> movies) { } @Test void beanOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = openAiChatClient.call(prompt).getResult(); ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent()); logger.info("" + actorsFilms); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Test void beanStreamOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); String generationTextFromStream = openStreamingChatClient.stream(prompt) .collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream); logger.info("" + actorsFilms); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Test void functionCallTest() { UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); List<Message> messages = new ArrayList<>(List.of(userMessage)); var promptOptions = OpenAiChatOptions.builder() .withModel(OpenAiApi.ChatModel.GPT_4_TURBO_PREVIEW.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("getCurrentWeather") .withDescription("Get the weather in location") .withResponseConverter((response) -> "" + response.temp() + response.unit()) .build())) .build(); ChatResponse response = openAiChatClient.call(new Prompt(messages, promptOptions)); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", "10"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15.0", "15"); } @Test void streamFunctionCallTest() { UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); List<Message> messages = new ArrayList<>(List.of(userMessage)); var promptOptions = OpenAiChatOptions.builder() // .withModel(OpenAiApi.ChatModel.GPT_4_TURBO_PREVIEW.getValue()) .withFunctionCallbacks(List.of(FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("getCurrentWeather") .withDescription("Get the weather in location") .withResponseConverter((response) -> "" + response.temp() + response.unit()) .build())) .build(); Flux<ChatResponse> response = openStreamingChatClient.stream(new Prompt(messages, promptOptions)); String content = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", content); assertThat(content).containsAnyOf("30.0", "30"); assertThat(content).containsAnyOf("10.0", "10"); assertThat(content).containsAnyOf("15.0", "15"); } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.openai.api.OpenAiApi.ChatModel.GPT_4_TURBO_PREVIEW.getValue", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder" ]
[((7264, 7644), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((7264, 7632), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((7264, 7357), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((7306, 7356), 'org.springframework.ai.openai.api.OpenAiApi.ChatModel.GPT_4_TURBO_PREVIEW.getValue'), ((7392, 7630), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7392, 7617), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7392, 7536), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((7392, 7484), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8286, 8669), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((8286, 8657), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((8417, 8655), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8417, 8642), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8417, 8561), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((8417, 8509), '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.vectorstore.qdrant; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutionException; import io.qdrant.client.QdrantClient; import io.qdrant.client.QdrantGrpcClient; import io.qdrant.client.grpc.Collections.Distance; import io.qdrant.client.grpc.Collections.VectorParams; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.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.openai.OpenAiEmbeddingClient; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import static org.assertj.core.api.Assertions.assertThat; /** * @author Anush Shetty * @since 0.8.1 */ @Testcontainers public class QdrantVectorStoreIT { private static final String COLLECTION_NAME = "test_collection"; private static final int EMBEDDING_DIMENSION = 1536; 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("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Collections.singletonMap("meta1", "meta1")), new Document("Hello World Hello World Hello World Hello World Hello World Hello World Hello World"), new Document( "Great Depression Great Depression Great Depression Great Depression Great Depression Great Depression", Collections.singletonMap("meta2", "meta2"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(TestApplication.class) .withPropertyValues("spring.ai.openai.apiKey=" + System.getenv("OPENAI_API_KEY")); @BeforeAll static void setup() throws InterruptedException, ExecutionException { String host = qdrantContainer.getHost(); int port = qdrantContainer.getMappedPort(QDRANT_GRPC_PORT); QdrantClient client = new QdrantClient(QdrantGrpcClient.newBuilder(host, port, false).build()); client .createCollectionAsync(COLLECTION_NAME, VectorParams.newBuilder().setDistance(Distance.Cosine).setSize(EMBEDDING_DIMENSION).build()) .get(); client.close(); } @Test public void addAndSearch() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Great").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId()); assertThat(resultDoc.getContent()).isEqualTo( "Great Depression Great Depression Great Depression Great Depression Great Depression Great Depression"); assertThat(resultDoc.getMetadata()).containsKeys("meta2", "distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); List<Document> results2 = vectorStore.similaritySearch(SearchRequest.query("Great").withTopK(1)); assertThat(results2).hasSize(0); }); } @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", "number", 3)); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Netherlands", "number", 90)); vectorStore.add(List.of(bgDocument, nlDocument)); var request = SearchRequest.query("The World").withTopK(5); List<Document> results = vectorStore.similaritySearch(request); assertThat(results).hasSize(2); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("country == 'Bulgaria'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("country == 'Netherlands'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("NOT(country == 'Netherlands')")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("number in [3, 5, 12]")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("number nin [3, 5, 12]")); 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()); }); } @Test public void documentUpdateTest() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); Document document = new Document(UUID.randomUUID().toString(), "Spring AI rocks!!", Collections.singletonMap("meta1", "meta1")); vectorStore.add(List.of(document)); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("Spring AI rocks!!"); assertThat(resultDoc.getMetadata()).containsKey("meta1"); assertThat(resultDoc.getMetadata()).containsKey("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)); results = vectorStore.similaritySearch(SearchRequest.query("FooBar").withTopK(5)); assertThat(results).hasSize(1); resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(document.getId()); assertThat(resultDoc.getContent()).isEqualTo("The World is Big and Salvation Lurks Around the Corner"); assertThat(resultDoc.getMetadata()).containsKey("meta2"); assertThat(resultDoc.getMetadata()).containsKey("distance"); vectorStore.delete(List.of(document.getId())); }); } @Test public void searchThresholdTest() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); var request = SearchRequest.query("Great").withTopK(5); List<Document> fullResult = vectorStore.similaritySearch(request.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(request.withSimilarityThreshold(1 - threshold)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId()); assertThat(resultDoc.getContent()).isEqualTo( "Great Depression Great Depression Great Depression Great Depression Great Depression Great Depression"); assertThat(resultDoc.getMetadata()).containsKey("meta2"); assertThat(resultDoc.getMetadata()).containsKey("distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); }); } @SpringBootConfiguration public static class TestApplication { @Bean public QdrantClient qdrantClient() { String host = qdrantContainer.getHost(); int port = qdrantContainer.getMappedPort(QDRANT_GRPC_PORT); QdrantClient qdrantClient = new QdrantClient(QdrantGrpcClient.newBuilder(host, port, false).build()); return qdrantClient; } @Bean public VectorStore qdrantVectorStore(EmbeddingClient embeddingClient, QdrantClient qdrantClient) { return new QdrantVectorStore(qdrantClient, COLLECTION_NAME, embeddingClient); } @Bean public EmbeddingClient embeddingClient() { return new OpenAiEmbeddingClient(new OpenAiApi(System.getenv("OPENAI_API_KEY"))); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3118, 3172), 'io.qdrant.client.QdrantGrpcClient.newBuilder'), ((3233, 3324), 'io.qdrant.client.grpc.Collections.VectorParams.newBuilder'), ((3233, 3316), 'io.qdrant.client.grpc.Collections.VectorParams.newBuilder'), ((3233, 3287), 'io.qdrant.client.grpc.Collections.VectorParams.newBuilder'), ((3586, 3626), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4187, 4227), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4783, 4827), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((6194, 6267), 'java.util.List.of'), ((6194, 6258), 'java.util.List.of'), ((6194, 6234), 'java.util.List.of'), ((6460, 6488), 'java.util.UUID.randomUUID'), ((6659, 6700), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((7299, 7340), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((7959, 7999), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((9250, 9304), 'io.qdrant.client.QdrantGrpcClient.newBuilder')]
/* * 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.redis; import com.redis.testcontainers.RedisStackContainer; import org.junit.jupiter.api.Test; import org.springframework.ai.ResourceUtils; import org.springframework.ai.autoconfigure.vectorstore.redis.RedisVectorStoreAutoConfiguration; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @SpringJUnitConfig @Testcontainers @TestPropertySource( properties = { "spring.ai.vectorstore.redis.index=myIdx", "spring.ai.vectorstore.redis.prefix=doc:" }) class RedisContainerConnectionDetailsFactoryTest { @Container @ServiceConnection static RedisStackContainer redisContainer = new RedisStackContainer( RedisStackContainer.DEFAULT_IMAGE_NAME.withTag(RedisStackContainer.DEFAULT_TAG)); private 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"))); @Autowired private VectorStore vectorStore; @Test 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."); // 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) @ImportAutoConfiguration(RedisVectorStoreAutoConfiguration.class) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2208, 2287), 'com.redis.testcontainers.RedisStackContainer.DEFAULT_IMAGE_NAME.withTag'), ((2805, 2846), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3298, 3339), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package com.example.thehealingmeal.gpt; import com.example.thehealingmeal.gpt.dto.AiResDto; import com.example.thehealingmeal.gpt.responseRepository.GPTResponse; import com.example.thehealingmeal.gpt.responseRepository.ResponseRepository; import com.example.thehealingmeal.member.domain.User; import com.example.thehealingmeal.member.repository.UserRepository; import com.example.thehealingmeal.menu.api.dto.MenuResponseDto; import com.example.thehealingmeal.menu.api.dto.SnackOrTeaResponseDto; import com.example.thehealingmeal.menu.domain.Meals; import com.example.thehealingmeal.menu.service.MenuProvider; import lombok.RequiredArgsConstructor; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @RequiredArgsConstructor public class GPTService { private final ChatClient chatClient; private final MenuProvider menuProvider; private final UserRepository userRepository; private final ResponseRepository responseRepository; private ChatResponse callChat(String menu) { return chatClient.call( new Prompt( menu + "을 먹는다고 했을 때 섭취하는 사람에게 어떤 효능이 있을까? 위 아래 문단의 잡설은 하지 말고, 각 음식에 대해 번호 리스트로 짧은 분량의 내용을 보여줘.", OpenAiChatOptions.builder() .withTemperature(0.4F) .withFrequencyPenalty(0.7F) .withModel("gpt-3.5-turbo") .build() )); } //request answer to openai. public AiResDto getAnswer(long user_id, Meals meals) { MenuResponseDto menu = menuProvider.provide(user_id, meals); List<String> names = List.of(menu.getMain_dish(), menu.getRice(), menu.getSideDishForUserMenu().toString()); StringBuilder sentence = new StringBuilder(); for (String name : names) { sentence.append(name); if (names.iterator().hasNext()) { sentence.append(", "); } } ChatResponse response = callChat(sentence.toString()); if (response == null) { response = callChat(sentence.toString()); } return new AiResDto(response.getResult().getOutput().getContent()); } public AiResDto getAnswerSnackOrTea(long user_id, Meals meals) { SnackOrTeaResponseDto menu = menuProvider.provideSnackOrTea(user_id, meals); String multiChat = callChat(menu.getSnack_or_tea()).getResult().getOutput().getContent(); if (multiChat == null || multiChat.isBlank() || multiChat.isEmpty()) { multiChat = callChat(menu.getSnack_or_tea()).getResult().getOutput().getContent(); } return new AiResDto(multiChat); } @Transactional public void saveResponse(String response, long user_id, Meals meals) { User id = userRepository.findById(user_id).orElseThrow(() -> new IllegalArgumentException("Not Found User Data In Database.")); GPTResponse gptResponse = GPTResponse.builder() .gptAnswer(response) .user(id) .meals(meals) .build(); responseRepository.save(gptResponse); } @Transactional(readOnly = true) public AiResDto provideResponse(long user_id, Meals meals) { try { GPTResponse gptResponse = responseRepository.findByMealsAndUserId(meals, user_id); return new AiResDto(gptResponse.getGptAnswer()); } catch (Exception e) { throw new IllegalArgumentException("Not Found Response Data In Database."); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((1615, 1858), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1615, 1817), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1615, 1757), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1615, 1697), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3387, 3526), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder'), ((3387, 3501), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder'), ((3387, 3471), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder'), ((3387, 3445), 'com.example.thehealingmeal.gpt.responseRepository.GPTResponse.builder')]
package com.redis.demo.spring.ai; import org.springframework.ai.autoconfigure.vectorstore.redis.RedisVectorStoreProperties; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.RedisVectorStore; import org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RagConfiguration { @Bean TransformersEmbeddingClient transformersEmbeddingClient() { return new TransformersEmbeddingClient(MetadataMode.EMBED); } @Bean VectorStore vectorStore(TransformersEmbeddingClient embeddingClient, RedisVectorStoreProperties properties) { var config = RedisVectorStoreConfig.builder().withURI(properties.getUri()).withIndexName(properties.getIndex()) .withPrefix(properties.getPrefix()).build(); RedisVectorStore vectorStore = new RedisVectorStore(config, embeddingClient); vectorStore.afterPropertiesSet(); return vectorStore; } @Bean RagService ragService(ChatClient chatClient, VectorStore vectorStore) { return new RagService(chatClient, vectorStore); } }
[ "org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder" ]
[((951, 1109), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((951, 1101), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((951, 1049), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((951, 1012), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder')]
package com.example; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.StreamingChatClient; import org.springframework.ai.chat.prompt.ChatOptions; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; /** * Chat Completionsを試す。 * */ @RestController @RequestMapping("/chat") public class ChatController { @Autowired private ChatClient chatClient; @Autowired private StreamingChatClient streamingChatClient; @PostMapping public Object post(@RequestParam String text) { Prompt prompt = new Prompt(text); ChatResponse resp = chatClient.call(prompt); return resp.getResult(); } @PostMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> stream(@RequestParam String text) { Prompt prompt = new Prompt(text); return streamingChatClient.stream(prompt) .map(resp -> resp.getResult().getOutput().getContent()); } @PostMapping("/fn") public Object postWithFunctionCalling(@RequestParam String text) { ChatOptions chatOptions = OpenAiChatOptions.builder() .withFunction("weatherFunction") .build(); Prompt prompt = new Prompt(text, chatOptions); ChatResponse resp = chatClient.call(prompt); return resp.getResult().getOutput(); } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((1607, 1708), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1607, 1683), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
package com.example.springbootaiintegration.services; import com.example.springbootaiintegration.mongoRepos.dtos.MessageDto; import com.example.springbootaiintegration.mongoRepos.entities.Session; import org.springframework.ai.chat.StreamingChatClient; import org.springframework.ai.chat.messages.MessageType; import org.springframework.ai.chat.prompt.Prompt; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.LinkedList; import java.util.Map; public abstract class AbstractApiService { SessionService sessionService; StreamingChatClient client; String intro = ""; String model = ""; public Flux<String> getFlux(Map<String, Object> request, String id) { var conversation = sessionService.getConversation(id); if (conversation == null || request.get("clearContext").equals(Boolean.TRUE)) { conversation = new Session(id, new LinkedList<>()); } validate(conversation); conversation.getMessages().add(new MessageDto(intro + (String) request.get("prompt"), MessageType.USER.getValue())); var prompt = new Prompt(conversation.getMessages().stream().map(MessageDto::convert).toList()); initializeClient(request); var flux = client.stream(prompt) .map(response -> { var responeString = response.getResult().getOutput().getContent(); if (responeString != null) { } else { response.getMetadata().getPromptMetadata().forEach(m -> System.out.println(m.getPromptIndex())); return "\n\n"; } return responeString; } ).doOnNext(System.out::print) .publish() .autoConnect(2); appendResponseToConversation(flux, conversation); return flux .map(string -> string.replace(" ", "\u00A0")) .concatWith(Mono.just("STREAM_END")); } private void appendResponseToConversation(Flux<String> flux, Session conversation) { flux.collectList().subscribe( list -> { var response = String.join("", list); conversation.getMessages().add(new MessageDto(response)); sessionService.addConversation(conversation); }, error -> System.out.println("error collecting the list!")); } private static void validate(Session session) { var conversation = session.getMessages(); while (conversation.size() != 0 && conversation.get(conversation.size() - 1).getType().equals("user")) { conversation.remove(conversation.size() - 1); } } abstract void initializeClient(Map<String, Object> request); abstract void makeClient(); }
[ "org.springframework.ai.chat.messages.MessageType.USER.getValue" ]
[((1074, 1101), 'org.springframework.ai.chat.messages.MessageType.USER.getValue')]
package com.example.pdfsimilaritysearch; import java.util.List; import java.util.Map; import java.util.Objects; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class DocumentController { private final VectorStore vectorStore; public DocumentController(VectorStore vectorStore) { this.vectorStore = vectorStore; } @GetMapping(path = "/documents") public List<Map<String, Object>> search(@RequestParam String query, @RequestParam(defaultValue = "4") int k, Model model) { List<Map<String, Object>> documents = this.vectorStore.similaritySearch(SearchRequest.query(query).withTopK(k)) .stream() .map(document -> { Map<String, Object> metadata = document.getMetadata(); return Map.of( // "content", document.getContent(), // "file_name", metadata.get("file_name"), // "page_number", metadata.get("page_number"), // "end_page_number", Objects.requireNonNullElse(metadata.get("end_page_number"), ""), // "title", Objects.requireNonNullElse(metadata.get("title"), "-"), // "similarity", 1 - (float) metadata.get("distance") // ); }) .toList(); return documents; } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((867, 905), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.ollama.chat; import org.springframework.ai.ollama.OllamaChatClient; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Profile("ollama-chat") @Configuration public class OllamaChatClientConfig { @Value("${ai-client.ollama.base-url}") private String ollamaBaseUrl; @Value("${ai-client.ollama.chat.options.model}") private String ollamaOptionsModelName; @Value("#{T(Float).parseFloat('${ai-client.ollama.chat.options.temperature}')}") private float ollamaOptionsTemprature; /** * We need to mark this bean as primary because the use of the pgVector dependency brings in the auto-configured OllamaChatClient * by default * @return */ @Primary @Bean OllamaChatClient chatClient() { return new OllamaChatClient(ollamaChatApi()) .withDefaultOptions(OllamaOptions.create() .withModel(ollamaOptionsModelName) .withTemperature(ollamaOptionsTemprature)); } @Bean public OllamaApi ollamaChatApi() { return new OllamaApi(ollamaBaseUrl); } }
[ "org.springframework.ai.ollama.api.OllamaOptions.create" ]
[((1238, 1385), 'org.springframework.ai.ollama.api.OllamaOptions.create'), ((1238, 1319), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.anthropic; import org.springframework.ai.anthropic.AnthropicChatClient; import org.springframework.ai.anthropic.AnthropicChatOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * Anthropic Chat autoconfiguration properties. * * @author Christian Tzolov * @since 1.0.0 */ @ConfigurationProperties(AnthropicChatProperties.CONFIG_PREFIX) public class AnthropicChatProperties { public static final String CONFIG_PREFIX = "spring.ai.anthropic.chat"; /** * Enable Anthropic 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 AnthropicChatOptions options = AnthropicChatOptions.builder() .withModel(AnthropicChatClient.DEFAULT_MODEL_NAME) .withMaxTokens(AnthropicChatClient.DEFAULT_MAX_TOKENS) .withTemperature(AnthropicChatClient.DEFAULT_TEMPERATURE) .build(); public AnthropicChatOptions getOptions() { return this.options; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return this.enabled; } }
[ "org.springframework.ai.anthropic.AnthropicChatOptions.builder" ]
[((1595, 1806), 'org.springframework.ai.anthropic.AnthropicChatOptions.builder'), ((1595, 1795), 'org.springframework.ai.anthropic.AnthropicChatOptions.builder'), ((1595, 1735), 'org.springframework.ai.anthropic.AnthropicChatOptions.builder'), ((1595, 1678), 'org.springframework.ai.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.autoconfigure.mistralai; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.mistralai.MistralAiEmbeddingOptions; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * @author Ricken Bazolo * @since 0.8.1 */ @ConfigurationProperties(MistralAiEmbeddingProperties.CONFIG_PREFIX) public class MistralAiEmbeddingProperties extends MistralAiParentProperties { public static final String CONFIG_PREFIX = "spring.ai.mistralai.embedding"; public static final String DEFAULT_EMBEDDING_MODEL = MistralAiApi.EmbeddingModel.EMBED.getValue(); public static final String DEFAULT_ENCODING_FORMAT = "float"; /** * Enable MistralAI embedding client. */ private boolean enabled = true; public MetadataMode metadataMode = MetadataMode.EMBED; @NestedConfigurationProperty private MistralAiEmbeddingOptions options = MistralAiEmbeddingOptions.builder() .withModel(DEFAULT_EMBEDDING_MODEL) .withEncodingFormat(DEFAULT_ENCODING_FORMAT) .build(); public MistralAiEmbeddingProperties() { super.setBaseUrl(MistralAiCommonProperties.DEFAULT_BASE_URL); } public MistralAiEmbeddingOptions getOptions() { return this.options; } public void setOptions(MistralAiEmbeddingOptions 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.mistralai.MistralAiEmbeddingOptions.builder", "org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue" ]
[((1340, 1384), 'org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue'), ((1666, 1797), 'org.springframework.ai.mistralai.MistralAiEmbeddingOptions.builder'), ((1666, 1786), 'org.springframework.ai.mistralai.MistralAiEmbeddingOptions.builder'), ((1666, 1739), 'org.springframework.ai.mistralai.MistralAiEmbeddingOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.document.Document; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.embedding.AbstractEmbeddingClient; import org.springframework.ai.embedding.Embedding; import org.springframework.ai.embedding.EmbeddingOptions; import org.springframework.ai.embedding.EmbeddingRequest; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.ai.embedding.EmbeddingResponseMetadata; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.api.OpenAiApi.EmbeddingList; import org.springframework.ai.openai.api.OpenAiApi.Usage; import org.springframework.ai.retry.RetryUtils; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.Assert; /** * Open AI Embedding Client implementation. * * @author Christian Tzolov */ public class OpenAiEmbeddingClient extends AbstractEmbeddingClient { private static final Logger logger = LoggerFactory.getLogger(OpenAiEmbeddingClient.class); private final OpenAiEmbeddingOptions defaultOptions; private final RetryTemplate retryTemplate; private final OpenAiApi openAiApi; private final MetadataMode metadataMode; /** * Constructor for the OpenAiEmbeddingClient class. * @param openAiApi The OpenAiApi instance to use for making API requests. */ public OpenAiEmbeddingClient(OpenAiApi openAiApi) { this(openAiApi, MetadataMode.EMBED); } /** * Initializes a new instance of the OpenAiEmbeddingClient class. * @param openAiApi The OpenAiApi instance to use for making API requests. * @param metadataMode The mode for generating metadata. */ public OpenAiEmbeddingClient(OpenAiApi openAiApi, MetadataMode metadataMode) { this(openAiApi, metadataMode, OpenAiEmbeddingOptions.builder().withModel(OpenAiApi.DEFAULT_EMBEDDING_MODEL).build(), RetryUtils.DEFAULT_RETRY_TEMPLATE); } /** * Initializes a new instance of the OpenAiEmbeddingClient class. * @param openAiApi The OpenAiApi instance to use for making API requests. * @param metadataMode The mode for generating metadata. * @param openAiEmbeddingOptions The options for OpenAi embedding. */ public OpenAiEmbeddingClient(OpenAiApi openAiApi, MetadataMode metadataMode, OpenAiEmbeddingOptions openAiEmbeddingOptions) { this(openAiApi, metadataMode, openAiEmbeddingOptions, RetryUtils.DEFAULT_RETRY_TEMPLATE); } /** * Initializes a new instance of the OpenAiEmbeddingClient class. * @param openAiApi - The OpenAiApi instance to use for making API requests. * @param metadataMode - The mode for generating metadata. * @param options - The options for OpenAI embedding. * @param retryTemplate - The RetryTemplate for retrying failed API requests. */ public OpenAiEmbeddingClient(OpenAiApi openAiApi, MetadataMode metadataMode, OpenAiEmbeddingOptions options, RetryTemplate retryTemplate) { Assert.notNull(openAiApi, "OpenAiService must not be null"); Assert.notNull(metadataMode, "metadataMode must not be null"); Assert.notNull(options, "options must not be null"); Assert.notNull(retryTemplate, "retryTemplate must not be null"); this.openAiApi = openAiApi; this.metadataMode = metadataMode; this.defaultOptions = options; this.retryTemplate = retryTemplate; } @Override public List<Double> embed(Document document) { Assert.notNull(document, "Document must not be null"); return this.embed(document.getFormattedContent(this.metadataMode)); } @SuppressWarnings("unchecked") @Override public EmbeddingResponse call(EmbeddingRequest request) { return this.retryTemplate.execute(ctx -> { org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<List<String>> apiRequest = (this.defaultOptions != null) ? new org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<>(request.getInstructions(), this.defaultOptions.getModel(), this.defaultOptions.getEncodingFormat(), this.defaultOptions.getUser()) : new org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<>(request.getInstructions(), OpenAiApi.DEFAULT_EMBEDDING_MODEL); if (request.getOptions() != null && !EmbeddingOptions.EMPTY.equals(request.getOptions())) { apiRequest = ModelOptionsUtils.merge(request.getOptions(), apiRequest, org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest.class); } EmbeddingList<OpenAiApi.Embedding> apiEmbeddingResponse = this.openAiApi.embeddings(apiRequest).getBody(); if (apiEmbeddingResponse == null) { logger.warn("No embeddings returned for request: {}", request); return new EmbeddingResponse(List.of()); } var metadata = generateResponseMetadata(apiEmbeddingResponse.model(), apiEmbeddingResponse.usage()); List<Embedding> embeddings = apiEmbeddingResponse.data() .stream() .map(e -> new Embedding(e.embedding(), e.index())) .toList(); return new EmbeddingResponse(embeddings, metadata); }); } private EmbeddingResponseMetadata generateResponseMetadata(String model, Usage usage) { EmbeddingResponseMetadata metadata = new EmbeddingResponseMetadata(); metadata.put("model", model); metadata.put("prompt-tokens", usage.promptTokens()); metadata.put("completion-tokens", usage.completionTokens()); metadata.put("total-tokens", usage.totalTokens()); return metadata; } }
[ "org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals" ]
[((4950, 5001), 'org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.milvus; import java.util.concurrent.TimeUnit; import io.milvus.client.MilvusServiceClient; import io.milvus.param.ConnectParam; import io.milvus.param.IndexType; import io.milvus.param.MetricType; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.MilvusVectorStore; import org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.util.StringUtils; /** * @author Christian Tzolov * @author Eddú Meléndez */ @AutoConfiguration @ConditionalOnClass({ MilvusVectorStore.class, EmbeddingClient.class }) @EnableConfigurationProperties({ MilvusServiceClientProperties.class, MilvusVectorStoreProperties.class }) public class MilvusVectorStoreAutoConfiguration { @Bean @ConditionalOnMissingBean(MilvusServiceClientConnectionDetails.class) PropertiesMilvusServiceClientConnectionDetails milvusServiceClientConnectionDetails( MilvusServiceClientProperties properties) { return new PropertiesMilvusServiceClientConnectionDetails(properties); } @Bean @ConditionalOnMissingBean public MilvusVectorStore vectorStore(MilvusServiceClient milvusClient, EmbeddingClient embeddingClient, MilvusVectorStoreProperties properties) { MilvusVectorStoreConfig config = MilvusVectorStoreConfig.builder() .withCollectionName(properties.getCollectionName()) .withDatabaseName(properties.getDatabaseName()) .withIndexType(IndexType.valueOf(properties.getIndexType().name())) .withMetricType(MetricType.valueOf(properties.getMetricType().name())) .withIndexParameters(properties.getIndexParameters()) .withEmbeddingDimension(properties.getEmbeddingDimension()) .build(); return new MilvusVectorStore(milvusClient, embeddingClient, config); } @Bean @ConditionalOnMissingBean public MilvusServiceClient milvusClient(MilvusVectorStoreProperties serverProperties, MilvusServiceClientProperties clientProperties, MilvusServiceClientConnectionDetails connectionDetails) { var builder = ConnectParam.newBuilder() .withHost(connectionDetails.getHost()) .withPort(connectionDetails.getPort()) .withDatabaseName(serverProperties.getDatabaseName()) .withConnectTimeout(clientProperties.getConnectTimeoutMs(), TimeUnit.MILLISECONDS) .withKeepAliveTime(clientProperties.getKeepAliveTimeMs(), TimeUnit.MILLISECONDS) .withKeepAliveTimeout(clientProperties.getKeepAliveTimeoutMs(), TimeUnit.MILLISECONDS) .withRpcDeadline(clientProperties.getRpcDeadlineMs(), TimeUnit.MILLISECONDS) .withSecure(clientProperties.isSecure()) .withIdleTimeout(clientProperties.getIdleTimeoutMs(), TimeUnit.MILLISECONDS) .withAuthorization(clientProperties.getUsername(), clientProperties.getPassword()); if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getUri())) { builder.withUri(clientProperties.getUri()); } if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getToken())) { builder.withToken(clientProperties.getToken()); } if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getClientKeyPath())) { builder.withClientKeyPath(clientProperties.getClientKeyPath()); } if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getClientPemPath())) { builder.withClientPemPath(clientProperties.getClientPemPath()); } if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getCaPemPath())) { builder.withCaPemPath(clientProperties.getCaPemPath()); } if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getServerPemPath())) { builder.withServerPemPath(clientProperties.getServerPemPath()); } if (clientProperties.isSecure() && StringUtils.hasText(clientProperties.getServerName())) { builder.withServerName(clientProperties.getServerName()); } return new MilvusServiceClient(builder.build()); } private static class PropertiesMilvusServiceClientConnectionDetails implements MilvusServiceClientConnectionDetails { private final MilvusServiceClientProperties properties; PropertiesMilvusServiceClientConnectionDetails(MilvusServiceClientProperties properties) { this.properties = properties; } @Override public String getHost() { return this.properties.getHost(); } @Override public int getPort() { return this.properties.getPort(); } } }
[ "org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder" ]
[((2302, 2718), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2302, 2706), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2302, 2643), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2302, 2586), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2302, 2512), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2302, 2441), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((2302, 2390), 'org.springframework.ai.vectorstore.MilvusVectorStore.MilvusVectorStoreConfig.builder'), ((3043, 3759), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3673), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3593), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3549), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3469), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3379), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3295), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3209), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3152), 'io.milvus.param.ConnectParam.newBuilder'), ((3043, 3110), 'io.milvus.param.ConnectParam.newBuilder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.mistralai; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.document.Document; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.embedding.AbstractEmbeddingClient; import org.springframework.ai.embedding.Embedding; import org.springframework.ai.embedding.EmbeddingOptions; import org.springframework.ai.embedding.EmbeddingRequest; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.ai.embedding.EmbeddingResponseMetadata; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.ai.retry.RetryUtils; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.Assert; /** * @author Ricken Bazolo * @since 0.8.1 */ public class MistralAiEmbeddingClient extends AbstractEmbeddingClient { private final Logger log = LoggerFactory.getLogger(getClass()); private final MistralAiEmbeddingOptions defaultOptions; private final MetadataMode metadataMode; private final MistralAiApi mistralAiApi; private final RetryTemplate retryTemplate; public MistralAiEmbeddingClient(MistralAiApi mistralAiApi) { this(mistralAiApi, MetadataMode.EMBED); } public MistralAiEmbeddingClient(MistralAiApi mistralAiApi, MetadataMode metadataMode) { this(mistralAiApi, metadataMode, MistralAiEmbeddingOptions.builder().withModel(MistralAiApi.EmbeddingModel.EMBED.getValue()).build(), RetryUtils.DEFAULT_RETRY_TEMPLATE); } public MistralAiEmbeddingClient(MistralAiApi mistralAiApi, MistralAiEmbeddingOptions options) { this(mistralAiApi, MetadataMode.EMBED, options, RetryUtils.DEFAULT_RETRY_TEMPLATE); } public MistralAiEmbeddingClient(MistralAiApi mistralAiApi, MetadataMode metadataMode, MistralAiEmbeddingOptions options, RetryTemplate retryTemplate) { Assert.notNull(mistralAiApi, "MistralAiApi must not be null"); Assert.notNull(metadataMode, "metadataMode must not be null"); Assert.notNull(options, "options must not be null"); Assert.notNull(retryTemplate, "retryTemplate must not be null"); this.mistralAiApi = mistralAiApi; this.metadataMode = metadataMode; this.defaultOptions = options; this.retryTemplate = retryTemplate; } @Override @SuppressWarnings("unchecked") public EmbeddingResponse call(EmbeddingRequest request) { return this.retryTemplate.execute(ctx -> { var apiRequest = (this.defaultOptions != null) ? new MistralAiApi.EmbeddingRequest<>(request.getInstructions(), this.defaultOptions.getModel(), this.defaultOptions.getEncodingFormat()) : new MistralAiApi.EmbeddingRequest<>(request.getInstructions(), MistralAiApi.EmbeddingModel.EMBED.getValue()); if (request.getOptions() != null && !EmbeddingOptions.EMPTY.equals(request.getOptions())) { apiRequest = ModelOptionsUtils.merge(request.getOptions(), apiRequest, MistralAiApi.EmbeddingRequest.class); } var apiEmbeddingResponse = this.mistralAiApi.embeddings(apiRequest).getBody(); if (apiEmbeddingResponse == null) { log.warn("No embeddings returned for request: {}", request); return new EmbeddingResponse(List.of()); } var metadata = generateResponseMetadata(apiEmbeddingResponse.model(), apiEmbeddingResponse.usage()); var embeddings = apiEmbeddingResponse.data() .stream() .map(e -> new Embedding(e.embedding(), e.index())) .toList(); return new EmbeddingResponse(embeddings, metadata); }); } @Override public List<Double> embed(Document document) { Assert.notNull(document, "Document must not be null"); return this.embed(document.getFormattedContent(this.metadataMode)); } private EmbeddingResponseMetadata generateResponseMetadata(String model, MistralAiApi.Usage usage) { var metadata = new EmbeddingResponseMetadata(); metadata.put("model", model); metadata.put("prompt-tokens", usage.promptTokens()); metadata.put("total-tokens", usage.totalTokens()); return metadata; } }
[ "org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals", "org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue" ]
[((2121, 2165), 'org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue'), ((3388, 3432), 'org.springframework.ai.mistralai.api.MistralAiApi.EmbeddingModel.EMBED.getValue'), ((3476, 3527), 'org.springframework.ai.embedding.EmbeddingOptions.EMPTY.equals')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.azure.openai; import org.springframework.ai.azure.openai.AzureOpenAiEmbeddingOptions; import org.springframework.ai.document.MetadataMode; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.util.Assert; @ConfigurationProperties(AzureOpenAiEmbeddingProperties.CONFIG_PREFIX) public class AzureOpenAiEmbeddingProperties { public static final String CONFIG_PREFIX = "spring.ai.azure.openai.embedding"; /** * Enable Azure OpenAI embedding client. */ private boolean enabled = true; @NestedConfigurationProperty private AzureOpenAiEmbeddingOptions options = AzureOpenAiEmbeddingOptions.builder() .withDeploymentName("text-embedding-ada-002") .build(); private MetadataMode metadataMode = MetadataMode.EMBED; public AzureOpenAiEmbeddingOptions getOptions() { return options; } public void setOptions(AzureOpenAiEmbeddingOptions options) { Assert.notNull(options, "Options must not be null"); this.options = options; } public MetadataMode getMetadataMode() { return metadataMode; } public void setMetadataMode(MetadataMode metadataMode) { Assert.notNull(metadataMode, "Metadata mode must not be null"); this.metadataMode = metadataMode; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
[ "org.springframework.ai.azure.openai.AzureOpenAiEmbeddingOptions.builder" ]
[((1363, 1459), 'org.springframework.ai.azure.openai.AzureOpenAiEmbeddingOptions.builder'), ((1363, 1448), 'org.springframework.ai.azure.openai.AzureOpenAiEmbeddingOptions.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 org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.RedisVectorStore; import org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; /** * @author Christian Tzolov * @author Eddú Meléndez */ @AutoConfiguration @ConditionalOnClass({ RedisVectorStore.class, EmbeddingClient.class }) @EnableConfigurationProperties(RedisVectorStoreProperties.class) public class RedisVectorStoreAutoConfiguration { @Bean @ConditionalOnMissingBean(RedisConnectionDetails.class) public PropertiesRedisConnectionDetails redisConnectionDetails(RedisVectorStoreProperties properties) { return new PropertiesRedisConnectionDetails(properties); } @Bean @ConditionalOnMissingBean public RedisVectorStore vectorStore(EmbeddingClient embeddingClient, RedisVectorStoreProperties properties, RedisConnectionDetails redisConnectionDetails) { var config = RedisVectorStoreConfig.builder() .withURI(redisConnectionDetails.getUri()) .withIndexName(properties.getIndex()) .withPrefix(properties.getPrefix()) .build(); return new RedisVectorStore(config, embeddingClient); } private static class PropertiesRedisConnectionDetails implements RedisConnectionDetails { private final RedisVectorStoreProperties properties; public PropertiesRedisConnectionDetails(RedisVectorStoreProperties properties) { this.properties = properties; } @Override public String getUri() { return this.properties.getUri(); } } }
[ "org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder" ]
[((1953, 2122), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((1953, 2110), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((1953, 2071), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder'), ((1953, 2030), 'org.springframework.ai.vectorstore.RedisVectorStore.RedisVectorStoreConfig.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.watsonx; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.Assert; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.metadata.ChatGenerationMetadata; import org.springframework.ai.chat.prompt.ChatOptionsBuilder; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.watsonx.api.WatsonxAiApi; import org.springframework.ai.watsonx.api.WatsonxAiRequest; import org.springframework.ai.watsonx.api.WatsonxAiResponse; import org.springframework.ai.watsonx.api.WatsonxAiResults; import org.springframework.http.ResponseEntity; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Pablo Sanchidrian Herrera * @author John Jairo Moreno Rojas */ public class WatsonxAiChatClientTest { WatsonxAiChatClient chatClient = new WatsonxAiChatClient(mock(WatsonxAiApi.class)); @Test public void testCreateRequestWithNoModelId() { var options = ChatOptionsBuilder.builder().withTemperature(0.9f).withTopK(100).withTopP(0.6f).build(); Prompt prompt = new Prompt("Test message", options); Exception exception = Assert.assertThrows(IllegalArgumentException.class, () -> { WatsonxAiRequest request = chatClient.request(prompt); }); } @Test public void testCreateRequestSuccessfullyWithDefaultParams() { String msg = "Test message"; WatsonxAiChatOptions modelOptions = WatsonxAiChatOptions.builder() .withModel("meta-llama/llama-2-70b-chat") .build(); Prompt prompt = new Prompt(msg, modelOptions); WatsonxAiRequest request = chatClient.request(prompt); Assert.assertEquals(request.getModelId(), "meta-llama/llama-2-70b-chat"); assertThat(request.getParameters().get("decoding_method")).isEqualTo("greedy"); assertThat(request.getParameters().get("temperature")).isEqualTo(0.7); assertThat(request.getParameters().get("top_p")).isEqualTo(1.0); assertThat(request.getParameters().get("top_k")).isEqualTo(50); assertThat(request.getParameters().get("max_new_tokens")).isEqualTo(20); assertThat(request.getParameters().get("min_new_tokens")).isEqualTo(0); assertThat(request.getParameters().get("stop_sequences")).isInstanceOf(List.class); Assert.assertEquals(request.getParameters().get("stop_sequences"), List.of()); assertThat(request.getParameters().get("random_seed")).isNull(); } @Test public void testCreateRequestSuccessfullyWithNonDefaultParams() { String msg = "Test message"; WatsonxAiChatOptions modelOptions = WatsonxAiChatOptions.builder() .withModel("meta-llama/llama-2-70b-chat") .withDecodingMethod("sample") .withTemperature(0.1f) .withTopP(0.2f) .withTopK(10) .withMaxNewTokens(30) .withMinNewTokens(10) .withRepetitionPenalty(1.4f) .withStopSequences(List.of("\n\n\n")) .withRandomSeed(4) .build(); Prompt prompt = new Prompt(msg, modelOptions); WatsonxAiRequest request = chatClient.request(prompt); Assert.assertEquals(request.getModelId(), "meta-llama/llama-2-70b-chat"); assertThat(request.getParameters().get("decoding_method")).isEqualTo("sample"); assertThat(request.getParameters().get("temperature")).isEqualTo(0.1); assertThat(request.getParameters().get("top_p")).isEqualTo(0.2); assertThat(request.getParameters().get("top_k")).isEqualTo(10); assertThat(request.getParameters().get("max_new_tokens")).isEqualTo(30); assertThat(request.getParameters().get("min_new_tokens")).isEqualTo(10); assertThat(request.getParameters().get("stop_sequences")).isInstanceOf(List.class); Assert.assertEquals(request.getParameters().get("stop_sequences"), List.of("\n\n\n")); assertThat(request.getParameters().get("random_seed")).isEqualTo(4); } @Test public void testCreateRequestSuccessfullyWithChatDisabled() { String msg = "Test message"; WatsonxAiChatOptions modelOptions = WatsonxAiChatOptions.builder() .withModel("meta-llama/llama-2-70b-chat") .withDecodingMethod("sample") .withTemperature(0.1f) .withTopP(0.2f) .withTopK(10) .withMaxNewTokens(30) .withMinNewTokens(10) .withRepetitionPenalty(1.4f) .withStopSequences(List.of("\n\n\n")) .withRandomSeed(4) .build(); Prompt prompt = new Prompt(msg, modelOptions); WatsonxAiRequest request = chatClient.request(prompt); Assert.assertEquals(request.getModelId(), "meta-llama/llama-2-70b-chat"); assertThat(request.getInput()).isEqualTo(msg); assertThat(request.getParameters().get("decoding_method")).isEqualTo("sample"); assertThat(request.getParameters().get("temperature")).isEqualTo(0.1); assertThat(request.getParameters().get("top_p")).isEqualTo(0.2); assertThat(request.getParameters().get("top_k")).isEqualTo(10); assertThat(request.getParameters().get("max_new_tokens")).isEqualTo(30); assertThat(request.getParameters().get("min_new_tokens")).isEqualTo(10); assertThat(request.getParameters().get("stop_sequences")).isInstanceOf(List.class); Assert.assertEquals(request.getParameters().get("stop_sequences"), List.of("\n\n\n")); assertThat(request.getParameters().get("random_seed")).isEqualTo(4); } @Test public void testCallMethod() { WatsonxAiApi mockChatApi = mock(WatsonxAiApi.class); WatsonxAiChatClient client = new WatsonxAiChatClient(mockChatApi); Prompt prompt = new Prompt(List.of(new SystemMessage("Your prompt here")), WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build()); WatsonxAiChatOptions parameters = WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build(); WatsonxAiResults fakeResults = new WatsonxAiResults("LLM response", 4, 3, "max_tokens"); WatsonxAiResponse fakeResponse = new WatsonxAiResponse("google/flan-ul2", new Date(), List.of(fakeResults), Map.of("warnings", List.of(Map.of("message", "the message", "id", "disclaimer_warning")))); when(mockChatApi.generate(any(WatsonxAiRequest.class))) .thenReturn(ResponseEntity.of(Optional.of(fakeResponse))); Generation expectedGenerator = new Generation("LLM response") .withGenerationMetadata(ChatGenerationMetadata.from("max_tokens", Map.of("warnings", List.of(Map.of("message", "the message", "id", "disclaimer_warning"))))); ChatResponse expectedResponse = new ChatResponse(List.of(expectedGenerator)); ChatResponse response = client.call(prompt); Assert.assertEquals(expectedResponse.getResults().size(), response.getResults().size()); Assert.assertEquals(expectedResponse.getResult().getOutput(), response.getResult().getOutput()); } @Test public void testStreamMethod() { WatsonxAiApi mockChatApi = mock(WatsonxAiApi.class); WatsonxAiChatClient client = new WatsonxAiChatClient(mockChatApi); Prompt prompt = new Prompt(List.of(new SystemMessage("Your prompt here")), WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build()); WatsonxAiChatOptions parameters = WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build(); WatsonxAiResults fakeResultsFirst = new WatsonxAiResults("LLM resp", 0, 0, "max_tokens"); WatsonxAiResults fakeResultsSecond = new WatsonxAiResults("onse", 4, 3, "not_finished"); WatsonxAiResponse fakeResponseFirst = new WatsonxAiResponse("google/flan-ul2", new Date(), List.of(fakeResultsFirst), Map.of("warnings", List.of(Map.of("message", "the message", "id", "disclaimer_warning")))); WatsonxAiResponse fakeResponseSecond = new WatsonxAiResponse("google/flan-ul2", new Date(), List.of(fakeResultsSecond), null); Flux<WatsonxAiResponse> fakeResponse = Flux.just(fakeResponseFirst, fakeResponseSecond); when(mockChatApi.generateStreaming(any(WatsonxAiRequest.class))).thenReturn(fakeResponse); Generation firstGen = new Generation("LLM resp") .withGenerationMetadata(ChatGenerationMetadata.from("max_tokens", Map.of("warnings", List.of(Map.of("message", "the message", "id", "disclaimer_warning"))))); Generation secondGen = new Generation("onse"); Flux<ChatResponse> response = client.stream(prompt); StepVerifier.create(response).assertNext(current -> { ChatResponse expected = new ChatResponse(List.of(firstGen)); Assert.assertEquals(expected.getResults().size(), current.getResults().size()); Assert.assertEquals(expected.getResult().getOutput(), current.getResult().getOutput()); }).assertNext(current -> { ChatResponse expected = new ChatResponse(List.of(secondGen)); Assert.assertEquals(expected.getResults().size(), current.getResults().size()); Assert.assertEquals(expected.getResult().getOutput(), current.getResult().getOutput()); }).expectComplete().verify(); } }
[ "org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder" ]
[((1960, 2047), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1960, 2039), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1960, 2024), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((1960, 2010), 'org.springframework.ai.chat.prompt.ChatOptionsBuilder.builder'), ((8956, 9549), 'reactor.test.StepVerifier.create'), ((8956, 9540), 'reactor.test.StepVerifier.create'), ((8956, 9523), 'reactor.test.StepVerifier.create'), ((8956, 9254), 'reactor.test.StepVerifier.create')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.audio.speech; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.ai.openai.OpenAiAudioSpeechClient; import org.springframework.ai.openai.OpenAiAudioSpeechOptions; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.metadata.audio.OpenAiAudioSpeechResponseMetadata; import org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders; import org.springframework.ai.retry.RetryUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.context.annotation.Bean; import org.springframework.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.time.Duration; 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 Ahmed Yousri */ @RestClientTest(OpenAiSpeechClientWithSpeechResponseMetadataTests.Config.class) public class OpenAiSpeechClientWithSpeechResponseMetadataTests { private static String TEST_API_KEY = "sk-1234567890"; private static final Float SPEED = 1.0f; @Autowired private OpenAiAudioSpeechClient openAiSpeechClient; @Autowired private MockRestServiceServer server; @AfterEach void resetMockServer() { server.reset(); } @Test void aiResponseContainsImageResponseMetadata() { prepareMock(); OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY) .withSpeed(SPEED) .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .withModel(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); SpeechPrompt speechPrompt = new SpeechPrompt("Today is a wonderful day to build something people love!", speechOptions); SpeechResponse response = openAiSpeechClient.call(speechPrompt); byte[] audioBytes = response.getResult().getOutput(); assertThat(audioBytes).hasSizeGreaterThan(0); OpenAiAudioSpeechResponseMetadata speechResponseMetadata = response.getMetadata(); assertThat(speechResponseMetadata).isNotNull(); var requestLimit = speechResponseMetadata.getRateLimit(); Long requestsLimit = requestLimit.getRequestsLimit(); Long tokensLimit = requestLimit.getTokensLimit(); Long tokensRemaining = requestLimit.getTokensRemaining(); Long requestsRemaining = requestLimit.getRequestsRemaining(); Duration requestsReset = requestLimit.getRequestsReset(); assertThat(requestsLimit).isNotNull(); assertThat(requestsLimit).isEqualTo(4000L); assertThat(tokensLimit).isEqualTo(725000L); assertThat(tokensRemaining).isEqualTo(112358L); assertThat(requestsRemaining).isEqualTo(999L); assertThat(requestsReset).isEqualTo(Duration.parse("PT64H15M29S")); } 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"); httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); server.expect(requestTo("/v1/audio/speech")) .andExpect(method(HttpMethod.POST)) .andExpect(header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_API_KEY)) .andRespond(withSuccess("Audio bytes as string", MediaType.APPLICATION_OCTET_STREAM).headers(httpHeaders)); } @SpringBootConfiguration static class Config { @Bean public OpenAiAudioSpeechClient openAiAudioSpeechClient(OpenAiAudioApi openAiAudioApi) { return new OpenAiAudioSpeechClient(openAiAudioApi); } @Bean public OpenAiAudioApi openAiAudioApi(RestClient.Builder builder) { return new OpenAiAudioApi("", TEST_API_KEY, builder, RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER); } } }
[ "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.OpenAiAudioSpeechOptions.builder", "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" ]
[((2485, 2736), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2485, 2724), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2485, 2673), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2485, 2596), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((2485, 2575), 'org.springframework.ai.openai.OpenAiAudioSpeechOptions.builder'), ((3929, 3985), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName'), ((4014, 4074), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName'), ((4102, 4158), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName'), ((4194, 4248), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName'), ((4279, 4337), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName'), ((4368, 4422), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName')]