code
stringlengths
419
138k
apis
sequencelengths
1
8
extract_api
stringlengths
67
7.3k
package com.kousenit.springaiexamples.rag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.reader.JsonReader; import org.springframework.ai.transformer.splitter.TextSplitter; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import java.io.File; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class RagService { private static final Logger logger = LoggerFactory.getLogger(RagService.class); @Value("classpath:/data/bikes.json") private Resource bikesResource; @Value("classpath:/prompts/system-qa.st") private Resource systemBikePrompt; private final ChatClient aiClient; private final EmbeddingClient embeddingClient; @Autowired public RagService(@Qualifier("openAiChatClient") ChatClient aiClient, @Qualifier("openAiEmbeddingClient") EmbeddingClient embeddingClient) { this.aiClient = aiClient; this.embeddingClient = embeddingClient; } public Generation retrieve(String message) { SimpleVectorStore vectorStore = new SimpleVectorStore(embeddingClient); File bikeVectorStore = new File("src/main/resources/data/bikeVectorStore.json"); if (bikeVectorStore.exists()) { vectorStore.load(bikeVectorStore); } else { // Step 1 - Load JSON document as Documents logger.info("Loading JSON as Documents"); JsonReader jsonReader = new JsonReader(bikesResource, "name", "price", "shortDescription", "description"); List<Document> documents = jsonReader.get(); logger.info("Loading JSON as Documents"); TextSplitter splitter = new TokenTextSplitter(); List<Document> splitDocuments = splitter.apply(documents); // Step 2 - Create embeddings and save to vector store logger.info("Creating Embeddings..."); vectorStore.add(splitDocuments); logger.info("Embeddings created."); vectorStore.save(bikeVectorStore); } // Step 3 retrieve related documents to query logger.info("Retrieving relevant documents"); List<Document> similarDocuments = vectorStore.similaritySearch( SearchRequest.query(message).withTopK(4)); logger.info(String.format("Found %s relevant documents.", similarDocuments.size())); // Step 4 Embed documents into SystemMessage with the `system-qa.st` prompt template Message systemMessage = getSystemMessage(similarDocuments); UserMessage userMessage = new UserMessage(message); // Step 5 - Ask the AI model logger.info("Asking AI model to reply to question."); Prompt prompt = new Prompt(List.of(systemMessage, userMessage)); logger.info(prompt.toString()); ChatResponse response = aiClient.call(prompt); logger.info("AI responded."); logger.info(response.getResult().toString()); return response.getResult(); } private Message getSystemMessage(List<Document> similarDocuments) { String documents = similarDocuments.stream() .map(Document::getContent) .collect(Collectors.joining("\n")); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemBikePrompt); return systemPromptTemplate.createMessage(Map.of("documents", documents)); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3128, 3168), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package org.example.springai.retriever; import java.util.List; import java.util.Objects; import java.util.Optional; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentRetriever; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; /** * spring-ai μ—μ„œ μ‚­μ œλœ 클래슀 λ“€κ³ μ˜΄ * μ•„λž˜λŠ” ν•΄λ‹Ή μ»€λ°‹λ©”μ‹œμ§€ * b35c71061ed1560241a4e3708775cd703acf2553 */ public class VectorStoreRetriever implements DocumentRetriever { private VectorStore vectorStore; int k; Optional<Double> threshold = Optional.empty(); public VectorStoreRetriever(VectorStore vectorStore) { this(vectorStore, 4); } public VectorStoreRetriever(VectorStore vectorStore, int k) { Objects.requireNonNull(vectorStore, "VectorStore must not be null"); this.vectorStore = vectorStore; this.k = k; } public VectorStoreRetriever(VectorStore vectorStore, int k, double threshold) { Objects.requireNonNull(vectorStore, "VectorStore must not be null"); this.vectorStore = vectorStore; this.k = k; this.threshold = Optional.of(threshold); } public VectorStore getVectorStore() { return vectorStore; } public int getK() { return k; } public Optional<Double> getThreshold() { return threshold; } @Override public List<Document> retrieve(String query) { SearchRequest request = SearchRequest.query(query).withTopK(this.k); if (threshold.isPresent()) { request.withSimilarityThreshold(this.threshold.get()); } return this.vectorStore.similaritySearch(request); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1529, 1572), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package ai.ssudikon.springai; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.PagePdfDocumentReader; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @SpringBootApplication public class SpringAiExpApplication { public static void main(String[] args) { SpringApplication.run(SpringAiExpApplication.class, args); } @Component static class AlexPopeAiClient { private final VectorStore vectorStore; private final ChatClient chatClient; AlexPopeAiClient(VectorStore vectorStore, ChatClient chatClient) { this.vectorStore = vectorStore; this.chatClient = chatClient; } public String chat(String query) { var prompt = """ You're assisting with questions about alexander pope. Alexander Pope (1688–1744) was an English poet, translator, and satirist known for his significant contributions to 18th-century English literature. He is renowned for works like "The Rape of the Lock," "The Dunciad," and "An Essay on Criticism." Pope's writing style often featured satire and discursive poetry, and his translations of Homer were also notable. Use the information from the DOCUMENTS section to provide accurate answers but act as if you knew this information innately. If unsure, simply state that you don't know. DOCUMENTS: {documents} """; var listOfSimilarDocs = vectorStore.similaritySearch(query); var docs = listOfSimilarDocs.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator())); var systemMessage = new SystemPromptTemplate(prompt).createMessage(Map.of("documents", docs)); var userMessage = new UserMessage(query); var promptList = new Prompt(List.of(systemMessage, userMessage)); var aiResponse = chatClient.call(promptList); return aiResponse.getResult().getOutput().getContent(); } } @Bean ApplicationRunner applicationRunner(VectorStore vectorStore, @Value("file:/Users/sudikonda/Developer/Java/IdeaProjects/spring-ai-exp/src/main/resources/AlexanderPope-Wikipedia.pdf") Resource resource, JdbcTemplate jdbcTemplate, ChatClient chatClient, AlexPopeAiClient alexPopeAiClient) { return args -> { init(vectorStore, resource, jdbcTemplate); String chatResponse = alexPopeAiClient.chat("Who is Alexander Pope"); System.out.println("chatResponse = " + chatResponse); }; } private static void init(VectorStore vectorStore, Resource resource, JdbcTemplate jdbcTemplate) { jdbcTemplate.update("DELETE FROM vector_store"); PdfDocumentReaderConfig config = PdfDocumentReaderConfig.builder().withPageExtractedTextFormatter(new ExtractedTextFormatter.Builder().withNumberOfBottomTextLinesToDelete(3).withNumberOfTopPagesToSkipBeforeDelete(1).build()).withPagesPerDocument(1).build(); PagePdfDocumentReader pagePdfDocumentReader = new PagePdfDocumentReader(resource, config); TokenTextSplitter tokenTextSplitter = new TokenTextSplitter(); List<Document> docs = tokenTextSplitter.apply(pagePdfDocumentReader.get()); vectorStore.accept(docs); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder" ]
[((3902, 4125), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3902, 4117), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3902, 4093), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder')]
package com.example.springaioutputparserdemo; import com.example.springaioutputparserdemo.entity.ActorsFilms; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.image.*; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController public class OutputParserController { @Autowired private ChatClient chatClient; @Autowired private ImageClient openAImageClient; @GetMapping("/ai/output") public ActorsFilms generate(@RequestParam(value = "actor", defaultValue = "Jeff Bridges") String actor) { var outputParser = new BeanOutputParser<>(ActorsFilms.class); String userMessage = """ Generate the filmography for the actor {actor}. {format} """; PromptTemplate promptTemplate = new PromptTemplate(userMessage, Map.of("actor", actor, "format", outputParser.getFormat() )); Prompt prompt = promptTemplate.create(); Generation generation = chatClient.call(prompt).getResult(); ActorsFilms actorsFilms = outputParser.parse(generation.getOutput().getContent()); return actorsFilms; } @GetMapping("/image") public Image getImage(){ ImageResponse response = openAImageClient.call( new ImagePrompt("Give me clear and HD image of a" + " football player on ground", OpenAiImageOptions.builder() .withQuality("hd") .withN(4) .withHeight(1024) .withWidth(1024).build()) ); //return response.getResult().getOutput().toString(); return response.getResult().getOutput(); } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((1895, 2115), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2107), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2060), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 2012), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((1895, 1972), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
package com.thomasvitale.ai.spring; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Service class ChatService { private final ChatClient chatClient; private final SimpleVectorStore vectorStore; ChatService(ChatClient chatClient, SimpleVectorStore vectorStore) { this.chatClient = chatClient; this.vectorStore = vectorStore; } AssistantMessage chatWithDocument(String message) { var systemPromptTemplate = new SystemPromptTemplate(""" You're assisting with questions about products in a bicycle catalog. Answer questions given the context information below (DOCUMENTS section) and no prior knowledge, but act as if you knew this information innately. If the answer is not found in the DOCUMENTS section, simply state that you don't know the answer. DOCUMENTS: {documents} """); List<Document> similarDocuments = vectorStore.similaritySearch(SearchRequest.query(message).withTopK(2)); String documents = similarDocuments.stream().map(Document::getContent).collect(Collectors.joining(System.lineSeparator())); Map<String,Object> model = Map.of("documents", documents); var systemMessage = systemPromptTemplate.createMessage(model); var userMessage = new UserMessage(message); var prompt = new Prompt(List.of(systemMessage, userMessage)); var chatResponse = chatClient.call(prompt); return chatResponse.getResult().getOutput(); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1539, 1579), 'org.springframework.ai.vectorstore.SearchRequest.query')]
package com.alok.ai.spring.ollama; import com.alok.ai.spring.model.Message; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/ollama/chat") @RestController public class OllamaChatController { private final OllamaApi ollamaApi; private final String model; private final OllamaApi.Message geographyTeacherRoleContextMessage = OllamaApi.Message.builder(OllamaApi.Message.Role.ASSISTANT) .withContent("You are geography teacher. You are talking to a student.") .build(); private final OllamaApi.Message historyTeacherRoleContextMessage = OllamaApi.Message.builder(OllamaApi.Message.Role.ASSISTANT) .withContent("You are history teacher. You are talking to a student.") .build(); @Autowired public OllamaChatController(OllamaApi ollamaApi, @Value("${spring.ai.ollama.chat.model}") String model) { this.ollamaApi = ollamaApi; this.model = model; } @PostMapping(value = "/teacher/geography") public ResponseEntity<OllamaApi.Message> chatWithGeographyTeacher( @RequestBody Message message ) { return ResponseEntity.ok(ollamaApi.chat(OllamaApi.ChatRequest.builder(model) .withStream(false) // not streaming .withMessages(List.of( geographyTeacherRoleContextMessage, OllamaApi.Message.builder(OllamaApi.Message.Role.USER) .withContent(message.question()) .build() ) ) .withOptions(OllamaOptions.create().withTemperature(0.9f)) .build()).message()); } @PostMapping(value = "/teacher/history") public ResponseEntity<OllamaApi.Message> chatWithHistoryTeacher( @RequestBody Message message ) { return ResponseEntity.ok(ollamaApi.chat(OllamaApi.ChatRequest.builder(model) .withStream(false) // not streaming .withMessages(List.of( historyTeacherRoleContextMessage, OllamaApi.Message.builder(OllamaApi.Message.Role.USER) .withContent(message.question()) .build() ) ) .withOptions(OllamaOptions.create().withTemperature(0.9f)) .build()).message()); } }
[ "org.springframework.ai.ollama.api.OllamaApi.Message.builder", "org.springframework.ai.ollama.api.OllamaOptions.create", "org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder" ]
[((661, 826), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((661, 805), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((661, 720), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 1063), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 1042), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((900, 959), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1477, 1993), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1968), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1893), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1548), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1477, 1513), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((1689, 1849), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1689, 1808), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1689, 1743), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((1923, 1967), 'org.springframework.ai.ollama.api.OllamaOptions.create'), ((2225, 2771), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2746), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2671), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2296), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2225, 2261), 'org.springframework.ai.ollama.api.OllamaApi.ChatRequest.builder'), ((2451, 2627), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2451, 2578), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2451, 2505), 'org.springframework.ai.ollama.api.OllamaApi.Message.builder'), ((2701, 2745), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
package com.example.springaivectorsearchqueryjson.services; import org.springframework.ai.document.Document; import org.springframework.ai.reader.JsonMetadataGenerator; import org.springframework.ai.reader.JsonReader; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class VectorService { @Autowired VectorStore vectorStore; @Value("classpath:/data/bikes.json") Resource bikesResouce; public List<Document> queryJSONVector(String query){ // read json file JsonReader jsonReader = new JsonReader(bikesResouce, new ProductMetadataGenerator(), "name","shortDescription", "description", "price","tags"); // create document object List<Document> documents = jsonReader.get(); // add to vectorstore vectorStore.add(documents); // query vector search List<Document> results = vectorStore.similaritySearch( SearchRequest.defaults() .withQuery(query) .withTopK(1) ); return results ; } public class ProductMetadataGenerator implements JsonMetadataGenerator { @Override public Map<String, Object> generate(Map<String, Object> jsonMap) { return Map.of("name", jsonMap.get("name"), "shortDescription", jsonMap.get("shortDescription")); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.defaults" ]
[((1301, 1406), 'org.springframework.ai.vectorstore.SearchRequest.defaults'), ((1301, 1368), 'org.springframework.ai.vectorstore.SearchRequest.defaults')]
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.openai; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Profile("openai") @Configuration public class OpenAiClientConfig { @Value("${ai-client.openai.api-key}") private String openAiApiKey; @Value("${ai-client.openai.chat.model}") private String openAiModelName; @Value("#{T(Float).parseFloat('${ai-client.openai.chat.temperature}')}") private float openAiTemperature; @Value("${ai-client.openai.chat.max-tokens}") private int openAiMaxTokens; @Bean public OpenAiApi openAiChatApi() { return new OpenAiApi(openAiApiKey); } @Bean OpenAiChatClient openAiChatClient(OpenAiApi openAiApi) { return new OpenAiChatClient(openAiApi, OpenAiChatOptions.builder() .withModel(openAiModelName) .withTemperature(openAiTemperature) .withMaxTokens(openAiMaxTokens) .build()) ; } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((1124, 1352), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1319), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1263), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((1124, 1203), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.openai; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * OpenAI Image autoconfiguration properties. * * @author Thomas Vitale * @since 0.8.0 */ @ConfigurationProperties(OpenAiImageProperties.CONFIG_PREFIX) public class OpenAiImageProperties extends OpenAiParentProperties { public static final String CONFIG_PREFIX = "spring.ai.openai.image"; /** * Enable OpenAI Image client. */ private boolean enabled = true; /** * Options for OpenAI Image API. */ @NestedConfigurationProperty private OpenAiImageOptions options = OpenAiImageOptions.builder().build(); public OpenAiImageOptions getOptions() { return options; } public void setOptions(OpenAiImageOptions options) { this.options = options; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((1375, 1411), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
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.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.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')]
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.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.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')]
/* * 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')]
/* * 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')]
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.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.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.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.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.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.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.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')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.chat; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Flux; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.document.MetadataMode; import org.springframework.ai.image.ImageMessage; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.openai.OpenAiAudioTranscriptionClient; import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.OpenAiEmbeddingClient; import org.springframework.ai.openai.OpenAiEmbeddingOptions; import org.springframework.ai.openai.OpenAiImageClient; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletion; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionChunk; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionFinishReason; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionMessage; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionMessage.Role; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionRequest; import org.springframework.ai.openai.api.OpenAiApi.Embedding; import org.springframework.ai.openai.api.OpenAiApi.EmbeddingList; import org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest; import org.springframework.ai.openai.api.OpenAiAudioApi; import org.springframework.ai.openai.api.OpenAiAudioApi.StructuredResponse; import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptResponseFormat; import org.springframework.ai.openai.api.OpenAiAudioApi.TranscriptionRequest; import org.springframework.ai.openai.api.OpenAiImageApi; import org.springframework.ai.openai.api.OpenAiImageApi.Data; import org.springframework.ai.openai.api.OpenAiImageApi.OpenAiImageRequest; import org.springframework.ai.openai.api.OpenAiImageApi.OpenAiImageResponse; import org.springframework.ai.openai.audio.transcription.AudioTranscriptionPrompt; import org.springframework.ai.openai.audio.transcription.AudioTranscriptionResponse; import org.springframework.ai.retry.RetryUtils; import org.springframework.ai.retry.TransientAiException; import org.springframework.core.io.ClassPathResource; import org.springframework.http.ResponseEntity; import org.springframework.retry.RetryCallback; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryListener; import org.springframework.retry.support.RetryTemplate; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.when; /** * @author Christian Tzolov */ @SuppressWarnings("unchecked") @ExtendWith(MockitoExtension.class) public class OpenAiRetryTests { private class TestRetryListener implements RetryListener { int onErrorRetryCount = 0; int onSuccessRetryCount = 0; @Override public <T, E extends Throwable> void onSuccess(RetryContext context, RetryCallback<T, E> callback, T result) { onSuccessRetryCount = context.getRetryCount(); } @Override public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) { onErrorRetryCount = context.getRetryCount(); } } private TestRetryListener retryListener; private RetryTemplate retryTemplate; private @Mock OpenAiApi openAiApi; private @Mock OpenAiAudioApi openAiAudioApi; private @Mock OpenAiImageApi openAiImageApi; private OpenAiChatClient chatClient; private OpenAiEmbeddingClient embeddingClient; private OpenAiAudioTranscriptionClient audioTranscriptionClient; private OpenAiImageClient imageClient; @BeforeEach public void beforeEach() { retryTemplate = RetryUtils.DEFAULT_RETRY_TEMPLATE; retryListener = new TestRetryListener(); retryTemplate.registerListener(retryListener); chatClient = new OpenAiChatClient(openAiApi, OpenAiChatOptions.builder().build(), null, retryTemplate); embeddingClient = new OpenAiEmbeddingClient(openAiApi, MetadataMode.EMBED, OpenAiEmbeddingOptions.builder().build(), retryTemplate); audioTranscriptionClient = new OpenAiAudioTranscriptionClient(openAiAudioApi, OpenAiAudioTranscriptionOptions.builder() .withModel("model") .withResponseFormat(TranscriptResponseFormat.JSON) .build(), retryTemplate); imageClient = new OpenAiImageClient(openAiImageApi, OpenAiImageOptions.builder().build(), retryTemplate); } @Test public void openAiChatTransientError() { var choice = new ChatCompletion.Choice(ChatCompletionFinishReason.STOP, 0, new ChatCompletionMessage("Response", Role.ASSISTANT), null); ChatCompletion expectedChatCompletion = new ChatCompletion("id", List.of(choice), 666l, "model", null, null, new OpenAiApi.Usage(10, 10, 10)); when(openAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedChatCompletion))); var result = chatClient.call(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiChatNonTransientError() { when(openAiApi.chatCompletionEntity(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.call(new Prompt("text"))); } @Test public void openAiChatStreamTransientError() { var choice = new ChatCompletionChunk.ChunkChoice(ChatCompletionFinishReason.STOP, 0, new ChatCompletionMessage("Response", Role.ASSISTANT), null); ChatCompletionChunk expectedChatCompletion = new ChatCompletionChunk("id", List.of(choice), 666l, "model", null, null); when(openAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(Flux.just(expectedChatCompletion)); var result = chatClient.stream(new Prompt("text")); assertThat(result).isNotNull(); assertThat(result.collectList().block().get(0).getResult().getOutput().getContent()).isSameAs("Response"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiChatStreamNonTransientError() { when(openAiApi.chatCompletionStream(isA(ChatCompletionRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> chatClient.stream(new Prompt("text"))); } @Test public void openAiEmbeddingTransientError() { EmbeddingList<Embedding> expectedEmbeddings = new EmbeddingList<>("list", List.of(new Embedding(0, List.of(9.9, 8.8))), "model", new OpenAiApi.Usage(10, 10, 10)); when(openAiApi.embeddings(isA(EmbeddingRequest.class))).thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedEmbeddings))); var result = embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null)); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput()).isEqualTo(List.of(9.9, 8.8)); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiEmbeddingNonTransientError() { when(openAiApi.embeddings(isA(EmbeddingRequest.class))) .thenThrow(new RuntimeException("Non Transient Error")); assertThrows(RuntimeException.class, () -> embeddingClient .call(new org.springframework.ai.embedding.EmbeddingRequest(List.of("text1", "text2"), null))); } @Test public void openAiAudioTranscriptionTransientError() { var expectedResponse = new StructuredResponse("nl", 6.7f, "Transcription Text", List.of(), List.of()); when(openAiAudioApi.createTranscription(isA(TranscriptionRequest.class), isA(Class.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedResponse))); AudioTranscriptionResponse result = audioTranscriptionClient .call(new AudioTranscriptionPrompt(new ClassPathResource("speech/jfk.flac"))); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput()).isEqualTo(expectedResponse.text()); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiAudioTranscriptionNonTransientError() { when(openAiAudioApi.createTranscription(isA(TranscriptionRequest.class), isA(Class.class))) .thenThrow(new RuntimeException("Transient Error 1")); assertThrows(RuntimeException.class, () -> audioTranscriptionClient .call(new AudioTranscriptionPrompt(new ClassPathResource("speech/jfk.flac")))); } @Test public void openAiImageTransientError() { var expectedResponse = new OpenAiImageResponse(678l, List.of(new Data("url678", "b64", "prompt"))); when(openAiImageApi.createImage(isA(OpenAiImageRequest.class))) .thenThrow(new TransientAiException("Transient Error 1")) .thenThrow(new TransientAiException("Transient Error 2")) .thenReturn(ResponseEntity.of(Optional.of(expectedResponse))); var result = imageClient.call(new ImagePrompt(List.of(new ImageMessage("Image Message")))); assertThat(result).isNotNull(); assertThat(result.getResult().getOutput().getUrl()).isEqualTo("url678"); assertThat(retryListener.onSuccessRetryCount).isEqualTo(2); assertThat(retryListener.onErrorRetryCount).isEqualTo(2); } @Test public void openAiImageNonTransientError() { when(openAiImageApi.createImage(isA(OpenAiImageRequest.class))) .thenThrow(new RuntimeException("Transient Error 1")); assertThrows(RuntimeException.class, () -> imageClient.call(new ImagePrompt(List.of(new ImageMessage("Image Message"))))); } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder", "org.springframework.ai.openai.OpenAiImageOptions.builder", "org.springframework.ai.openai.OpenAiEmbeddingOptions.builder" ]
[((4961, 4996), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((5101, 5141), 'org.springframework.ai.openai.OpenAiEmbeddingOptions.builder'), ((5243, 5379), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((5243, 5365), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((5243, 5309), 'org.springframework.ai.openai.OpenAiAudioTranscriptionOptions.builder'), ((5455, 5491), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.redis; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.ai.ResourceUtils; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import com.redis.testcontainers.RedisStackContainer; /** * @author Julien Ruaux */ @Testcontainers class RedisVectorStoreAutoConfigurationIT { @Container static RedisStackContainer redisContainer = new RedisStackContainer( RedisStackContainer.DEFAULT_IMAGE_NAME.withTag(RedisStackContainer.DEFAULT_TAG)); List<Document> documents = List.of( new Document(ResourceUtils.getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document(ResourceUtils.getText("classpath:/test/data/time.shelter.txt")), new Document( ResourceUtils.getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RedisVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.redis.index=myIdx") .withPropertyValues("spring.ai.vectorstore.redis.prefix=doc:"); @Test void addAndSearch() { contextRunner.withPropertyValues("spring.ai.vectorstore.redis.uri=" + redisContainer.getRedisURI()) .run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).isEmpty(); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((1756, 1835), 'com.redis.testcontainers.RedisStackContainer.DEFAULT_IMAGE_NAME.withTag'), ((2834, 2875), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3344, 3385), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.image; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.ai.image.ImageGeneration; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.image.ImageResponseMetadata; import org.springframework.ai.openai.OpenAiImageClient; import org.springframework.ai.openai.api.OpenAiImageApi; import org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestClient; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; /** * @author John Blum * @author Christian Tzolov * @since 0.7.0 */ @RestClientTest(OpenAiImageClientWithImageResponseMetadataTests.Config.class) public class OpenAiImageClientWithImageResponseMetadataTests { private static String TEST_API_KEY = "sk-1234567890"; @Autowired private OpenAiImageClient openAiImageClient; @Autowired private MockRestServiceServer server; @AfterEach void resetMockServer() { server.reset(); } @Test void aiResponseContainsImageResponseMetadata() { prepareMock(); ImagePrompt prompt = new ImagePrompt("Create an image of a mini golden doodle dog."); ImageResponse response = this.openAiImageClient.call(prompt); assertThat(response).isNotNull(); List<ImageGeneration> imageGenerations = response.getResults(); assertThat(imageGenerations).isNotNull(); assertThat(imageGenerations).hasSize(2); ImageResponseMetadata imageResponseMetadata = response.getMetadata(); assertThat(imageResponseMetadata).isNotNull(); Long created = imageResponseMetadata.created(); assertThat(created).isNotNull(); assertThat(created).isEqualTo(1589478378); ImageResponseMetadata responseMetadata = response.getMetadata(); assertThat(responseMetadata).isNotNull(); } private void prepareMock() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName(), "4000"); httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName(), "999"); httpHeaders.set(OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName(), "2d16h15m29s"); httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName(), "725000"); httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName(), "112358"); httpHeaders.set(OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName(), "27h55s451ms"); server.expect(requestTo("v1/images/generations")) .andExpect(method(HttpMethod.POST)) .andExpect(header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_API_KEY)) .andRespond(withSuccess(getJson(), MediaType.APPLICATION_JSON).headers(httpHeaders)); } private String getJson() { return """ { "created": 1589478378, "data": [ { "url": "https://upload.wikimedia.org/wikipedia/commons/4/4e/Mini_Golden_Doodle.jpg" }, { "url": "https://upload.wikimedia.org/wikipedia/commons/8/85/Goldendoodle_puppy_Marty.jpg" } ] } """; } @SpringBootConfiguration static class Config { @Bean public OpenAiImageApi imageGenerationApi(RestClient.Builder builder) { return new OpenAiImageApi("", TEST_API_KEY, builder); } @Bean public OpenAiImageClient openAiImageClient(OpenAiImageApi openAiImageApi) { return new OpenAiImageClient(openAiImageApi); } } }
[ "org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName", "org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName", "org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName", "org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName", "org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName", "org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName" ]
[((3237, 3293), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_LIMIT_HEADER.getName'), ((3322, 3382), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_REMAINING_HEADER.getName'), ((3410, 3466), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.REQUESTS_RESET_HEADER.getName'), ((3502, 3556), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_LIMIT_HEADER.getName'), ((3587, 3645), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_REMAINING_HEADER.getName'), ((3676, 3730), 'org.springframework.ai.openai.metadata.support.OpenAiApiResponseHeaders.TOKENS_RESET_HEADER.getName')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vertexai.gemini.tool; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.vertexai.gemini.VertexAiGeminiAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallback; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.ai.model.function.FunctionCallbackWrapper.Builder.SchemaType; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*") public class FunctionCallWithFunctionWrapperIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionWrapperIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.vertex.ai.gemini.project-id=" + System.getenv("VERTEX_AI_GEMINI_PROJECT_ID"), "spring.ai.vertex.ai.gemini.location=" + System.getenv("VERTEX_AI_GEMINI_LOCATION")) .withConfiguration(AutoConfigurations.of(VertexAiGeminiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.vertex.ai.gemini.chat.options.model=" + VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .run(context -> { VertexAiGeminiChatClient chatClient = context.getBean(VertexAiGeminiChatClient.class); var systemMessage = new SystemMessage(""" Use Multi-turn function calling. Answer for all listed locations. If the information was not fetched call the function again. Repeat at most 3 times. """); var userMessage = new UserMessage("What's the weather like in San Francisco, Paris and in Tokyo?"); ChatResponse response = chatClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("WeatherInfo").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", "10"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15", "15.0"); }); } @Configuration static class Config { @Bean public FunctionCallback weatherFunctionInfo() { return FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("WeatherInfo") .withSchemaType(SchemaType.OPEN_API_SCHEMA) .withDescription("Get the current weather in a given location") .build(); } } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue" ]
[((2721, 2777), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((3322, 3393), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3322, 3385), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3836, 4051), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3836, 4038), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3836, 3970), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3836, 3922), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.watsonx.api; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.springframework.ai.watsonx.WatsonxAiChatOptions; import java.util.List; /** * @author Pablo Sanchidrian Herrera * @author John Jairo Moreno Rojas */ public class WatsonxAiChatOptionTest { @Test public void testOptions() { WatsonxAiChatOptions options = WatsonxAiChatOptions.builder() .withDecodingMethod("sample") .withTemperature(1.2f) .withTopK(20) .withTopP(0.5f) .withMaxNewTokens(100) .withMinNewTokens(20) .withStopSequences(List.of("\n\n\n")) .withRepetitionPenalty(1.1f) .withRandomSeed(4) .build(); var optionsMap = options.toMap(); assertThat(optionsMap).containsEntry("decoding_method", "sample"); assertThat(optionsMap).containsEntry("temperature", 1.2); assertThat(optionsMap).containsEntry("top_k", 20); assertThat(optionsMap).containsEntry("top_p", 0.5); assertThat(optionsMap).containsEntry("max_new_tokens", 100); assertThat(optionsMap).containsEntry("min_new_tokens", 20); assertThat(optionsMap).containsEntry("stop_sequences", List.of("\n\n\n")); assertThat(optionsMap).containsEntry("repetition_penalty", 1.1); assertThat(optionsMap).containsEntry("random_seed", 4); } @Test public void testFilterOut() { WatsonxAiChatOptions options = WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build(); var mappedOptions = WatsonxAiChatOptions.filterNonSupportedFields(options.toMap()); assertThat(mappedOptions).doesNotContainEntry("model", "google/flan-ul2"); } }
[ "org.springframework.ai.watsonx.WatsonxAiChatOptions.builder" ]
[((1021, 1304), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1292), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1270), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1238), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1197), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1172), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1146), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1127), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1110), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1021, 1084), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1982, 2049), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder'), ((1982, 2041), 'org.springframework.ai.watsonx.WatsonxAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.mistralai.tool; import java.util.List; import java.util.Map; import java.util.function.Function; import com.fasterxml.jackson.annotation.JsonProperty; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.mistralai.MistralAiAutoConfiguration; import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.mistralai.MistralAiChatClient; import org.springframework.ai.mistralai.MistralAiChatOptions; import org.springframework.ai.mistralai.api.MistralAiApi; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "MISTRAL_AI_API_KEY", matches = ".*") class PaymentStatusBeanIT { private final Logger logger = LoggerFactory.getLogger(PaymentStatusBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.mistralai.apiKey=" + System.getenv("MISTRAL_AI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, MistralAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.mistralai.chat.options.model=" + MistralAiApi.ChatModel.LARGE.getValue()) .run(context -> { MistralAiChatClient chatClient = context.getBean(MistralAiChatClient.class); ChatResponse response = chatClient .call(new Prompt(List.of(new UserMessage("What's the status of my transaction with id T1001?")), MistralAiChatOptions.builder() .withFunction("retrievePaymentStatus") .withFunction("retrievePaymentDate") .build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("T1001"); assertThat(response.getResult().getOutput().getContent()).containsIgnoringCase("paid"); }); } // Assuming we have the following data public static final Map<String, StatusDate> DATA = Map.of("T1001", new StatusDate("Paid", "2021-10-05"), "T1002", new StatusDate("Unpaid", "2021-10-06"), "T1003", new StatusDate("Paid", "2021-10-07"), "T1004", new StatusDate("Paid", "2021-10-05"), "T1005", new StatusDate("Pending", "2021-10-08")); record StatusDate(String status, String date) { } @Configuration static class Config { public record Transaction(@JsonProperty(required = true, value = "transaction_id") String transactionId) { } public record Status(@JsonProperty(required = true, value = "status") String status) { } public record Date(@JsonProperty(required = true, value = "date") String date) { } @Bean @Description("Get payment status of a transaction") public Function<Transaction, Status> retrievePaymentStatus() { return (transaction) -> new Status(DATA.get(transaction.transactionId).status()); } @Bean @Description("Get payment date of a transaction") public Function<Transaction, Date> retrievePaymentDate() { return (transaction) -> new Date(DATA.get(transaction.transactionId).date()); } } }
[ "org.springframework.ai.mistralai.MistralAiChatOptions.builder", "org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue" ]
[((2623, 2662), 'org.springframework.ai.mistralai.api.MistralAiApi.ChatModel.LARGE.getValue'), ((2916, 3055), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((2916, 3038), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder'), ((2916, 2993), 'org.springframework.ai.mistralai.MistralAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.cohere.api; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import reactor.core.publisher.Flux; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatRequest.Truncate; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatResponse; import org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatResponse.Generation.FinishReason; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;; /** * @author Christian Tzolov */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class CohereChatBedrockApiIT { private CohereChatBedrockApi cohereChatApi = new CohereChatBedrockApi(CohereChatModel.COHERE_COMMAND_V14.id(), Region.US_EAST_1.id()); @Test public void requestBuilder() { CohereChatRequest request1 = new CohereChatRequest( "What is the capital of Bulgaria and what is the size? What it the national anthem?", 0.5f, 0.9f, 15, 40, List.of("END"), CohereChatRequest.ReturnLikelihoods.ALL, false, 1, null, Truncate.NONE); var request2 = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withTemperature(0.5f) .withTopP(0.9f) .withTopK(15) .withMaxTokens(40) .withStopSequences(List.of("END")) .withReturnLikelihoods(CohereChatRequest.ReturnLikelihoods.ALL) .withStream(false) .withNumGenerations(1) .withLogitBias(null) .withTruncate(Truncate.NONE) .build(); assertThat(request1).isEqualTo(request2); } @Test public void chatCompletion() { var request = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(false) .withTemperature(0.5f) .withTopP(0.8f) .withTopK(15) .withMaxTokens(100) .withStopSequences(List.of("END")) .withReturnLikelihoods(CohereChatRequest.ReturnLikelihoods.ALL) .withNumGenerations(3) .withLogitBias(null) .withTruncate(Truncate.NONE) .build(); CohereChatResponse response = cohereChatApi.chatCompletion(request); assertThat(response).isNotNull(); assertThat(response.prompt()).isEqualTo(request.prompt()); assertThat(response.generations()).hasSize(request.numGenerations()); assertThat(response.generations().get(0).text()).isNotEmpty(); } @Test public void chatCompletionStream() { var request = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(true) .withTemperature(0.5f) .withTopP(0.8f) .withTopK(15) .withMaxTokens(100) .withStopSequences(List.of("END")) .withReturnLikelihoods(CohereChatRequest.ReturnLikelihoods.ALL) .withNumGenerations(3) .withLogitBias(null) .withTruncate(Truncate.NONE) .build(); Flux<CohereChatResponse.Generation> responseStream = cohereChatApi.chatCompletionStream(request); List<CohereChatResponse.Generation> responses = responseStream.collectList().block(); assertThat(responses).isNotNull(); assertThat(responses).hasSizeGreaterThan(10); assertThat(responses.get(0).text()).isNotEmpty(); CohereChatResponse.Generation lastResponse = responses.get(responses.size() - 1); assertThat(lastResponse.text()).isNull(); assertThat(lastResponse.isFinished()).isTrue(); assertThat(lastResponse.finishReason()).isEqualTo(FinishReason.MAX_TOKENS); assertThat(lastResponse.amazonBedrockInvocationMetrics()).isNotNull(); } @Test public void testStreamConfigurations() { var streamRequest = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(true) .build(); assertThatThrownBy(() -> cohereChatApi.chatCompletion(streamRequest)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The request must be configured to return the complete response!"); var notStreamRequest = CohereChatRequest .builder("What is the capital of Bulgaria and what is the size? What it the national anthem?") .withStream(false) .build(); assertThatThrownBy(() -> cohereChatApi.chatCompletionStream(notStreamRequest)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The request must be configured to stream the response!"); } }
[ "org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id" ]
[((1787, 1826), 'org.springframework.ai.bedrock.cohere.api.CohereChatBedrockApi.CohereChatModel.COHERE_COMMAND_V14.id'), ((1831, 1852), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vertexai.gemini.tool; import java.util.List; import java.util.function.Function; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.vertexai.gemini.VertexAiGeminiAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.SystemMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_PROJECT_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "VERTEX_AI_GEMINI_LOCATION", matches = ".*") class FunctionCallWithFunctionBeanIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.vertex.ai.gemini.project-id=" + System.getenv("VERTEX_AI_GEMINI_PROJECT_ID"), "spring.ai.vertex.ai.gemini.location=" + System.getenv("VERTEX_AI_GEMINI_LOCATION")) .withConfiguration(AutoConfigurations.of(VertexAiGeminiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner .withPropertyValues("spring.ai.vertex.ai.gemini.chat.options.model=" + VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue()) .run(context -> { VertexAiGeminiChatClient chatClient = context.getBean(VertexAiGeminiChatClient.class); var systemMessage = new SystemMessage(""" Use Multi-turn function calling. Answer for all listed locations. If the information was not fetched call the function again. Repeat at most 3 times. """); var userMessage = new UserMessage( "What's the weather like in San Francisco, Paris and in Tokyo (Japan)?"); ChatResponse response = chatClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("weatherFunction").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); response = chatClient.call(new Prompt(List.of(systemMessage, userMessage), VertexAiGeminiChatOptions.builder().withFunction("weatherFunction3").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } @Configuration static class Config { @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction() { return new MockWeatherService(); } // Relies on the Request's JsonClassDescription annotation to provide the // function description. @Bean public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction3() { MockWeatherService weatherService = new MockWeatherService(); return (weatherService::apply); } } }
[ "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder", "org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue" ]
[((2583, 2639), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatClient.ChatModel.GEMINI_PRO.getValue'), ((3199, 3274), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3199, 3266), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3499, 3575), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder'), ((3499, 3567), 'org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.qdrant; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.qdrant.QdrantContainer; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.DefaultResourceLoader; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov * @since 0.8.1 */ @Testcontainers public class QdrantVectorStoreAutoConfigurationIT { private static final String COLLECTION_NAME = "test_collection"; private static final int QDRANT_GRPC_PORT = 6334; @Container static QdrantContainer qdrantContainer = new QdrantContainer("qdrant/qdrant:v1.7.4"); List<Document> documents = List.of( new Document(getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document(getText("classpath:/test/data/time.shelter.txt")), new Document(getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(QdrantVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.qdrant.port=" + qdrantContainer.getMappedPort(QDRANT_GRPC_PORT), "spring.ai.vectorstore.qdrant.host=" + qdrantContainer.getHost(), "spring.ai.vectorstore.qdrant.collectionName=" + COLLECTION_NAME); @Test public void addAndSearch() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore .similaritySearch(SearchRequest.query("What is Great Depression?").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId()); assertThat(resultDoc.getMetadata()).containsKeys("depression", "distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Great Depression").withTopK(1)); assertThat(results).hasSize(0); }); } public static String getText(String uri) { var resource = new DefaultResourceLoader().getResource(uri); try { return resource.getContentAsString(StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2991, 3051), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3440, 3491), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.transformer; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.ai.document.DefaultContentFormatter; import org.springframework.ai.document.Document; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.transformer.ContentFormatTransformer; import org.springframework.ai.transformer.KeywordMetadataEnricher; import org.springframework.ai.transformer.SummaryMetadataEnricher; import org.springframework.ai.transformer.SummaryMetadataEnricher.SummaryType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @SpringBootTest public class MetadataTransformerIT { @Autowired KeywordMetadataEnricher keywordMetadataEnricher; @Autowired SummaryMetadataEnricher summaryMetadataEnricher; @Autowired ContentFormatTransformer contentFormatTransformer; @Autowired DefaultContentFormatter defaultContentFormatter; Document document1 = new Document("Somewhere in the Andes, they believe to this very day that the" + " future is behind you. It comes up from behind your back, surprising and unforeseeable, while the past " + " is always before your eyes, that which has already happened. When they talk about the past, the people of" + " the Aymara tribe point in front of them. You walk forward facing the past and you turn back toward the future.", new HashMap<>(Map.of("key", "value"))); Document document2 = new Document( "The Spring Framework is divided into modules. Applications can choose which modules" + " they need. At the heart are the modules of the core container, including a configuration generative and a " + "dependency injection mechanism. Beyond that, the Spring Framework provides foundational support " + " for different application architectures, including messaging, transactional data and persistence, " + "and web. It also includes the Servlet-based Spring MVC web framework and, in parallel, the Spring " + "WebFlux reactive web framework."); @Test public void testKeywordExtractor() { var updatedDocuments = keywordMetadataEnricher.apply(List.of(document1, document2)); List<Map<String, Object>> keywords = updatedDocuments.stream().map(d -> d.getMetadata()).toList(); assertThat(updatedDocuments.size()).isEqualTo(2); var keywords1 = keywords.get(0); var keywords2 = keywords.get(1); assertThat(keywords1).containsKeys("excerpt_keywords"); assertThat(keywords2).containsKeys("excerpt_keywords"); assertThat((String) keywords1.get("excerpt_keywords")).contains("Andes", "Aymara"); assertThat((String) keywords2.get("excerpt_keywords")).contains("Spring Framework", "dependency injection"); } @Test public void testSummaryExtractor() { var updatedDocuments = summaryMetadataEnricher.apply(List.of(document1, document2)); List<Map<String, Object>> summaries = updatedDocuments.stream().map(d -> d.getMetadata()).toList(); assertThat(summaries.size()).isEqualTo(2); var summary1 = summaries.get(0); var summary2 = summaries.get(1); assertThat(summary1).containsKeys("section_summary", "next_section_summary"); assertThat(summary1).doesNotContainKeys("prev_section_summary"); assertThat(summary2).containsKeys("section_summary", "prev_section_summary"); assertThat(summary2).doesNotContainKeys("next_section_summary"); assertThat((String) summary1.get("section_summary")).isNotEmpty(); assertThat((String) summary1.get("next_section_summary")).isNotEmpty(); assertThat((String) summary2.get("section_summary")).isNotEmpty(); assertThat((String) summary2.get("prev_section_summary")).isNotEmpty(); assertThat((String) summary1.get("section_summary")).isEqualTo((String) summary2.get("prev_section_summary")); assertThat((String) summary1.get("next_section_summary")).isEqualTo((String) summary2.get("section_summary")); } @Test public void testContentFormatEnricher() { assertThat(((DefaultContentFormatter) document1.getContentFormatter()).getExcludedEmbedMetadataKeys()) .doesNotContain("NewEmbedKey"); assertThat(((DefaultContentFormatter) document1.getContentFormatter()).getExcludedInferenceMetadataKeys()) .doesNotContain("NewInferenceKey"); assertThat(((DefaultContentFormatter) document2.getContentFormatter()).getExcludedEmbedMetadataKeys()) .doesNotContain("NewEmbedKey"); assertThat(((DefaultContentFormatter) document2.getContentFormatter()).getExcludedInferenceMetadataKeys()) .doesNotContain("NewInferenceKey"); List<Document> enrichedDocuments = contentFormatTransformer.apply(List.of(document1, document2)); assertThat(enrichedDocuments.size()).isEqualTo(2); var doc1 = enrichedDocuments.get(0); var doc2 = enrichedDocuments.get(1); assertThat(doc1).isEqualTo(document1); assertThat(doc2).isEqualTo(document2); assertThat(((DefaultContentFormatter) doc1.getContentFormatter()).getTextTemplate()) .isSameAs(defaultContentFormatter.getTextTemplate()); assertThat(((DefaultContentFormatter) doc1.getContentFormatter()).getExcludedEmbedMetadataKeys()) .contains("NewEmbedKey"); assertThat(((DefaultContentFormatter) doc1.getContentFormatter()).getExcludedInferenceMetadataKeys()) .contains("NewInferenceKey"); assertThat(((DefaultContentFormatter) doc2.getContentFormatter()).getTextTemplate()) .isSameAs(defaultContentFormatter.getTextTemplate()); assertThat(((DefaultContentFormatter) doc2.getContentFormatter()).getExcludedEmbedMetadataKeys()) .contains("NewEmbedKey"); assertThat(((DefaultContentFormatter) doc2.getContentFormatter()).getExcludedInferenceMetadataKeys()) .contains("NewInferenceKey"); } @SpringBootConfiguration public static class OpenAiTestConfiguration { @Bean public OpenAiApi openAiApi() throws IOException { String apiKey = System.getenv("OPENAI_API_KEY"); if (!StringUtils.hasText(apiKey)) { throw new IllegalArgumentException( "You must provide an API key. Put it in an environment variable under the name OPENAI_API_KEY"); } return new OpenAiApi(apiKey); } @Bean public OpenAiChatClient openAiChatClient(OpenAiApi openAiApi) { OpenAiChatClient openAiChatClient = new OpenAiChatClient(openAiApi); return openAiChatClient; } @Bean public KeywordMetadataEnricher keywordMetadata(OpenAiChatClient aiClient) { return new KeywordMetadataEnricher(aiClient, 5); } @Bean public SummaryMetadataEnricher summaryMetadata(OpenAiChatClient aiClient) { return new SummaryMetadataEnricher(aiClient, List.of(SummaryType.PREVIOUS, SummaryType.CURRENT, SummaryType.NEXT)); } @Bean public DefaultContentFormatter defaultContentFormatter() { return DefaultContentFormatter.builder() .withExcludedEmbedMetadataKeys("NewEmbedKey") .withExcludedInferenceMetadataKeys("NewInferenceKey") .build(); } @Bean public ContentFormatTransformer contentFormatTransformer(DefaultContentFormatter defaultContentFormatter) { return new ContentFormatTransformer(defaultContentFormatter, false); } } }
[ "org.springframework.ai.document.DefaultContentFormatter.builder" ]
[((7727, 7881), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((7727, 7868), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((7727, 7810), 'org.springframework.ai.document.DefaultContentFormatter.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.openai.tool; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration; import org.springframework.ai.autoconfigure.retry.SpringAiRetryAutoConfiguration; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.AssistantMessage; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallingOptions; import org.springframework.ai.model.function.FunctionCallingOptionsBuilder.PortableFunctionCallingOptions; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.web.client.RestClientAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".*") class FunctionCallbackWithPlainFunctionBeanIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallbackWithPlainFunctionBeanIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.openai.apiKey=" + System.getenv("OPENAI_API_KEY")) .withConfiguration(AutoConfigurations.of(SpringAiRetryAutoConfiguration.class, RestClientAutoConfiguration.class, OpenAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); // Test weatherFunction UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunction").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); // Test weatherFunctionTwo response = chatClient.call(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunctionTwo").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).contains("30", "10", "15"); }); } @Test void functionCallWithPortableFunctionCallingOptions() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); // Test weatherFunction UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); PortableFunctionCallingOptions functionOptions = FunctionCallingOptions.builder() .withFunction("weatherFunction") .build(); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), functionOptions)); logger.info("Response: {}", response); }); } @Test void streamFunctionCallTest() { contextRunner.withPropertyValues("spring.ai.openai.chat.options.model=gpt-4-turbo-preview").run(context -> { OpenAiChatClient chatClient = context.getBean(OpenAiChatClient.class); // Test weatherFunction UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?"); Flux<ChatResponse> response = chatClient.stream(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunction").build())); String content = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", content); assertThat(content).containsAnyOf("30.0", "30"); assertThat(content).containsAnyOf("10.0", "10"); assertThat(content).containsAnyOf("15.0", "15"); // Test weatherFunctionTwo response = chatClient.stream(new Prompt(List.of(userMessage), OpenAiChatOptions.builder().withFunction("weatherFunctionTwo").build())); content = response.collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); logger.info("Response: {}", content); assertThat(content).containsAnyOf("30.0", "30"); assertThat(content).containsAnyOf("10.0", "10"); assertThat(content).containsAnyOf("15.0", "15"); }); } @Configuration static class Config { @Bean @Description("Get the weather in location") public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunction() { return new MockWeatherService(); } // Relies on the Request's JsonClassDescription annotation to provide the // function description. @Bean public Function<MockWeatherService.Request, MockWeatherService.Response> weatherFunctionTwo() { MockWeatherService weatherService = new MockWeatherService(); return (weatherService::apply); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallingOptions.builder" ]
[((3172, 3239), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3172, 3231), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3475, 3545), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((3475, 3537), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((4133, 4215), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((4133, 4202), 'org.springframework.ai.model.function.FunctionCallingOptions.builder'), ((4819, 4886), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((4819, 4878), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((5429, 5499), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((5429, 5491), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.llama2; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.AssistantMessage; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi; import org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel; import org.springframework.ai.chat.Generation; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.ai.parser.ListOutputParser; import org.springframework.ai.parser.MapOutputParser; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.io.Resource; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") class BedrockLlama2ChatClientIT { @Autowired private BedrockLlama2ChatClient client; @Value("classpath:/prompts/system-message.st") private Resource systemResource; @Test void roleTest() { UserMessage userMessage = new UserMessage( "Tell me about 3 famous pirates from the Golden Age of Piracy and why they did."); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource); Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Bob", "voice", "pirate")); Prompt prompt = new Prompt(List.of(userMessage, systemMessage)); ChatResponse response = client.call(prompt); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void outputParser() { DefaultConversionService conversionService = new DefaultConversionService(); ListOutputParser outputParser = new ListOutputParser(conversionService); String format = outputParser.getFormat(); String template = """ List five {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "ice cream flavors.", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = this.client.call(prompt).getResult(); List<String> list = outputParser.parse(generation.getOutput().getContent()); assertThat(list).hasSize(5); } @Test void mapOutputParser() { MapOutputParser outputParser = new MapOutputParser(); String format = outputParser.getFormat(); String template = """ Provide me a List of {subject} {format} """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); Map<String, Object> result = outputParser.parse(generation.getOutput().getContent()); assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)); } record ActorsFilmsRecord(String actor, List<String> movies) { } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void beanOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove non JSON tex blocks from the output. Provide your answer in the JSON format with the feature names as the keys. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); Generation generation = client.call(prompt).getResult(); ActorsFilmsRecord actorsFilms = outputParser.parse(generation.getOutput().getContent()); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @Disabled("TODO: Fix the parser instructions to return the correct format") @Test void beanStreamOutputParserRecords() { BeanOutputParser<ActorsFilmsRecord> outputParser = new BeanOutputParser<>(ActorsFilmsRecord.class); String format = outputParser.getFormat(); String template = """ Generate the filmography of 5 movies for Tom Hanks. {format} Remove Markdown code blocks from the output. """; PromptTemplate promptTemplate = new PromptTemplate(template, Map.of("format", format)); Prompt prompt = new Prompt(promptTemplate.createMessage()); String generationTextFromStream = client.stream(prompt) .collectList() .block() .stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); ActorsFilmsRecord actorsFilms = outputParser.parse(generationTextFromStream); System.out.println(actorsFilms); assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks"); assertThat(actorsFilms.movies()).hasSize(5); } @SpringBootConfiguration public static class TestConfiguration { @Bean public Llama2ChatBedrockApi llama2Api() { return new Llama2ChatBedrockApi(Llama2ChatModel.LLAMA2_70B_CHAT_V1.id(), EnvironmentVariableCredentialsProvider.create(), Region.US_EAST_1.id(), new ObjectMapper()); } @Bean public BedrockLlama2ChatClient llama2ChatClient(Llama2ChatBedrockApi llama2Api) { return new BedrockLlama2ChatClient(llama2Api, BedrockLlama2ChatOptions.builder().withTemperature(0.5f).withMaxGenLen(100).withTopP(0.9f).build()); } } }
[ "org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id" ]
[((6861, 6900), 'org.springframework.ai.bedrock.llama2.api.Llama2ChatBedrockApi.Llama2ChatModel.LLAMA2_70B_CHAT_V1.id'), ((6956, 6977), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.chroma; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @Testcontainers public class ChromaVectorStoreAutoConfigurationIT { @Container static GenericContainer<?> chromaContainer = new GenericContainer<>("ghcr.io/chroma-core/chroma:0.4.15") .withExposedPorts(8000); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ChromaVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.ai.vectorstore.chroma.client.host=http://" + chromaContainer.getHost(), "spring.ai.vectorstore.chroma.client.port=" + chromaContainer.getMappedPort(8000), "spring.ai.vectorstore.chroma.store.collectionName=TestCollection"); @Test public void addAndSearchWithFilters() { contextRunner.run(context -> { VectorStore vectorStore = context.getBean(VectorStore.class); var bgDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Bulgaria")); var nlDocument = new Document("The World is Big and Salvation Lurks Around the Corner", Map.of("country", "Netherlands")); vectorStore.add(List.of(bgDocument, nlDocument)); var request = SearchRequest.query("The World").withTopK(5); List<Document> results = vectorStore.similaritySearch(request); assertThat(results).hasSize(2); results = vectorStore .similaritySearch(request.withSimilarityThresholdAll().withFilterExpression("country == 'Bulgaria'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(bgDocument.getId()); results = vectorStore.similaritySearch( request.withSimilarityThresholdAll().withFilterExpression("country == 'Netherlands'")); assertThat(results).hasSize(1); assertThat(results.get(0).getId()).isEqualTo(nlDocument.getId()); // Remove all documents from the store vectorStore.delete(List.of(bgDocument, nlDocument).stream().map(doc -> doc.getId()).toList()); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2742, 2786), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3434, 3507), 'java.util.List.of'), ((3434, 3498), 'java.util.List.of'), ((3434, 3474), 'java.util.List.of')]
package com.example.carina.data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.PagePdfDocumentReader; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import org.springframework.util.Assert; @Service public class DataLoadingService { private static final Logger logger = LoggerFactory.getLogger(DataLoadingService.class); @Value("classpath:/data/medicaid-wa-faqs.pdf") private Resource pdfResource; private final VectorStore vectorStore; @Autowired public DataLoadingService(VectorStore vectorStore) { Assert.notNull(vectorStore, "VectorStore must not be null."); this.vectorStore = vectorStore; } public void load() { PagePdfDocumentReader pdfReader = new PagePdfDocumentReader( this.pdfResource, PdfDocumentReaderConfig.builder() .withPageExtractedTextFormatter(ExtractedTextFormatter.builder() .withNumberOfBottomTextLinesToDelete(3) .withNumberOfTopPagesToSkipBeforeDelete(1) // .withLeftAlignment(true) .build()) .withPagesPerDocument(1) .build()); var textSplitter = new TokenTextSplitter(); logger.info("Parsing document, splitting, creating embeddings and storing in vector store... this will take a while."); this.vectorStore.accept( textSplitter.apply( pdfReader.get())); logger.info("Done parsing document, splitting, creating embeddings and storing in vector store"); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((1268, 1721), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1268, 1688), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1268, 1639), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1358, 1638), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1358, 1537), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1358, 1462), 'org.springframework.ai.reader.ExtractedTextFormatter.builder')]
/** * Copyright 2023 Sven Loesekann Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ch.xxx.aidoclibchat.adapter.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.stream.IntStream; import org.postgresql.util.PGobject; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.PgVectorStore; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.ai.vectorstore.filter.Filter; import org.springframework.ai.vectorstore.filter.Filter.ExpressionType; import org.springframework.ai.vectorstore.filter.Filter.Key; import org.springframework.ai.vectorstore.filter.Filter.Value; import org.springframework.ai.vectorstore.filter.FilterExpressionConverter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.pgvector.PGvector; import ch.xxx.aidoclibchat.domain.common.MetaData; import ch.xxx.aidoclibchat.domain.common.MetaData.DataType; import ch.xxx.aidoclibchat.domain.model.entity.DocumentVsRepository; @Repository public class DocumentVSRepositoryBean implements DocumentVsRepository { private final String vectorTableName; private final VectorStore vectorStore; private final JdbcTemplate jdbcTemplate; private final ObjectMapper objectMapper; private final FilterExpressionConverter filterExpressionConverter; public DocumentVSRepositoryBean(JdbcTemplate jdbcTemplate, EmbeddingClient embeddingClient, ObjectMapper objectMapper) { this.jdbcTemplate = jdbcTemplate; this.objectMapper = objectMapper; this.vectorStore = new PgVectorStore(jdbcTemplate, embeddingClient); this.filterExpressionConverter = ((PgVectorStore) this.vectorStore).filterExpressionConverter; this.vectorTableName = PgVectorStore.VECTOR_TABLE_NAME; } @Override public void add(List<Document> documents) { this.vectorStore.add(documents); } @Override public List<Document> retrieve(String query, DataType dataType, int k, double threshold) { return this.vectorStore .similaritySearch(SearchRequest .query(query).withFilterExpression(new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString()))) .withTopK(k).withSimilarityThreshold(threshold)); } @Override public List<Document> retrieve(String query, DataType dataType, int k) { return this.vectorStore.similaritySearch(SearchRequest.query(query).withFilterExpression( new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString()))) .withTopK(k)); } @Override public List<Document> retrieve(String query, DataType dataType) { return this.vectorStore.similaritySearch(SearchRequest.query(query).withFilterExpression( new Filter.Expression(ExpressionType.EQ, new Key(MetaData.DATATYPE), new Value(dataType.toString())))); } @Override public List<Document> findAllTableDocuments() { String nativeFilterExpression = this.filterExpressionConverter.convertExpression(new Filter.Expression(ExpressionType.NE, new Key(MetaData.DATATYPE), new Value(DataType.DOCUMENT.toString()))); String jsonPathFilter = " WHERE metadata::jsonb @@ '" + nativeFilterExpression + "'::jsonpath "; return this.jdbcTemplate.query( String.format("SELECT * FROM %s %s LIMIT ? ", this.vectorTableName, jsonPathFilter), new DocumentRowMapper(this.objectMapper), 100000); } @Override public void deleteByIds(List<String> ids) { this.vectorStore.delete(ids); } private static class DocumentRowMapper implements RowMapper<Document> { private static final String COLUMN_EMBEDDING = "embedding"; private static final String COLUMN_METADATA = "metadata"; private static final String COLUMN_ID = "id"; private static final String COLUMN_CONTENT = "content"; private ObjectMapper objectMapper; public DocumentRowMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public Document mapRow(ResultSet rs, int rowNum) throws SQLException { String id = rs.getString(COLUMN_ID); String content = rs.getString(COLUMN_CONTENT); PGobject pgMetadata = rs.getObject(COLUMN_METADATA, PGobject.class); PGobject embedding = rs.getObject(COLUMN_EMBEDDING, PGobject.class); Map<String, Object> metadata = toMap(pgMetadata); Document document = new Document(id, content, metadata); document.setEmbedding(toDoubleList(embedding)); return document; } private List<Double> toDoubleList(PGobject embedding) throws SQLException { float[] floatArray = new PGvector(embedding.getValue()).toArray(); return IntStream.range(0, floatArray.length).mapToDouble(i -> floatArray[i]).boxed().toList(); } @SuppressWarnings("unchecked") private Map<String, Object> toMap(PGobject pgObject) { String source = pgObject.getValue(); try { return (Map<String, Object>) objectMapper.readValue(source, Map.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3233, 3404), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3233, 3387), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3532, 3686), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3919, 3947), 'ch.xxx.aidoclibchat.domain.common.MetaData.DataType.DOCUMENT.toString'), ((5441, 5527), 'java.util.stream.IntStream.range'), ((5441, 5518), 'java.util.stream.IntStream.range'), ((5441, 5510), 'java.util.stream.IntStream.range')]
package com.example.pdfsimilaritysearch; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentReader; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.PagePdfDocumentReader; import org.springframework.ai.reader.pdf.ParagraphPdfDocumentReader; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.task.TaskExecutor; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class UploadController { private final VectorStore vectorStore; private final Resource uploadDir; private final TaskExecutor taskExecutor; private final Logger logger = LoggerFactory.getLogger(UploadController.class); private final ConcurrentMap<String, UploadTask> uploadTaskMap = new ConcurrentHashMap<>(); public UploadController(VectorStore vectorStore, @Value("${upload.dir:file:/tmp}") Resource uploadDir, TaskExecutor taskExecutor) { this.vectorStore = vectorStore; this.uploadDir = uploadDir; this.taskExecutor = taskExecutor; } @GetMapping("/upload") public String index() { return "upload"; } @GetMapping(path = "/upload/{id}/progress") public SseEmitter uploadProgress(@PathVariable String id) { UploadTask uploadTask = this.uploadTaskMap.get(id); if (uploadTask == null) { throw new ResponseStatusException(HttpStatus.GONE, "The requested task has gone."); } if (!uploadTask.isStarted().compareAndSet(false, true)) { throw new ResponseStatusException(HttpStatus.GONE, "The requested task has already started."); } SseEmitter emitter = new SseEmitter(TimeUnit.HOURS.toMillis(1)); emitter.onTimeout(() -> logger.warn("Timeout! ID: {}", uploadTask.id())); emitter.onError(ex -> logger.error("Error! ID: " + uploadTask.id(), ex)); this.taskExecutor.execute(() -> { logger.info("Started the task ID: {}", uploadTask.id()); try { for (Path path : uploadTask.paths()) { Resource resource = new FileSystemResource(path); DocumentReader documentReader; emitter.send(SseEmitter.event() .name("message") .data("βŒ›οΈ Adding %s to the vector store.".formatted(path.getFileName()))); try { documentReader = new ParagraphPdfDocumentReader(resource); } catch (RuntimeException e) { documentReader = new PagePdfDocumentReader(resource, PdfDocumentReaderConfig.builder() .withPagesPerDocument(2) .withPageExtractedTextFormatter( ExtractedTextFormatter.builder().withNumberOfBottomTextLinesToDelete(2).build()) .build()); } emitter.send(SseEmitter.event() .name("message") .data("Use %s as the document reader.".formatted(documentReader.getClass()))); List<Document> documents = documentReader.get(); for (int i = 0; i < documents.size(); i++) { Document document = documents.get(i); // TODO Batch processing this.vectorStore.add(List.of(document)); if ((i + 1) % 10 == 0) { emitter.send(SseEmitter.event() .name("message") .data("%d%% done".formatted(100 * (i + 1) / documents.size()))); } } emitter.send(SseEmitter.event() .name("message") .data("βœ… Added %s to the vector store.".formatted(path.getFileName()))); } emitter.send("Completed πŸŽ‰"); emitter.complete(); } catch (Exception ex) { logger.error("Task failed", ex); emitter.completeWithError(ex); } finally { this.uploadTaskMap.remove(id); } logger.info("Finished the task ID: {}", uploadTask.id()); }); return emitter; } @PostMapping("/upload") public String upload(@RequestParam("files") MultipartFile[] files, RedirectAttributes redirectAttributes) throws Exception { List<Path> paths = new ArrayList<>(); for (MultipartFile file : files) { if (file.isEmpty()) { continue; } byte[] bytes = file.getBytes(); Path path = this.uploadDir.getFile().toPath().resolve(Objects.requireNonNull(file.getOriginalFilename())); Files.write(path, bytes); paths.add(path); } String id = UUID.randomUUID().toString(); this.uploadTaskMap.computeIfAbsent(id, k -> new UploadTask(id, paths, new AtomicBoolean(false))); redirectAttributes .addFlashAttribute("message", "Files have been uploaded. Next, add the uploaded files to the vector store.") .addFlashAttribute("id", id); return "redirect:/upload"; } record UploadTask(String id, List<Path> paths, AtomicBoolean isStarted) { } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((2799, 2825), 'java.util.concurrent.TimeUnit.HOURS.toMillis'), ((3237, 3361), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((3237, 3278), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((3540, 3751), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3540, 3735), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3540, 3605), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((3655, 3734), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((3655, 3726), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((3779, 3903), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((3779, 3820), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4183, 4297), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4183, 4226), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4333, 4453), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4333, 4374), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((5259, 5287), 'java.util.UUID.randomUUID')]
package com.ea.ai.rag.dms.infrastructure.repository.config.aiClient.ollama.chat; import org.springframework.ai.ollama.OllamaEmbeddingClient; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Profile("ollama-chat") @Configuration public class OllamaChatEmbeddingClientConfig { @Value("${ai-client.ollama.chat.options.model}") private String ollamaOptionsModelName; private final OllamaApi ollamaApi; public OllamaChatEmbeddingClientConfig(OllamaApi ollamaApi) { this.ollamaApi = ollamaApi; } @Bean @Primary public OllamaEmbeddingClient ollamaChatEmbeddingClient() { return new OllamaEmbeddingClient(ollamaApi) .withDefaultOptions(OllamaOptions.create() .withModel(ollamaOptionsModelName)); } }
[ "org.springframework.ai.ollama.api.OllamaOptions.create" ]
[((1038, 1119), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
package xyz.austinatchley.poesie.client; import org.springframework.ai.openai.OpenAiImageClient; import org.springframework.ai.openai.OpenAiImageOptions; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import xyz.austinatchley.poesie.entity.ImageEntity; import org.apache.commons.lang3.StringUtils; import org.springframework.ai.chat.prompt.PromptTemplate; import org.springframework.ai.image.Image; import org.springframework.ai.image.ImageGeneration; import org.springframework.ai.image.ImageOptions; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.parser.BeanOutputParser; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import lombok.NonNull; @Component @Log4j2 @RequiredArgsConstructor public class PoesieOpenAiImageClient implements PoesieImageClient { private static final ImageOptions DEFAULT_IMAGE_OPTIONS = OpenAiImageOptions.builder() .withResponseFormat("url") .build(); private final OpenAiImageClient imageClient; @Override public ImageEntity generateImageResponse(@NonNull final String topic) { final ImagePrompt prompt = generatePrompt(topic, null); return sendRequest(prompt); } @Override public ImageEntity generateImageResponse(@NonNull final String topic, @NonNull final String poem) { final ImagePrompt prompt = generatePrompt(topic, poem); return sendRequest(prompt); } private ImagePrompt generatePrompt(@NonNull final String topic, @Nullable final String poem) { String templateText = """ Create an image to accompany a haiku in an ancient temple hidden in the misty forest. The image should be in the traditional Japanese style, created by a master of the medium after 100 years of pondering the haiku. The theme for both the haiku and image is: {topic}. """; if (StringUtils.isNotBlank(poem)) { templateText += """ The poem is: {text} """; } final PromptTemplate template = new PromptTemplate(templateText); template.add("topic", topic); if (StringUtils.isNotBlank(poem)) { template.add("text", poem); } final String promptText = template.create().getContents(); log.info("Generated prompt: {}", promptText); return new ImagePrompt(promptText, DEFAULT_IMAGE_OPTIONS); } private ImageEntity sendRequest(@NonNull final ImagePrompt prompt) { log.info("Sending OpenAI request with prompt: {}", prompt); ImageResponse response = imageClient.call(prompt); log.info("OpenAI response: {}", response); ImageGeneration imageGeneration = response.getResult(); log.info("Extracted image generation from response: {}", imageGeneration); log.info(imageGeneration.getOutput()); final Image image = imageGeneration.getOutput(); final String url = image.getUrl(); final String metadata = imageGeneration.getMetadata().toString(); return new ImageEntity(url, metadata); } }
[ "org.springframework.ai.openai.OpenAiImageOptions.builder" ]
[((977, 1065), 'org.springframework.ai.openai.OpenAiImageOptions.builder'), ((977, 1044), 'org.springframework.ai.openai.OpenAiImageOptions.builder')]
package com.kousenit.springaiexamples.rag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatClient; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.document.Document; import org.springframework.ai.document.DocumentReader; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.reader.TextReader; import org.springframework.ai.transformer.splitter.TextSplitter; import org.springframework.ai.transformer.splitter.TokenTextSplitter; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import java.io.File; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Service public class PossService { private static final Logger logger = LoggerFactory.getLogger(RagService.class); @Value("classpath:/data/chapter3_poss.txt") private Resource chapterResource; @Value("classpath:/prompts/quiz-prompt.st") private Resource quizPrompt; private final ChatClient aiClient; private final EmbeddingClient embeddingClient; @Autowired public PossService(@Qualifier("openAiChatClient") ChatClient aiClient, @Qualifier("openAiEmbeddingClient") EmbeddingClient embeddingClient) { this.aiClient = aiClient; this.embeddingClient = embeddingClient; } public Generation retrieve(String message) { SimpleVectorStore vectorStore = new SimpleVectorStore(embeddingClient); File possVectorStore = new File("src/main/resources/data/possVectorStore.json"); if (possVectorStore.exists()) { vectorStore.load(possVectorStore); } else { DocumentReader documentReader = new TextReader(chapterResource); List<Document> documents = documentReader.get(); TextSplitter splitter = new TokenTextSplitter(); List<Document> splitDocuments = splitter.apply(documents); logger.info("Creating Embeddings..."); vectorStore.add(splitDocuments); logger.info("Embeddings created."); vectorStore.save(possVectorStore); } List<Document> similarDocuments = vectorStore.similaritySearch( SearchRequest.query(message).withTopK(4)); Message systemMessage = getSystemMessage(similarDocuments, message); UserMessage userMessage = new UserMessage(message); Prompt prompt = new Prompt(List.of(systemMessage, userMessage)); ChatResponse response = aiClient.call(prompt); logger.info(response.getResult().toString()); return response.getResult(); } private Message getSystemMessage(List<Document> similarDocuments, String message) { String documents = similarDocuments.stream() .map(Document::getContent) .collect(Collectors.joining("\n")); SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(quizPrompt); return systemPromptTemplate.createMessage( Map.of("documents", documents, "topic", message)); } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((2848, 2888), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.ollama; import org.springframework.ai.ollama.api.OllamaOptions; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * Ollama Chat autoconfiguration properties. * * @author Christian Tzolov * @since 0.8.0 */ @ConfigurationProperties(OllamaChatProperties.CONFIG_PREFIX) public class OllamaChatProperties { public static final String CONFIG_PREFIX = "spring.ai.ollama.chat"; /** * Enable Ollama chat client. */ private boolean enabled = true; /** * Client lever Ollama options. Use this property to configure generative temperature, * topK and topP and alike parameters. The null values are ignored defaulting to the * generative's defaults. */ @NestedConfigurationProperty private OllamaOptions options = OllamaOptions.create().withModel(OllamaOptions.DEFAULT_MODEL); public String getModel() { return this.options.getModel(); } public void setModel(String model) { this.options.setModel(model); } public OllamaOptions getOptions() { return this.options; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return this.enabled; } }
[ "org.springframework.ai.ollama.api.OllamaOptions.create" ]
[((1503, 1564), 'org.springframework.ai.ollama.api.OllamaOptions.create')]
package com.thomasvitale.ai.spring; import org.springframework.ai.document.DefaultContentFormatter; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.vectorstore.SimpleVectorStore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class DocumentTransformersMetadataOllamaApplication { @Bean DefaultContentFormatter defaultContentFormatter() { return DefaultContentFormatter.builder() .withExcludedEmbedMetadataKeys("NewEmbedKey") .withExcludedInferenceMetadataKeys("NewInferenceKey") .build(); } @Bean SimpleVectorStore documentWriter(EmbeddingClient embeddingClient) { return new SimpleVectorStore(embeddingClient); } public static void main(String[] args) { SpringApplication.run(DocumentTransformersMetadataOllamaApplication.class, args); } }
[ "org.springframework.ai.document.DefaultContentFormatter.builder" ]
[((558, 748), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((558, 723), 'org.springframework.ai.document.DefaultContentFormatter.builder'), ((558, 653), 'org.springframework.ai.document.DefaultContentFormatter.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.stabilityai; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.image.Image; import org.springframework.ai.image.ImageClient; import org.springframework.ai.image.ImageGeneration; import org.springframework.ai.image.ImageOptions; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.image.ImageResponse; import org.springframework.ai.image.ImageResponseMetadata; import org.springframework.ai.model.ModelOptionsUtils; import org.springframework.ai.stabilityai.api.StabilityAiApi; import org.springframework.ai.stabilityai.api.StabilityAiImageOptions; import org.springframework.util.Assert; /** * StabilityAiImageClient is a class that implements the ImageClient interface. It * provides a client for calling the StabilityAI image generation API. */ public class StabilityAiImageClient implements ImageClient { private final Logger logger = LoggerFactory.getLogger(getClass()); private StabilityAiImageOptions options; private final StabilityAiApi stabilityAiApi; public StabilityAiImageClient(StabilityAiApi stabilityAiApi) { this(stabilityAiApi, StabilityAiImageOptions.builder().build()); } public StabilityAiImageClient(StabilityAiApi stabilityAiApi, StabilityAiImageOptions options) { Assert.notNull(stabilityAiApi, "StabilityAiApi must not be null"); Assert.notNull(options, "StabilityAiImageOptions must not be null"); this.stabilityAiApi = stabilityAiApi; this.options = options; } public StabilityAiImageOptions getOptions() { return this.options; } /** * Calls the StabilityAiImageClient with the given StabilityAiImagePrompt and returns * the ImageResponse. This overloaded call method lets you pass the full set of Prompt * instructions that StabilityAI supports. * @param imagePrompt the StabilityAiImagePrompt containing the prompt and image model * options * @return the ImageResponse generated by the StabilityAiImageClient */ public ImageResponse call(ImagePrompt imagePrompt) { ImageOptions runtimeOptions = imagePrompt.getOptions(); // Merge the runtime options passed via the prompt with the StabilityAiImageClient // options configured via Autoconfiguration. // Runtime options overwrite StabilityAiImageClient options StabilityAiImageOptions optionsToUse = ModelOptionsUtils.merge(runtimeOptions, this.options, StabilityAiImageOptions.class); // Copy the org.springframework.ai.model derived ImagePrompt and ImageOptions data // types to the data types used in StabilityAiApi StabilityAiApi.GenerateImageRequest generateImageRequest = getGenerateImageRequest(imagePrompt, optionsToUse); // Make the request StabilityAiApi.GenerateImageResponse generateImageResponse = this.stabilityAiApi .generateImage(generateImageRequest); // Convert to org.springframework.ai.model derived ImageResponse data type return convertResponse(generateImageResponse); } private static StabilityAiApi.GenerateImageRequest getGenerateImageRequest(ImagePrompt stabilityAiImagePrompt, StabilityAiImageOptions optionsToUse) { StabilityAiApi.GenerateImageRequest.Builder builder = new StabilityAiApi.GenerateImageRequest.Builder(); StabilityAiApi.GenerateImageRequest generateImageRequest = builder .withTextPrompts(stabilityAiImagePrompt.getInstructions() .stream() .map(message -> new StabilityAiApi.GenerateImageRequest.TextPrompts(message.getText(), message.getWeight())) .collect(Collectors.toList())) .withHeight(optionsToUse.getHeight()) .withWidth(optionsToUse.getWidth()) .withCfgScale(optionsToUse.getCfgScale()) .withClipGuidancePreset(optionsToUse.getClipGuidancePreset()) .withSampler(optionsToUse.getSampler()) .withSamples(optionsToUse.getN()) .withSeed(optionsToUse.getSeed()) .withSteps(optionsToUse.getSteps()) .withStylePreset(optionsToUse.getStylePreset()) .build(); return generateImageRequest; } private ImageResponse convertResponse(StabilityAiApi.GenerateImageResponse generateImageResponse) { List<ImageGeneration> imageGenerationList = generateImageResponse.artifacts().stream().map(entry -> { return new ImageGeneration(new Image(null, entry.base64()), new StabilityAiImageGenerationMetadata(entry.finishReason(), entry.seed())); }).toList(); return new ImageResponse(imageGenerationList, ImageResponseMetadata.NULL); } private StabilityAiImageOptions convertOptions(ImageOptions runtimeOptions) { StabilityAiImageOptions.Builder builder = StabilityAiImageOptions.builder(); if (runtimeOptions == null) { return builder.build(); } if (runtimeOptions.getN() != null) { builder.withN(runtimeOptions.getN()); } if (runtimeOptions.getModel() != null) { builder.withModel(runtimeOptions.getModel()); } if (runtimeOptions.getResponseFormat() != null) { builder.withResponseFormat(runtimeOptions.getResponseFormat()); } if (runtimeOptions.getWidth() != null) { builder.withWidth(runtimeOptions.getWidth()); } if (runtimeOptions.getHeight() != null) { builder.withHeight(runtimeOptions.getHeight()); } if (runtimeOptions instanceof StabilityAiImageOptions) { StabilityAiImageOptions stabilityAiImageOptions = (StabilityAiImageOptions) runtimeOptions; if (stabilityAiImageOptions.getCfgScale() != null) { builder.withCfgScale(stabilityAiImageOptions.getCfgScale()); } if (stabilityAiImageOptions.getClipGuidancePreset() != null) { builder.withClipGuidancePreset(stabilityAiImageOptions.getClipGuidancePreset()); } if (stabilityAiImageOptions.getSampler() != null) { builder.withSampler(stabilityAiImageOptions.getSampler()); } if (stabilityAiImageOptions.getSeed() != null) { builder.withSeed(stabilityAiImageOptions.getSeed()); } if (stabilityAiImageOptions.getSteps() != null) { builder.withSteps(stabilityAiImageOptions.getSteps()); } if (stabilityAiImageOptions.getStylePreset() != null) { builder.withStylePreset(stabilityAiImageOptions.getStylePreset()); } } return builder.build(); } }
[ "org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder" ]
[((1835, 1876), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.anthropic; import java.util.List; import org.springframework.ai.bedrock.anthropic.AnthropicChatOptions; import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.util.Assert; /** * Configuration properties for Bedrock Anthropic. * * @author Christian Tzolov * @since 0.8.0 */ @ConfigurationProperties(BedrockAnthropicChatProperties.CONFIG_PREFIX) public class BedrockAnthropicChatProperties { public static final String CONFIG_PREFIX = "spring.ai.bedrock.anthropic.chat"; /** * Enable Bedrock Anthropic chat client. Disabled by default. */ private boolean enabled = false; /** * The generative id to use. See the {@link AnthropicChatModel} for the supported * models. */ private String model = AnthropicChatModel.CLAUDE_V2.id(); @NestedConfigurationProperty private AnthropicChatOptions options = AnthropicChatOptions.builder() .withTemperature(0.7f) .withMaxTokensToSample(300) .withTopK(10) .withStopSequences(List.of("\n\nHuman:")) .build(); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public AnthropicChatOptions getOptions() { return options; } public void setOptions(AnthropicChatOptions options) { Assert.notNull(options, "AnthropicChatOptions must not be null"); Assert.notNull(options.getTemperature(), "AnthropicChatOptions.temperature must not be null"); this.options = options; } }
[ "org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id", "org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder" ]
[((1613, 1646), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((1719, 1875), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1864), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1820), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1804), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder'), ((1719, 1774), 'org.springframework.ai.bedrock.anthropic.AnthropicChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.openai.chat; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.openai.api.OpenAiApi.ChatCompletionRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov */ @SpringBootTest(classes = OpenAiChatClient2IT.Config.class) @EnabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = ".+") public class OpenAiChatClient2IT { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private OpenAiChatClient openAiChatClient; @Test void responseFormatTest() throws JsonMappingException, JsonProcessingException { // 400 - ResponseError[error=Error[message='json' is not one of ['json_object', // 'text'] - // 'response_format.type', type=invalid_request_error, param=null, code=null]] // 400 - ResponseError[error=Error[message='messages' must contain the word 'json' // in some form, to use // 'response_format' of type 'json_object'., type=invalid_request_error, // param=messages, code=null]] Prompt prompt = new Prompt("List 8 planets. Use JSON response", OpenAiChatOptions.builder() .withResponseFormat(new ChatCompletionRequest.ResponseFormat("json_object")) .build()); ChatResponse response = this.openAiChatClient.call(prompt); assertThat(response).isNotNull(); String content = response.getResult().getOutput().getContent(); logger.info("Response content: {}", content); assertThat(isValidJson(content)).isTrue(); } private static ObjectMapper MAPPER = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); public static boolean isValidJson(String json) { try { MAPPER.readTree(json); } catch (JacksonException e) { return false; } return true; } @SpringBootConfiguration static class Config { @Bean public OpenAiApi chatCompletionApi() { return new OpenAiApi(System.getenv("OPENAI_API_KEY")); } @Bean public OpenAiChatClient openAiClient(OpenAiApi openAiApi) { return new OpenAiChatClient(openAiApi); } } }
[ "org.springframework.ai.openai.OpenAiChatOptions.builder" ]
[((2629, 2752), 'org.springframework.ai.openai.OpenAiChatOptions.builder'), ((2629, 2738), 'org.springframework.ai.openai.OpenAiChatOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.reader.pdf; import org.junit.jupiter.api.Test; import org.springframework.ai.reader.ExtractedTextFormatter; import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Christian Tzolov */ public class ParagraphPdfDocumentReaderTests { @Test public void testPdfWithoutToc() { assertThatThrownBy(() -> { new ParagraphPdfDocumentReader("classpath:/sample1.pdf", PdfDocumentReaderConfig.builder() .withPageTopMargin(0) .withPageBottomMargin(0) .withPageExtractedTextFormatter(ExtractedTextFormatter.builder() .withNumberOfTopTextLinesToDelete(0) .withNumberOfBottomTextLinesToDelete(3) .withNumberOfTopPagesToSkipBeforeDelete(0) .build()) .withPagesPerDocument(1) .build()); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "Document outline (e.g. TOC) is null. Make sure the PDF document has a table of contents (TOC). If not, consider the PagePdfDocumentReader or the TikaDocumentReader instead."); } }
[ "org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder", "org.springframework.ai.reader.ExtractedTextFormatter.builder" ]
[((1123, 1490), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1475), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1444), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1215), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1123, 1184), 'org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig.builder'), ((1254, 1443), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1254, 1427), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1254, 1377), 'org.springframework.ai.reader.ExtractedTextFormatter.builder'), ((1254, 1330), 'org.springframework.ai.reader.ExtractedTextFormatter.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.azure.tool; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ai.autoconfigure.azure.openai.AzureOpenAiAutoConfiguration; import org.springframework.ai.azure.openai.AzureOpenAiChatClient; import org.springframework.ai.azure.openai.AzureOpenAiChatOptions; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.model.function.FunctionCallback; import org.springframework.ai.model.function.FunctionCallbackWrapper; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_API_KEY", matches = ".+") @EnabledIfEnvironmentVariable(named = "AZURE_OPENAI_ENDPOINT", matches = ".+") public class FunctionCallWithFunctionWrapperIT { private final Logger logger = LoggerFactory.getLogger(FunctionCallWithFunctionWrapperIT.class); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withPropertyValues( // @formatter:off "spring.ai.azure.openai.api-key=" + System.getenv("AZURE_OPENAI_API_KEY"), "spring.ai.azure.openai.endpoint=" + System.getenv("AZURE_OPENAI_ENDPOINT")) // @formatter:onn .withConfiguration(AutoConfigurations.of(AzureOpenAiAutoConfiguration.class)) .withUserConfiguration(Config.class); @Test void functionCallTest() { contextRunner.withPropertyValues("spring.ai.azure.openai.chat.options.model=gpt-4-0125-preview") .run(context -> { AzureOpenAiChatClient chatClient = context.getBean(AzureOpenAiChatClient.class); UserMessage userMessage = new UserMessage( "What's the weather like in San Francisco, Paris and in Tokyo?"); ChatResponse response = chatClient.call(new Prompt(List.of(userMessage), AzureOpenAiChatOptions.builder().withFunction("WeatherInfo").build())); logger.info("Response: {}", response); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("30.0", "30"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("10.0", "10"); assertThat(response.getResult().getOutput().getContent()).containsAnyOf("15", "15.0"); }); } @Configuration static class Config { @Bean public FunctionCallback weatherFunctionInfo() { return FunctionCallbackWrapper.builder(new MockWeatherService()) .withName("WeatherInfo") .withDescription("Get the current weather in a given location") .build(); } } }
[ "org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder", "org.springframework.ai.model.function.FunctionCallbackWrapper.builder" ]
[((2864, 2932), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((2864, 2924), 'org.springframework.ai.azure.openai.AzureOpenAiChatOptions.builder'), ((3375, 3542), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3375, 3529), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder'), ((3375, 3461), 'org.springframework.ai.model.function.FunctionCallbackWrapper.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.stabilityai; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.image.*; import org.springframework.ai.stabilityai.StyleEnum; import org.springframework.ai.stabilityai.api.StabilityAiImageOptions; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; @EnabledIfEnvironmentVariable(named = "STABILITYAI_API_KEY", matches = ".*") public class StabilityAiAutoConfigurationIT { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.stabilityai.image.api-key=" + System.getenv("STABILITYAI_API_KEY")) .withConfiguration(AutoConfigurations.of(StabilityAiImageAutoConfiguration.class)); @Test void generate() { contextRunner.run(context -> { ImageClient imageClient = context.getBean(ImageClient.class); StabilityAiImageOptions imageOptions = StabilityAiImageOptions.builder() .withStylePreset(StyleEnum.PHOTOGRAPHIC) .build(); var instructions = """ A light cream colored mini golden doodle. """; ImagePrompt imagePrompt = new ImagePrompt(instructions, imageOptions); ImageResponse imageResponse = imageClient.call(imagePrompt); ImageGeneration imageGeneration = imageResponse.getResult(); Image image = imageGeneration.getOutput(); assertThat(image.getB64Json()).isNotEmpty(); }); } }
[ "org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder" ]
[((1714, 1805), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder'), ((1714, 1792), 'org.springframework.ai.stabilityai.api.StabilityAiImageOptions.builder')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.bedrock.titan; import java.io.IOException; import java.util.Base64; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import software.amazon.awssdk.regions.Region; import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi; import org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel; import org.springframework.ai.embedding.EmbeddingResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.io.DefaultResourceLoader; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") class BedrockTitanEmbeddingClientIT { @Autowired private BedrockTitanEmbeddingClient embeddingClient; @Test void singleEmbedding() { assertThat(embeddingClient).isNotNull(); EmbeddingResponse embeddingResponse = embeddingClient.embedForResponse(List.of("Hello World")); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty(); assertThat(embeddingClient.dimensions()).isEqualTo(1024); } @Test void imageEmbedding() throws IOException { byte[] image = new DefaultResourceLoader().getResource("classpath:/spring_framework.png") .getContentAsByteArray(); EmbeddingResponse embeddingResponse = embeddingClient .embedForResponse(List.of(Base64.getEncoder().encodeToString(image))); assertThat(embeddingResponse.getResults()).hasSize(1); assertThat(embeddingResponse.getResults().get(0).getOutput()).isNotEmpty(); assertThat(embeddingClient.dimensions()).isEqualTo(1024); } @SpringBootConfiguration public static class TestConfiguration { @Bean public TitanEmbeddingBedrockApi titanEmbeddingApi() { return new TitanEmbeddingBedrockApi(TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id(), Region.US_EAST_1.id()); } @Bean public BedrockTitanEmbeddingClient titanEmbedding(TitanEmbeddingBedrockApi titanEmbeddingApi) { return new BedrockTitanEmbeddingClient(titanEmbeddingApi); } } }
[ "org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id" ]
[((2380, 2421), 'java.util.Base64.getEncoder'), ((2795, 2840), 'org.springframework.ai.bedrock.titan.api.TitanEmbeddingBedrockApi.TitanEmbeddingModel.TITAN_EMBED_IMAGE_V1.id'), ((2842, 2863), 'software.amazon.awssdk.regions.Region.US_EAST_1.id')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.testcontainers.service.connection.milvus; import org.junit.jupiter.api.Test; import org.springframework.ai.ResourceUtils; import org.springframework.ai.autoconfigure.vectorstore.milvus.MilvusVectorStoreAutoConfiguration; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.boot.testcontainers.service.connection.ServiceConnection; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.milvus.MilvusContainer; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @SpringJUnitConfig @Testcontainers @TestPropertySource(properties = { "spring.ai.vectorstore.milvus.metricType=COSINE", "spring.ai.vectorstore.milvus.indexType=IVF_FLAT", "spring.ai.vectorstore.milvus.embeddingDimension=384", "spring.ai.vectorstore.milvus.collectionName=myTestCollection" }) class MilvusContainerConnectionDetailsFactoryTest { @Container @ServiceConnection static MilvusContainer milvusContainer = new MilvusContainer("milvusdb/milvus:v2.3.8"); List<Document> documents = List.of( new Document(ResourceUtils.getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document(ResourceUtils.getText("classpath:/test/data/time.shelter.txt")), new Document( ResourceUtils.getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MilvusVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class); @Autowired private VectorStore vectorStore; @Test public void addAndSearch() { vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()) .contains("Spring AI provides abstractions that serve as the foundation for developing AI applications."); assertThat(resultDoc.getMetadata()).hasSize(2); assertThat(resultDoc.getMetadata()).containsKeys("spring", "distance"); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(0); } @Configuration(proxyBeanMethods = false) @ImportAutoConfiguration(MilvusVectorStoreAutoConfiguration.class) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3232, 3273), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((3849, 3890), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.vectorstore.neo4j; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.springframework.ai.ResourceUtils; import org.springframework.ai.document.Document; import org.springframework.ai.embedding.EmbeddingClient; import org.springframework.ai.transformers.TransformersEmbeddingClient; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jingzhou Ou */ @Testcontainers public class Neo4jVectorStoreAutoConfigurationIT { // Needs to be Neo4j 5.15+, because Neo4j 5.15 deprecated the used embedding storing // function. @Container static Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>(DockerImageName.parse("neo4j:5.15")) .withRandomPassword(); List<Document> documents = List.of( new Document(ResourceUtils.getText("classpath:/test/data/spring.ai.txt"), Map.of("spring", "great")), new Document(ResourceUtils.getText("classpath:/test/data/time.shelter.txt")), new Document( ResourceUtils.getText("classpath:/test/data/great.depression.txt"), Map.of("depression", "bad"))); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class, Neo4jVectorStoreAutoConfiguration.class)) .withUserConfiguration(Config.class) .withPropertyValues("spring.neo4j.uri=" + neo4jContainer.getBoltUrl(), "spring.neo4j.authentication.username=" + "neo4j", "spring.neo4j.authentication.password=" + neo4jContainer.getAdminPassword()); @Test void addAndSearch() { contextRunner .withPropertyValues("spring.ai.vectorstore.neo4j.label=my_test_label", "spring.ai.vectorstore.neo4j.embeddingDimension=384", "spring.ai.vectorstore.neo4j.indexName=customIndexName") .run(context -> { var properties = context.getBean(Neo4jVectorStoreProperties.class); assertThat(properties.getLabel()).isEqualTo("my_test_label"); assertThat(properties.getEmbeddingDimension()).isEqualTo(384); assertThat(properties.getIndexName()).isEqualTo("customIndexName"); VectorStore vectorStore = context.getBean(VectorStore.class); vectorStore.add(documents); List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).hasSize(1); Document resultDoc = results.get(0); assertThat(resultDoc.getId()).isEqualTo(documents.get(0).getId()); assertThat(resultDoc.getContent()).contains( "Spring AI provides abstractions that serve as the foundation for developing AI applications."); // Remove all documents from the store vectorStore.delete(documents.stream().map(doc -> doc.getId()).toList()); results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(1)); assertThat(results).isEmpty(); }); } @Configuration(proxyBeanMethods = false) static class Config { @Bean public EmbeddingClient embeddingClient() { return new TransformersEmbeddingClient(); } } }
[ "org.springframework.ai.vectorstore.SearchRequest.query" ]
[((3534, 3575), 'org.springframework.ai.vectorstore.SearchRequest.query'), ((4044, 4085), 'org.springframework.ai.vectorstore.SearchRequest.query')]
/* * Copyright 2023 - 2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ai.autoconfigure.bedrock.anthropic; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.ai.chat.messages.AssistantMessage; import reactor.core.publisher.Flux; import software.amazon.awssdk.regions.Region; import org.springframework.ai.autoconfigure.bedrock.BedrockAwsConnectionProperties; import org.springframework.ai.bedrock.anthropic.BedrockAnthropicChatClient; import org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.Generation; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.SystemPromptTemplate; import org.springframework.ai.chat.messages.Message; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; /** * @author Christian Tzolov * @since 0.8.0 */ @EnabledIfEnvironmentVariable(named = "AWS_ACCESS_KEY_ID", matches = ".*") @EnabledIfEnvironmentVariable(named = "AWS_SECRET_ACCESS_KEY", matches = ".*") public class BedrockAnthropicChatAutoConfigurationIT { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=true", "spring.ai.bedrock.aws.access-key=" + System.getenv("AWS_ACCESS_KEY_ID"), "spring.ai.bedrock.aws.secret-key=" + System.getenv("AWS_SECRET_ACCESS_KEY"), "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), "spring.ai.bedrock.anthropic.chat.model=" + AnthropicChatModel.CLAUDE_V2.id(), "spring.ai.bedrock.anthropic.chat.options.temperature=0.5") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)); private final Message systemMessage = new SystemPromptTemplate(""" You are a helpful AI assistant. Your name is {name}. You are an AI assistant that helps people find information. Your name is {name} You should reply to the user's request with your name and also in the style of a {voice}. """).createMessage(Map.of("name", "Bob", "voice", "pirate")); private final UserMessage userMessage = new UserMessage( "Tell me about 3 famous pirates from the Golden Age of Piracy and why they did."); @Test public void chatCompletion() { contextRunner.run(context -> { BedrockAnthropicChatClient anthropicChatClient = context.getBean(BedrockAnthropicChatClient.class); ChatResponse response = anthropicChatClient.call(new Prompt(List.of(userMessage, systemMessage))); assertThat(response.getResult().getOutput().getContent()).contains("Blackbeard"); }); } @Test public void chatCompletionStreaming() { contextRunner.run(context -> { BedrockAnthropicChatClient anthropicChatClient = context.getBean(BedrockAnthropicChatClient.class); Flux<ChatResponse> response = anthropicChatClient.stream(new Prompt(List.of(userMessage, systemMessage))); List<ChatResponse> responses = response.collectList().block(); assertThat(responses.size()).isGreaterThan(2); String stitchedResponseContent = responses.stream() .map(ChatResponse::getResults) .flatMap(List::stream) .map(Generation::getOutput) .map(AssistantMessage::getContent) .collect(Collectors.joining()); assertThat(stitchedResponseContent).contains("Blackbeard"); }); } @Test public void propertiesTest() { new ApplicationContextRunner() .withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=true", "spring.ai.bedrock.aws.access-key=ACCESS_KEY", "spring.ai.bedrock.aws.secret-key=SECRET_KEY", "spring.ai.bedrock.anthropic.chat.model=MODEL_XYZ", "spring.ai.bedrock.aws.region=" + Region.EU_CENTRAL_1.id(), "spring.ai.bedrock.anthropic.chat.options.temperature=0.55") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { var anthropicChatProperties = context.getBean(BedrockAnthropicChatProperties.class); var awsProperties = context.getBean(BedrockAwsConnectionProperties.class); assertThat(anthropicChatProperties.isEnabled()).isTrue(); assertThat(awsProperties.getRegion()).isEqualTo(Region.EU_CENTRAL_1.id()); assertThat(anthropicChatProperties.getOptions().getTemperature()).isEqualTo(0.55f); assertThat(anthropicChatProperties.getModel()).isEqualTo("MODEL_XYZ"); assertThat(awsProperties.getAccessKey()).isEqualTo("ACCESS_KEY"); assertThat(awsProperties.getSecretKey()).isEqualTo("SECRET_KEY"); }); } @Test public void chatCompletionDisabled() { // It is disabled by default new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockAnthropicChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockAnthropicChatClient.class)).isEmpty(); }); // Explicitly enable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=true") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockAnthropicChatProperties.class)).isNotEmpty(); assertThat(context.getBeansOfType(BedrockAnthropicChatClient.class)).isNotEmpty(); }); // Explicitly disable the chat auto-configuration. new ApplicationContextRunner().withPropertyValues("spring.ai.bedrock.anthropic.chat.enabled=false") .withConfiguration(AutoConfigurations.of(BedrockAnthropicChatAutoConfiguration.class)) .run(context -> { assertThat(context.getBeansOfType(BedrockAnthropicChatProperties.class)).isEmpty(); assertThat(context.getBeansOfType(BedrockAnthropicChatClient.class)).isEmpty(); }); } }
[ "org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id" ]
[((2413, 2437), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((2487, 2520), 'org.springframework.ai.bedrock.anthropic.api.AnthropicChatBedrockApi.AnthropicChatModel.CLAUDE_V2.id'), ((4615, 4639), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id'), ((5101, 5125), 'software.amazon.awssdk.regions.Region.EU_CENTRAL_1.id')]