### Example format instructions for JSON output Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/structured-output/converters.adoc Example formatting instructions that a FormatProvider might return. These instructions are appended to the user input to guide the model to produce JSON output matching a specified Java class. ```text Your response should be in JSON format. The data structure for the JSON should match this Java class: java.util.HashMap Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation. ``` -------------------------------- ### ci-alert-config.json example Source: https://github.com/spring-projects/spring-ai/blob/main/src/ecosystem-ci/README.md Example configuration for the dashboard. Each dependency requires an 'owner' and 'repo'. The 'tracked_branch' setting (default: main) determines the branch monitored. ```json { "dependencies": [ { "owner": "org-name", "repo": "repo-name" }, ... ] } ``` -------------------------------- ### Sample Output Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-annotations-examples.adoc Example console output when running the MCP client. ```text > USER: What is the weather in Amsterdam right now? Please incorporate all creative responses from all LLM providers. After the other providers add a poem that synthesizes the poems from all the other providers. > ASSISTANT: OpenAI poem about the weather: **Amsterdam's Winter Whisper** *Temperature: 4.2°C* In Amsterdam's embrace, where canals reflect the sky, A gentle chill of 4.2 degrees drifts by... Anthropic poem about the weather: **Canal-Side Contemplation** *Current conditions: 4.2°C* Along the waterways where bicycles rest, The winter air puts Amsterdam to test... Weather Data: { "current": { "time": "2025-01-23T11:00", "interval": 900, "temperature_2m": 4.2 } } ``` -------------------------------- ### Start Milvus with Docker Compose Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/milvus.adoc Run from the `src/test/resources/` folder to start the Milvus environment. Connects to the vector store at http://localhost:19530 and management UI at http://localhost:9001 (user: minioadmin, pass: minioadmin). ```bash docker-compose up ``` -------------------------------- ### Simple MCP Server Tool Example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-server-boot-starter-docs.adoc A simple example of an MCP server component using the @McpTool annotation to expose a calculator tool. ```java @Component public class CalculatorTools { ``` -------------------------------- ### Basic OAuth 2.0 Setup - application.properties Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-security.adoc Enable the MCP server in your application.properties file. ```properties spring.ai.mcp.server.name=my-cool-mcp-server ``` -------------------------------- ### Complete example of extended usage Source: https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-google-genai/README.md A complete example demonstrating how to access extended usage metadata, including basic token counts, thinking tokens, cached tokens, tool-use tokens, modality breakdowns, traffic type, and native SDK object. ```java @Component public class ExtendedUsageExample { private final GoogleGenAiChatModel chatModel; public void demonstrateExtendedUsage() { Prompt prompt = new Prompt("Analyze this complex multi-modal request"); ChatResponse response = chatModel.call(prompt); // Cast to GoogleGenAiUsage for extended metadata GoogleGenAiUsage usage = (GoogleGenAiUsage) response.getMetadata().getUsage(); // Basic token counts (standard Usage interface) System.out.println("Prompt tokens: " + usage.getPromptTokens()); System.out.println("Completion tokens: " + usage.getCompletionTokens()); System.out.println("Total tokens: " + usage.getTotalTokens()); // Extended metadata (Google GenAI specific) System.out.println("Thinking tokens: " + usage.getThoughtsTokenCount()); System.out.println("Cached tokens: " + usage.getCachedContentTokenCount()); System.out.println("Tool-use tokens: " + usage.getToolUsePromptTokenCount()); // Modality breakdowns if (usage.getPromptTokensDetails() != null) { usage.getPromptTokensDetails().forEach(detail -> System.out.println(" " + detail.getModality() + ": " + detail.getTokenCount()) ); } // Traffic type System.out.println("Traffic type: " + usage.getTrafficType()); // Access native SDK object for any additional metadata GenerateContentResponseUsageMetadata nativeUsage = (GenerateContentResponseUsageMetadata) usage.getNativeUsage(); } } ``` -------------------------------- ### Cache isolation with namespaces Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/redis.adoc Java example creating isolated SemanticCache instances for different users or contexts using distinct index names. Each user gets their own cache space, and an advisor is built for one of them. ```java // Create isolated caches for different users or contexts SemanticCache user1Cache = DefaultSemanticCache.builder() .jedisClient(jedisClient) .embeddingModel(embeddingModel) .indexName("user-1-cache") .build(); SemanticCache user2Cache = DefaultSemanticCache.builder() .jedisClient(jedisClient) .embeddingModel(embeddingModel) .indexName("user-2-cache") .build(); // Each user gets their own isolated cache space SemanticCacheAdvisor user1Advisor = SemanticCacheAdvisor.builder() .cache(user1Cache) .build(); ``` -------------------------------- ### Configure QdrantVectorStore via application.yml Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/qdrant.adoc Provide connection details for the Qdrant instance using Spring Boot's application.yml. Properties start with spring.ai.vectorstore.qdrant.*. Set initialize-schema to true to opt-in to schema initialization (breaking change from earlier versions). ```yaml spring: ai: vectorstore: qdrant: host: port: api-key: collection-name: content-field-name: use-tls: false initialize-schema: true ``` -------------------------------- ### Run Postgres & PGVector DB Locally Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/pgvector.adoc Docker command to start a local PostgreSQL instance with the pgvector extension. Uses user 'postgres' and password 'postgres' on port 5432. ```bash docker run -it --rm --name postgres -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres pgvector/pgvector ``` -------------------------------- ### Create and use VertexAiMultimodalEmbeddingModel Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/embeddings/vertexai-embeddings-multimodal.adoc Java example showing how to create a VertexAiMultimodalEmbeddingModel with connection details and options, then use it to generate embeddings for documents and text. The example includes creating media objects and documents, and calling the model for responses. ```java VertexAiEmbeddingConnectionDetails connectionDetails = VertexAiEmbeddingConnectionDetails.builder() .projectId(System.getenv()) .location(System.getenv()) .build(); VertexAiMultimodalEmbeddingOptions options = VertexAiMultimodalEmbeddingOptions.builder() .model(VertexAiMultimodalEmbeddingOptions.DEFAULT_MODEL_NAME) .build(); var embeddingModel = new VertexAiMultimodalEmbeddingModel(this.connectionDetails, this.options); Media imageMedial = new Media(MimeTypeUtils.IMAGE_PNG, new ClassPathResource("/test.image.png")); Media videoMedial = new Media(new MimeType("video", "mp4"), new ClassPathResource("/test.video.mp4")); var document = new Document("Explain what do you see on this video?", List.of(this.imageMedial, this.videoMedial), Map.of()); EmbeddingResponse embeddingResponse = this.embeddingModel .embedForResponse(List.of("Hello World", "World is big and salvation is near")); DocumentEmbeddingRequest embeddingRequest = new DocumentEmbeddingRequest(List.of(this.document), EmbeddingOptions.EMPTY); EmbeddingResponse embeddingResponse = multiModelEmbeddingModel.call(this.embeddingRequest); assertThat(embeddingResponse.getResults()).hasSize(3); ``` -------------------------------- ### Starter dependency for Google GenAI Source: https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-google-genai/README.md Add the Spring AI Google GenAI starter dependency to your Maven project to get started with the chat model. ```xml org.springframework.ai spring-ai-starter-model-google-genai ``` -------------------------------- ### Solution: Use toolSpecifications() method (M8) for Azure OpenAI ChatClient Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/upgrade-notes.adoc This example shows the correct approach for M8, using the `toolSpecifications()` method instead of the deprecated `tools()` method. It configures the same tool and callback as the previous example but works reliably. ```java // This works in M8 ChatClient chatClient = new OpenAiChatClient(api) .toolSpecifications(List.of( new Tool("get_current_weather", "Get the current weather in a given location", new ToolSpecification.ToolParameter("location", "The city and state, e.g. San Francisco, CA", true)) )) .toolCallbacks(List.of( new ToolCallback("get_current_weather", (toolName, params) -> { // Weather retrieval logic return Map.of("temperature", 72, "unit", "fahrenheit", "description", "Sunny"); }) )); ``` -------------------------------- ### Creating a Spring Boot Application with MCP Server Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-streamable-http-server-boot-starter-docs.adoc Example of defining a tool service and registering it as an MCP tool callback provider. ```APIDOC ## Creating a Spring Boot Application with MCP Server ### Description Example of defining a tool service and registering it as an MCP tool callback provider. ### Components - **WeatherService** - A Spring service that exposes a tool method annotated with `@Tool`. - **McpServerApplication** - The main Spring Boot application class. - **weatherTools** - A `@Bean` method that creates a `ToolCallbackProvider` from the `WeatherService`. ### Tool Method - **getWeather(String cityName)** - Returns weather information for the given city. ### Example Code ```java @Service public class WeatherService { @Tool(description = "Get weather information by city name") public String getWeather(String cityName) { // Implementation } } @SpringBootApplication public class McpServerApplication { private static final Logger logger = LoggerFactory.getLogger(McpServerApplication.class); public static void main(String[] args) { SpringApplication.run(McpServerApplication.class, args); } @Bean public ToolCallbackProvider weatherTools(WeatherService weatherService) { return MethodToolCallbackProvider.builder().toolObjects(weatherService).build(); } } ``` ### Notes - The auto-configuration will automatically register the tool callbacks as MCP tools. - You can have multiple beans producing ToolCallbacks, and the auto-configuration will merge them. ``` -------------------------------- ### Client Application Setup Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-annotations-examples.adoc Registers MCP tools and handlers in the client application using @SpringBootApplication and CommandLineRunner. ```java @SpringBootApplication public class McpClientApplication { public static void main(String[] args) { SpringApplication.run(McpClientApplication.class, args).close(); } @Bean public CommandLineRunner predefinedQuestions(OpenAiChatModel openAiChatModel, ToolCallbackProvider mcpToolProvider) { return args -> { ChatClient chatClient = ChatClient.builder(openAiChatModel) .defaultTools(mcpToolProvider) .build(); String userQuestion = """ What is the weather in Amsterdam right now? Please incorporate all creative responses from all LLM providers. After the other providers add a poem that synthesizes the poems from all the other providers. """; ``` -------------------------------- ### Instantiating a container with ClassPathXmlApplicationContext (Java) Source: https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/resources/text_source.txt Java example of creating an ApplicationContext by passing resource strings to the ClassPathXmlApplicationContext constructor. ```java ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); ``` -------------------------------- ### Add Redis Vector Store Starter Dependency (Gradle build.gradle) Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/redis.adoc Add the Spring AI Redis vector store starter to your Gradle build to enable auto-configuration. Requires the Spring AI BOM and artifact repositories as noted in the getting-started guide. ```groovy dependencies { implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis' } ``` -------------------------------- ### One-shot and few-shot prompting with ChatClient Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/chat/prompt-engineering-patterns.adoc Demonstrates a few-shot prompting example that parses a pizza order into JSON using two examples. Uses ChatClient with model 'claude-sonnet-4-6', temperature 0.1, maxTokens 250. ```java // Implementation of Section 2.2: One-shot & few-shot (page 16) public void pt_one_shot_few_shots(ChatClient chatClient) { String pizzaOrder = chatClient.prompt(""" Parse a customer's pizza order into valid JSON EXAMPLE 1: I want a small pizza with cheese, tomato sauce, and pepperoni. JSON Response: ``` { "size": "small", "type": "normal", "ingredients": ["cheese", "tomato sauce", "pepperoni"] } ``` EXAMPLE 2: Can I get a large pizza with tomato sauce, basil and mozzarella. JSON Response: ``` { "size": "large", "type": "normal", "ingredients": ["tomato sauce", "basil", "mozzarella"] } ``` Now, I would like a large pizza, with the first half cheese and mozzarella. And the other tomato sauce, ham and pineapple. """) .options(ChatOptions.builder() .model("claude-sonnet-4-6") .temperature(0.1) .maxTokens(250) .build()) .call() .content(); } ``` -------------------------------- ### Example output of SelfRefineEvaluationAdvisor run Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/guides/llm-as-judge.adoc This text output shows the expected console output when running the complete example. It demonstrates the evaluation failing on the first attempt due to unrealistic temperature, then passing on the second attempt, and finally returning the response. ```text REQUEST: [{"role":"user","content":"What is current weather in Paris?"}] >>> Tool Call responseTemp: -255 Evaluation failed on attempt 1, evaluation: The response contains unrealistic temperature data, feedback: The temperature of -255°C is physically impossible and indicates a data error. >>> Tool Call responseTemp: 15 Evaluation passed on attempt 2, evaluation: Excellent response with realistic weather data RESPONSE: The current weather in Paris is sunny with a temperature of 15°C. ``` -------------------------------- ### Complete example with cost tracking Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/chat/bedrock-converse.adoc Complete example demonstrating prompt caching with cost tracking. Creates a large system prompt (1024+ tokens for cache effectiveness), makes two requests with the same system prompt, and accesses cache-related token usage from metadata. The second request should show cacheWriteInputTokens as 0 and cacheReadInputTokens greater than 0. ```java // Create system content that will be reused multiple times String largeSystemPrompt = "You are an expert software architect specializing in distributed systems..."; // (Ensure this is 1024+ tokens for cache effectiveness) // First request - creates cache ChatResponse firstResponse = chatModel.call( new Prompt( List.of( new SystemMessage(largeSystemPrompt), new UserMessage("What is microservices architecture?") ), BedrockChatOptions.builder() .model("us.anthropic.claude-haiku-4-5-20251001-v1:0") .cacheOptions(BedrockCacheOptions.builder() .strategy(BedrockCacheStrategy.SYSTEM_ONLY) .build()) .maxTokens(500) .build() ) ); // Access cache-related token usage from metadata Integer cacheWrite1 = (Integer) firstResponse.getMetadata() .getMetadata() .get("cacheWriteInputTokens"); Integer cacheRead1 = (Integer) firstResponse.getMetadata() .getMetadata() .get("cacheReadInputTokens"); System.out.println("Cache creation tokens: " + cacheWrite1); System.out.println("Cache read tokens: " + cacheRead1); // Second request with same system prompt - reads from cache ChatResponse secondResponse = chatModel.call( new Prompt( List.of( new SystemMessage(largeSystemPrompt), // Same prompt - cache hit new UserMessage("What are the benefits of event sourcing?") ), BedrockChatOptions.builder() .model("us.anthropic.claude-haiku-4-5-20251001-v1:0") .cacheOptions(BedrockCacheOptions.builder() .strategy(BedrockCacheStrategy.SYSTEM_ONLY) .build()) .maxTokens(500) .build() ) ); Integer cacheWrite2 = (Integer) secondResponse.getMetadata() .getMetadata() .get("cacheWriteInputTokens"); Integer cacheRead2 = (Integer) secondResponse.getMetadata() .getMetadata() .get("cacheReadInputTokens"); System.out.println("Cache creation tokens: " + cacheWrite2); // Should be 0 System.out.println("Cache read tokens: " + cacheRead2); // Should be > 0 ``` -------------------------------- ### Auto-wire and use Chroma VectorStore Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/chroma.adoc Java example showing how to autowire the VectorStore, create documents with metadata, add them to the store, and perform a similarity search with a query and topK parameter. ```java @Autowired VectorStore vectorStore; // ... List documents = List.of( new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")), new Document("The World is Big and Salvation Lurks Around the Corner"), new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2"))); // Add the documents vectorStore.add(documents); // Retrieve documents similar to a query List results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build()); ``` -------------------------------- ### Portable filter expression example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/mongodb.adoc Example of a portable filter expression that gets converted to MongoDB Atlas filter format. ```sql author in ['john', 'jill'] && article_type == 'blog' ``` -------------------------------- ### Portable filter expression Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/azure.adoc Example of a portable filter expression that gets converted to OData. ```sql country in ['UK', 'NL'] && year >= 2020 ``` -------------------------------- ### Manual configuration: create ElevenLabsApi and model Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/audio/speech/elevenlabs-speech.adoc Configure how to create an ElevenLabsTextToSpeechModel with default options. ```java ElevenLabsApi elevenLabsApi = ElevenLabsApi.builder() .apiKey(System.getenv("ELEVEN_LABS_API_KEY")) .build(); ElevenLabsTextToSpeechModel elevenLabsTextToSpeechModel = ElevenLabsTextToSpeechModel.builder() .elevenLabsApi(elevenLabsApi) .options(ElevenLabsTextToSpeechOptions.builder() .model("eleven_turbo_v2_5") .voiceId("your_voice_id") // e.g. "9BWtsMINqrJLrRacOk9x" .outputFormat("mp3_44100_128") .build()) .build(); // The call will use the default options configured above. TextToSpeechPrompt speechPrompt = new TextToSpeechPrompt("Hello, this is a text-to-speech example."); TextToSpeechResponse response = elevenLTextToSpeechModel.call(speechPrompt); byte[] responseAsBytes = response.getResult().getOutput(); ``` -------------------------------- ### Evaluator-Optimizer usage example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/effective-agents.adoc Shows how to instantiate the EvaluatorOptimizerWorkflow with a ChatClient and run the loop, printing the final solution and evolution. ```java ChatClient chatClient = // ... initialize chat client EvaluatorOptimizerWorkflow workflow = new EvaluatorOptimizerWorkflow(chatClient); RefinedResponse response = workflow.loop( "Create a Java class implementing a thread-safe counter" ); System.out.println("Final Solution: " + response.solution()); System.out.println("Evolution: " + response.chainOfThought()); ``` -------------------------------- ### PromptTemplate usage example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/prompt.adoc Simple example from the AI Workshop on PromptTemplates: creates a PromptTemplate with placeholders, calls create with a map of values, and passes the resulting Prompt to chatModel.call to get a result. ```java PromptTemplate promptTemplate = new PromptTemplate("Tell me a {adjective} joke about {topic}"); Prompt prompt = promptTemplate.create(Map.of("adjective", adjective, "topic", topic)); return chatModel.call(prompt).getResult(); ``` -------------------------------- ### SystemPromptTemplate and UserMessage usage example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/prompt.adoc Example from the AI Workshop on Roles: builds a Prompt by combining a UserMessage with a system message created via SystemPromptTemplate, passing placeholder values for name and voice, then calls chatModel to get results. ```java String userText = """ Tell me about three famous pirates from the Golden Age of Piracy and why they did. Write at least a sentence for each pirate. """; Message userMessage = new UserMessage(userText); String systemText = """ You are a helpful 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}. """; SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText); Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice)); Prompt prompt = new Prompt(List.of(userMessage, systemMessage)); List response = chatModel.call(prompt).getResults(); ``` -------------------------------- ### Unified Context Example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-annotations-server.adoc Shows how to access root directories in stateful mode using the unified context. The code checks if roots are enabled and iterates over them, logging each root URI. ```java // Access root directories (only in stateful mode) if (context.rootsEnabled()) { ListRootsResult roots = context.roots(); roots.roots().forEach(root -> context.info("Root: " + root.uri())); } return "Processed with unified context"; } ``` -------------------------------- ### Kotlin: ExampleBean with int and String constructor args Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/test/resources/text_source.txt Kotlin data class with two constructor parameters, including comments for each. ```kotlin package examples class ExampleBean( private val years: Int, // Number of years to calculate the Ultimate Answer private val ultimateAnswer: String // The Answer to Life, the Universe, and Everything ) ``` -------------------------------- ### Using ApplicationContext to retrieve beans (Java) Source: https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/resources/text_source.txt Java example showing how to create and configure beans with ClassPathXmlApplicationContext, retrieve a configured instance using getBean, and use it. ```java // create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); // retrieve configured instance PetStoreService service = context.getBean("petStore", PetStoreService.class); // use configured instance List userList = service.getUsernameList(); ``` -------------------------------- ### Subclass example: MyAuditingToolCallingAdvisor Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/tools/tool-calling-advisor.adoc Concrete example of a ToolCallingAdvisor subclass. The source shows the class declaration and opening brace; the full implementation is not displayed. Overrides doInitializeLoop and doInitializeLoopStream to index the tool set at session start and augment the system message, and doBeforeCall and doBeforeStream to inject only the tools discovered so far on each iteration. ```java public class MyAuditingToolCallingAdvisor extends ToolCallingAdvisor { ``` -------------------------------- ### Use CouchbaseSearchVectorStore in Java Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/couchbase.adoc Example of auto-wiring the VectorStore, adding documents, and performing a similarity search. ```java @Autowired VectorStore vectorStore; // ... List documents = List.of( new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")), new Document("The World is Big and Salvation Lurks Around the Corner"), new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2"))); // Add the documents to Couchbase vectorStore.add(documents); // Retrieve documents similar to a query List results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build()); ``` -------------------------------- ### Bootstrap with Groovy configuration using GenericGroovyApplicationContext (Kotlin) Source: https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/resources/text_source.txt Create an application context from Groovy configuration files with Kotlin. ```kotlin val context = GenericGroovyApplicationContext("services.groovy", "daos.groovy") ``` -------------------------------- ### Metadata Filtering with Filter.Expression DSL Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/opensearch.adoc Performs a similarity search using the programmatic Filter.Expression DSL to build the same filter as the text expression example. ```java FilterExpressionBuilder b = new FilterExpressionBuilder(); vectorStore.similaritySearch(SearchRequest.builder() .query("The World") .topK(TOP_K) .similarityThreshold(SIMILARITY_THRESHOLD) .filterExpression(b.and( b.in("author", "john", "jill"), b.eq("article_type", "blog")).build()).build()); ``` -------------------------------- ### Manual TransformersEmbeddingModel setup Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/embeddings/onnx.adoc Create a TransformersEmbeddingModel instance and set the tokenizer and model resources. The tokenizer URI defaults to classpath:/onnx/all-MiniLM-L6-v2/tokenizer.json if not set. ```java TransformersEmbeddingModel embeddingModel = new TransformersEmbeddingModel(); // (optional) defaults to classpath:/onnx/all-MiniLM-L6-v2/tokenizer.json embeddingModel.setTokenizerResource("classpath:/onnx/all-MiniLM-L6-v2/tokenizer.json"); ``` -------------------------------- ### Java: ExampleBean with int and String constructor args Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-client-chat/src/test/resources/text_source.txt Example class with two constructor arguments (int years and String ultimateAnswer) used to illustrate simple type matching. ```java package examples; public class ExampleBean { // Number of years to calculate the Ultimate Answer private final int years; // The Answer to Life, the Universe, and Everything private final String ultimateAnswer; public ExampleBean(int years, String ultimateAnswer) { this.years = years; this.ultimateAnswer = ultimateAnswer; } } ``` -------------------------------- ### JsonReader get() with JSON Pointer example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/etl-pipeline.adoc Creates a JsonReader with 'description' as the jsonKeysToUse and retrieves documents from the JSON element at '/store/books/0'. The pointer must be valid; otherwise an IllegalArgumentException is thrown. ```java JsonReader jsonReader = new JsonReader(resource, "description"); List documents = this.jsonReader.get("/store/books/0"); ``` -------------------------------- ### Orchestrator-Workers usage example Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/effective-agents.adoc Shows how to instantiate the OrchestratorWorkersWorkflow with a ChatClient and process a task, printing the analysis and worker outputs. ```java ChatClient chatClient = // ... initialize chat client OrchestratorWorkersWorkflow workflow = new OrchestratorWorkersWorkflow(chatClient); WorkerResponse response = workflow.process( "Generate both technical and user-friendly documentation for a REST API endpoint" ); System.out.println("Analysis: " + response.analysis()); System.out.println("Worker Outputs: " + response.workerResponses()); ``` -------------------------------- ### Progress Token Null Checks Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-annotations-special-params.adoc Use @McpProgressToken to safely handle progress notifications, always checking for null before sending. The example sends a starting and a complete progress notification with the provided token, only when it is not null, and returns a completion message. ```java @McpTool(name = "safe-progress", description = "Safe progress handling") public String safeProgress( @McpProgressToken String progressToken, @McpToolParam(description = "Task", required = true) String task, McpSyncServerExchange exchange) { // Always check if progress token is available if (progressToken != null) { exchange.progressNotification(ProgressNotification.builder(progressToken, 0.0) .total(1.0).message("Starting").build()); } // Perform work... if (progressToken != null) { exchange.progressNotification(ProgressNotification.builder(progressToken, 1.0) .total(1.0).message("Complete").build()); } return "Task completed"; } ``` -------------------------------- ### Add Starter Dependency Source: https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-google-genai-embedding/README.md Include this dependency in your project to use the Google GenAI embedding starter. ```xml org.springframework.ai spring-ai-starter-model-google-genai-embedding ``` -------------------------------- ### Qdrant Vector Store Filter Expression with String Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/qdrant.adoc Uses the VectorStore's similaritySearch method with a filter expression as a string. The filter expression is portable and gets converted into Qdrant's proprietary filter syntax. ```java vectorStore.similaritySearch( SearchRequest.builder() .query("The World") .topK(TOP_K) .similarityThreshold(SIMILARITY_THRESHOLD) .filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build()); ``` -------------------------------- ### Kotlin: SimpleMovieLister constructor injection Source: https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/test/resources/text_source.txt Kotlin version of the constructor injection example, using a primary constructor with a private val parameter. ```kotlin // a constructor so that the Spring container can inject a MovieFinder class SimpleMovieLister(private val movieFinder: MovieFinder) { // business logic that actually uses the injected MovieFinder is omitted... } ``` -------------------------------- ### Create QdrantVectorStore bean with builder Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/qdrant.adoc Creates a VectorStore bean using QdrantVectorStore.builder, with optional collection name, content field name, schema initialization, and batching strategy. Also includes an EmbeddingModel bean example. ```java @Bean public VectorStore vectorStore(QdrantClient qdrantClient, EmbeddingModel embeddingModel) { return QdrantVectorStore.builder(qdrantClient, embeddingModel) .collectionName("custom-collection") // Optional: defaults to "vector_store" .contentFieldName("page_content") // Optional: defaults to "doc_content" .initializeSchema(true) // Optional: defaults to false .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy .build(); } // This can be any EmbeddingModel implementation @Bean public EmbeddingModel embeddingModel() { return new OpenAiEmbeddingModel(OpenAiEmbeddingOptions.builder().apiKey(System.getenv("OPENAI_API_KEY")).build()); } ``` -------------------------------- ### Complete example: working with existing index Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/azure.adoc Complete configuration class for using an existing Azure AI Search index with custom field names. Includes SearchIndexClient bean and VectorStore bean with initializeSchema(false). ```java @Configuration public class VectorStoreConfig { @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, EmbeddingModel embeddingModel) { return AzureVectorStore.builder(searchIndexClient, embeddingModel) .indexName("production-documents-index") .initializeSchema(false) // Use existing index // Map to existing index field names .contentFieldName("document_text") .embeddingFieldName("text_vector") .metadataFieldName("document_metadata") // Define filterable metadata fields from existing schema .filterMetadataFields(List.of( MetadataField.text("department"), MetadataField.int64("year"), MetadataField.date("created_date"))) .defaultTopK(10) .defaultSimilarityThreshold(0.75) .build(); } } ``` -------------------------------- ### Direct SemanticCache usage Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/redis.adoc Java example for direct interaction with SemanticCache. Shows storing responses with optional TTL, retrieving semantically similar responses, extracting the answer text, and clearing all cached entries. ```java @Autowired private SemanticCache semanticCache; // Store a response with a query semanticCache.set("What is the capital of France?", chatResponse); // Store with TTL (time-to-live) for automatic expiration semanticCache.set("What's the weather today?", weatherResponse, Duration.ofHours(1)); // Retrieve a semantically similar response Optional cached = semanticCache.get("Tell me France's capital"); if (cached.isPresent()) { // Use the cached response String answer = cached.get().getResult().getOutput().getText(); } // Clear all cached entries semanticCache.clear(); ``` -------------------------------- ### Inject MCP client beans (sync and async) Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-client-boot-starter-docs.adoc Shows how to autowire lists of McpSyncClient and McpAsyncClient beans that are automatically configured by the starter. Use the appropriate list depending on whether you need synchronous or asynchronous clients. ```java @Autowired private List mcpSyncClients; // For sync client // OR @Autowired private List mcpAsyncClients; // For async client ``` -------------------------------- ### Define Custom Metadata Fields Bean for Redis Schema Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/redis.adoc Define a List bean to include custom metadata fields in the auto-configured Redis schema. The example creates a tag field named 'conversationId'. ```java @Bean List redisMetadataFields() { return List.of(RedisVectorStore.MetadataField.tag("conversationId")); } ``` -------------------------------- ### Sampling Client Implementation Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-annotations-examples.adoc Demonstrates how to handle sampling requests by routing them to appropriate LLM providers based on model hints using the @McpSampling annotation. ```java @Service public class McpClientHandlers { private static final Logger logger = LoggerFactory.getLogger(McpClientHandlers.class); @Autowired Map chatClients; @McpProgress(clients = "server1") public void progressHandler(ProgressNotification progressNotification) { logger.info("MCP PROGRESS: [{}] progress: {} total: {} message: {}", progressNotification.progressToken(), progressNotification.progress(), progressNotification.total(), progressNotification.message()); } @McpLogging(clients = "server1") public void loggingHandler(LoggingMessageNotification loggingMessage) { logger.info("MCP LOGGING: [{}] {}", loggingMessage.level(), loggingMessage.data()); } @McpSampling(clients = "server1") public CreateMessageResult samplingHandler(CreateMessageRequest llmRequest) { logger.info("MCP SAMPLING: {}", llmRequest); // Extract user prompt and model hint var userPrompt = ((McpSchema.TextContent) llmRequest.messages().get(0).content()).text(); String modelHint = llmRequest.modelPreferences().hints().get(0).name(); // Find appropriate ChatClient based on model hint ChatClient hintedChatClient = chatClients.entrySet().stream() .filter(e -> e.getKey().contains(modelHint)) .findFirst() .orElseThrow() .getValue(); // Generate response using the selected model String response = hintedChatClient.prompt() .system(llmRequest.systemPrompt()) .user(userPrompt) .call() .content(); return CreateMessageResult.builder(Role.ASSISTANT, response, modelHint) .build(); } } ``` -------------------------------- ### Stateless Tools with Filtering Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/mcp/mcp-annotations-server.adoc Example of stateless tools. Methods with McpTransportContext or no context are registered, while methods with McpSyncRequestContext are filtered out and a warning is logged. ```java @Component public class StatelessTools { @McpTool(name = "simple-tool", description = "Simple stateless tool") public String simpleTool(@McpToolParam(description = "Input") String input) { // This method WILL be registered on stateless servers return "Processed: " + input; } @McpTool(name = "context-tool", description = "Tool with transport context") public String contextTool( McpTransportContext context, @McpToolParam(description = "Input") String input) { // This method WILL be registered on stateless servers return "Processed: " + input; } @McpTool(name = "bidirectional-tool", description = "Tool with bidirectional context") public String bidirectionalTool( McpSyncRequestContext context, @McpToolParam(description = "Input") String input) { // This method will be FILTERED OUT on stateless servers // A warning will be logged return "Processed with sampling"; } } ``` -------------------------------- ### OpenSearchVectorStore configuration properties in application.yml Source: https://github.com/spring-projects/spring-ai/blob/main/spring-ai-docs/src/main/antora/modules/ROOT/pages/api/vectordbs/opensearch.adoc Configure connection details for OpenSearchVectorStore via Spring Boot's application.yml. Properties starting with spring.ai.vectorstore.opensearch.* configure the vector store; the aws block is only for Amazon OpenSearch Service. ```yaml spring: ai: vectorstore: opensearch: uris: username: password: index-name: spring-ai-document-index initialize-schema: true similarity-function: cosinesimil read-timeout: