<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dipak Maity on Medium]]></title>
        <description><![CDATA[Stories by Dipak Maity on Medium]]></description>
        <link>https://medium.com/@dipak.maity?source=rss-c5ca8a7f81e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gI-8lpz7yIMK8q_LG0dc9g.jpeg</url>
            <title>Stories by Dipak Maity on Medium</title>
            <link>https://medium.com/@dipak.maity?source=rss-c5ca8a7f81e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:22:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dipak.maity/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring AI Meets GPT-4o: Creating a Simple Multi-Agent AI System]]></title>
            <link>https://medium.com/walmartglobaltech/spring-ai-meets-gpt-4o-creating-a-simple-multi-agent-ai-system-fc572a469612?source=rss-c5ca8a7f81e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc572a469612</guid>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[Dipak Maity]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 06:34:57 GMT</pubDate>
            <atom:updated>2025-09-08T06:34:57.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVcGOIV9id7XwXte42jbDQ.png" /><figcaption>AI generated image</figcaption></figure><p>Spring AI is a powerful extension of the widely used Spring Framework, designed to simplify the development of AI-based applications. It provides seamless integration with various AI models and tools, leveraging the flexibility and scalability of the Spring ecosystem to build AI-driven solutions. Spring AI abstracts much of the complexity of deploying AI models, allowing developers to focus on building and scaling applications rather than worrying about infrastructure details.</p><p>Spring AI supports a variety of machine learning and AI workflows, from natural language processing (NLP) to image recognition, making it a versatile choice for a wide range of projects. With Spring’s robust support for dependency injection, configuration management, and scalability, Spring AI makes it easy to build production-ready AI applications.</p><p><strong>Benefits of Using Spring AI</strong></p><ul><li><strong><em>Seamless Integration with Spring Ecosystem:</em> </strong>Spring AI integrates seamlessly with the larger Spring Framework, allowing you to take advantage of Spring Boot, Spring Cloud, and other Spring projects for easy deployment, scalability, and maintenance.</li><li><strong><em>Modular and Flexible Architecture:</em></strong> Spring AI allows developers to choose the right AI models and frameworks without being locked into a specific technology. It provides flexibility in integrating popular AI and machine learning models with your application.</li><li><strong><em>Enhanced Developer Productivity:</em></strong> Spring AI abstracts many of the complexities of working with AI models, enabling developers to quickly prototype and implement AI functionality without needing to deep dive into every technical detail of the underlying model.</li><li><strong><em>Scalability:</em></strong> Since Spring AI leverages the core strengths of the Spring ecosystem, it provides out-of-the-box scalability features, making it easier to scale AI applications to handle larger volumes of data and traffic.</li><li><strong><em>Easy Model Deployment:</em></strong> Spring AI simplifies the process of deploying AI models as services, enabling you to integrate them into real-time applications like chatbots, recommendation systems, and more.</li></ul><p><strong>Why I Chose Spring AI for This Project</strong></p><p>For this chatbot project, Spring AI was an ideal choice because of its ability to quickly integrate AI-powered models into a Spring-based application. Since I was already familiar with the Spring Framework, using Spring AI allowed me to stay within the Spring ecosystem and leverage its powerful features, such as dependency injection and easy configuration management.</p><p>Moreover, the modular and flexible nature of Spring AI allowed me to experiment with different AI models and embeddings without being tied to a specific approach. The clean integration with Spring Boot also made it straightforward to manage and deploy the application, giving me more time to focus on building the core chatbot functionality rather than worrying about complex infrastructure or dependencies.</p><p><strong><em>System Architecture Overview</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeg-A6AeHqHoy2qwiJekbg.png" /></figure><p><strong><em>Flow</em>:</strong></p><ol><li>User submits a query.</li><li>Main Orchestrator (could be an LLM or a rules-based classifier) analyses the query to detect the intent/context.</li><li>The orchestrator routes the request to one of the three agents:</li></ol><ul><li>Travel Planner Agent (e.g., suggests destinations, builds itineraries)</li><li>Weather Reporter Agent (e.g., gives weather for a location/date)</li><li>Currency Converter Agent (e.g., converts money between currencies)</li></ul><p>4. The chosen agent processes the query and returns its data/result.</p><p>5. The orchestrator (or a response composer) formats the answer and sends it back to the user.</p><p><strong><em>Step-by-Step implementation</em></strong></p><p><strong>Step 1:</strong> Setting Up Spring AI project</p><p>Generate a sample Spring project by including below dependencies -</p><ol><li><strong>Azure OpenAI </strong>— Spring AI support for Azure’s OpenAI offering, powered by ChatGPT. It extends beyond traditional OpenAI capabilities, delivering AI-driven text generation with enhanced functionality. <a href="https://docs.spring.io/spring-ai/reference/api/chat/azure-openai-chat.html">Click here</a></li><li><strong>Spring Web</strong> — Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container. <a href="https://docs.spring.io/spring-boot/3.4.5/reference/web/servlet.html">Click here</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8-YjTsNCDsulaG4V3SXVA.png" /></figure><pre>&lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-ai-starter-model-azure-openai&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.azure&lt;/groupId&gt;<br>            &lt;artifactId&gt;azure-core&lt;/artifactId&gt;<br>            &lt;version&gt;1.55.3&lt;/version&gt; <br>        &lt;/dependency&gt;<br> <br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.azure&lt;/groupId&gt;<br>            &lt;artifactId&gt;azure-core-http-netty&lt;/artifactId&gt;<br>            &lt;version&gt;1.13.9&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;<br>            &lt;artifactId&gt;poi-ooxml&lt;/artifactId&gt;<br>            &lt;version&gt;5.2.3&lt;/version&gt;<br>        &lt;/dependency&gt;<br>         &lt;!-- gRPC dependencies --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-netty-shaded&lt;/artifactId&gt;<br>        &lt;version&gt;1.59.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-protobuf&lt;/artifactId&gt;<br>        &lt;version&gt;1.59.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-stub&lt;/artifactId&gt;<br>        &lt;version&gt;1.59.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><p><strong>Step 2:</strong> Build and Configure an OpenAIClientBuilder with Custom Headers.</p><p>Follow these steps to create and configure an OpenAIClientBuilder with a gateway URL and custom headers:</p><ol><li>Begin by instantiating the OpenAIClientBuilder object.</li><li>Set up a Reactor Netty HTTP Client to manage HTTP communication effectively.</li><li>Ensure SSL (Secure Sockets Layer) is enabled to facilitate secure and encrypted communication with the server.</li><li>Include any required custom HTTP headers for authentication or additional metadata.</li><li>Use the configured Reactor Netty HTTP Client to create an Azure HTTP Client.</li><li>Create HTTP Pipeline.</li><li>Finally, attach the Azure HTTP Client to the OpenAIClientBuilder to complete the setup.</li></ol><pre>import java.io.File;<br>import java.io.FileInputStream;<br>import java.io.IOException;<br>import java.security.KeyStore;<br>import java.security.cert.CertificateFactory;<br>import java.security.cert.X509Certificate;<br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;<br>import javax.net.ssl.TrustManagerFactory;<br>import com.azure.ai.openai.OpenAIClientBuilder;<br>import com.azure.core.http.HttpClient;<br>import com.azure.core.http.HttpPipelineBuilder;<br>import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;<br>import io.netty.handler.ssl.SslContext;<br>import io.netty.handler.ssl.SslContextBuilder;<br>import io.netty.handler.ssl.SslProvider;<br>import io.netty.handler.ssl.util.InsecureTrustManagerFactory;<br>/**<br> * Creates and configures an `OpenAIClientBuilder` with custom HTTP client settings.<br> *<br> * This method performs the following steps:<br> * 1. Sets up the OpenAI client builder with the specified endpoint (Gateway URL).<br> * 2. Configures a Reactor Netty HTTP client for secure communication, including:<br> *    - SSL context for HTTPS connections.<br> *    - Custom headers for HTTP requests.<br> * 3. Wraps the Reactor Netty HTTP client into an Azure-specific `NettyAsyncHttpClientBuilder`.<br> * 4. Builds an `HttpPipeline` that attaches the configured HTTP client.<br> * 5. Returns the fully configured `OpenAIClientBuilder`.<br> *<br> * @return A fully configured instance of `OpenAIClientBuilder`.<br> */<br>public static OpenAIClientBuilder getBuilder() {<br>    // Step 1: Initialize the OpenAIClientBuilder with the specified endpoint<br>    OpenAIClientBuilder builder = new OpenAIClientBuilder()<br>            .endpoint(&quot;Gateway URL&quot;); // Sets the endpoint (Gateway URL) for the OpenAI client. Replace with the actual URL.<br> <br>    // Step 2: Configure a Reactor Netty HTTP client<br>    reactor.netty.http.client.HttpClient reactorHttpClient = reactor.netty.http.client.HttpClient.create()<br>            // Configure SSL for secure communication<br>            .secure(sslSpec -&gt; {<br>                try {<br>                    // Create and set the SSL context for secure connections<br>                    sslSpec.sslContext(createSslContext());<br>                } catch (Exception e) {<br>                    // Handle potential exceptions during SSL context creation<br>                    e.printStackTrace();<br>                }<br>            })<br>            // Add custom headers to the HTTP requests<br>            .headers(headers -&gt; {<br>                headers.add(&quot;customHeader1_key&quot;, &quot;customHeader1_value&quot;); // Example header 1<br>                headers.add(&quot;customHeader2_key&quot;, &quot;customHeader2_value&quot;); // Example header 2<br>                headers.add(&quot;customHeader3_key&quot;, &quot;customHeader3_value&quot;); // Example header 3<br>                headers.add(&quot;customHeader4_key&quot;, &quot;customHeader4_value&quot;); // Example header 4<br>                headers.add(&quot;customHeader5_key&quot;, &quot;customHeader5_value&quot;); // Example header 5<br>                headers.add(&quot;customHeader6_key&quot;, &quot;customHeader6_value&quot;); // Example header 6<br>            });<br> <br>    // Step 3: Wrap the Reactor HTTP client into an Azure-specific HTTP client<br>    HttpClient azureHttpClient = new NettyAsyncHttpClientBuilder(reactorHttpClient).build();<br> <br>    // Step 4: Build an HTTP pipeline to attach the custom HTTP client<br>    HttpClient httpClient = new HttpPipelineBuilder()<br>            .httpClient(azureHttpClient) // Attach the Azure-specific HTTP client<br>            .build()<br>            .getHttpClient();<br> <br>    // Step 5: Attach the HTTP client to the OpenAIClientBuilder<br>    builder.httpClient(httpClient);<br> <br>    // Step 6: Return the configured OpenAIClientBuilder<br>    return builder;<br>}<br> <br>/**<br> * Creates an SSL context for secure communication using a custom Certificate Authority (CA) certificate.<br> *<br> * The method performs the following steps:<br> * 1. Loads the CA certificate from a specified path.<br> * 2. Creates a KeyStore containing the trusted CA certificate.<br> * 3. Initializes a TrustManagerFactory with the KeyStore.<br> * 4. Builds and returns an SslContext configured for client use.<br> *<br> * Note: Replace &quot;CERT PATH&quot; with the actual path to the CA certificate file.<br> *<br> * @return an SslContext configured for secure communication.<br> * @throws Exception if any step in the process fails (e.g., file not found, invalid certificate).<br> */<br>public static SslContext createSslContext() throws Exception {<br>    // Step 1: Load the CA certificate<br>    CertificateFactory cf = CertificateFactory.getInstance(&quot;X.509&quot;); // Create a CertificateFactory for X.509 certificates<br>    X509Certificate caCert;<br>    try (FileInputStream fis = new FileInputStream(&quot;CERT PATH&quot;)) { // Replace &quot;CERT PATH&quot; with the actual file path of the CA certificate<br>        caCert = (X509Certificate) cf.generateCertificate(fis); // Generate the CA certificate from the file<br>    }<br> <br>    // Step 2: Create a KeyStore containing the trusted CA<br>    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); // Create a new KeyStore instance for storing certificates<br>    keyStore.load(null, null); // Initialize the KeyStore with no password<br>    keyStore.setCertificateEntry(&quot;ca&quot;, caCert); // Add the CA certificate to the KeyStore with an alias &quot;ca&quot;<br> <br>    // Step 3: Create a TrustManager that trusts the CA in the KeyStore<br>    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Get the default TrustManagerFactory<br>    tmf.init(keyStore); // Initialize the TrustManagerFactory with the KeyStore<br> <br>    // Step 4: Build and return the SSL context for client use<br>    return SslContextBuilder.forClient() // Create a new SSL context builder for client-side SSL<br>            .sslProvider(SslProvider.JDK) // Use the JDK SSL provider<br>            .trustManager(InsecureTrustManagerFactory.INSTANCE) // Use an insecure TrustManager for demonstration purposes<br>            .build(); // Build the SSL context<br>}</pre><p><strong>Step 7:</strong> Create a AzureOpenAiChatModel bean using OpenAIClientBuilder</p><pre>/**<br> * Configures and provides a Spring-managed bean for the Azure OpenAI Chat Model.<br> *<br> * This method creates an instance of the `AzureOpenAiChatModel` with the following configuration:<br> * 1. Utilizes a custom OpenAI client builder for connecting to Azure OpenAI services.<br> * 2. Sets default options for the chat model, including deployment name, maximum tokens, and temperature.<br> * 3. Registers the configured `AzureOpenAiChatModel` instance as a Spring-managed bean.<br> *<br> * @return an initialized and configured instance of `AzureOpenAiChatModel`.<br> */<br>@Bean<br>public AzureOpenAiChatModel azureOpenAiChatModel() {<br>    return AzureOpenAiChatModel.builder()<br>            // Step 1: Set the OpenAI client builder<br>            .openAIClientBuilder(CommonUtil.getBuilder()) // Retrieves a pre-configured OpenAI client builder<br>             <br>            // Step 2: Configure default options for the chat model<br>            .defaultOptions(AzureOpenAiChatOptions.builder()<br>                    .deploymentName(&quot;gpt-4o&quot;) // Specify the deployment name for the model (e.g., &quot;gpt-4o&quot;)<br>                    .maxTokens(1000)         // Set the maximum number of tokens for responses<br>                    .temperature(0.1)       // Set the temperature for response creativity (lower values = more deterministic)<br>                    .build())<br>             <br>            // Step 3: Build the Azure OpenAI Chat Model instance<br>            .build();<br>}</pre><p><strong>Step 3:</strong> Initiating a Chat Using AzureOpenAiChatModel. The following steps outline the chat process leveraging the AzureOpenAiChatModel:</p><ol><li><strong>Capture User Input:</strong> Retrieve the user’s input from the UI chat interface. Ensure the input is sanitized and pre-processed (if necessary) to handle special characters, incomplete queries, or ambiguous phrases.</li><li><strong>Intent Recognition:</strong> Utilize an intent recognition engine or model to analyze the user’s query and determine the context or category (e.g., Travel Planning, Weather Information, or Currency Conversion). This step may involve natural language processing (NLP) techniques to extract key phrases, entities, and the overall intent.</li><li><strong>Activate Relevant Agents: </strong>Based on the recognized intent, activate the appropriate agents or services to handle the specific tasks. These agents are specialized modules designed to perform context-specific operations (e.g., fetching travel itineraries, retrieving weather data, or calculating currency exchange rates).</li><li><strong>Consolidate Results: </strong>Gather and aggregate the responses from all the activated agents. Format the consolidated results into a cohesive and user-friendly response that directly addresses the user’s query. Handle edge cases such as missing data from agents or conflicting outputs gracefully.</li><li><strong>Return Response to User: </strong>Send the final response back to the user through the UI chat interface. Include any additional context or follow-up suggestions if applicable to improve the user’s experience further. Ensure the response is clear, concise, and actionable.</li></ol><pre>/**<br> * Handles user queries related to Travel, Weather, and Currency Conversion.<br> * This method processes a user query, determines its intent, and delegates it to the corresponding handler.<br> *<br> * @param queryText The query provided by the user, passed as a request parameter.<br> * @return ChatResponseLocal An object containing the response generated by the appropriate handlers.<br> *<br> * The flow of this method:<br> * 1. The user&#39;s query is analyzed using a multi-functional ChatClient.<br> * 2. The ChatClient determines whether the query is related to Travel Planning, Weather Information, or Currency Conversion.<br> * 3. The classification is returned in a map format, where:<br> *    - Key: The category (e.g., Travel Planning, Weather Information, Currency Conversion, or Context).<br> *    - Value: The respective query or high-level context.<br> * 4. Based on the categories identified in the map:<br> *    - Travel queries are handled by `handleTravelPlanning`.<br> *    - Weather queries are handled by `handleWeather`.<br> *    - Currency conversion queries are handled by `handleCurrencyConversion`.<br> * 5. The responses from the handlers are aggregated and returned as a single result.<br> */<br>@GetMapping(value = &quot;/travel&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>public ChatResponseLocal getChatTravel(@RequestParam(&quot;text&quot;) String queryText) {<br>    // Step 1: Use ChatClient to analyze the user&#39;s query and classify it into a category<br>    String response = ChatClient.create(chatModel).prompt()<br>            .user(u -&gt; u.text(&quot;You are a multi-functional assistant. Analyze the user&#39;s query: \&quot;&quot; + queryText<br>                + &quot;\&quot; and decide whether it is related to Travel Planning, Weather Information, or Currency Conversion. Provide the response in map format, where key will be category and value will be respective query. Provide a very high-level context of the query as a separate key in the map as &#39;Context&#39;&quot;))<br>            .call().content();<br><br>    // Log the response from ChatClient for debugging purposes<br>    System.out.println(response);<br><br>    // Step 2: Initialize an empty result string<br>    String result = &quot;&quot;;<br><br>    // Step 3: Convert the response from the ChatClient into a Map for easier processing<br>    Map&lt;String, String&gt; map = convertStringToHashMap(response);<br><br>    // Step 4: Check if the response contains the &quot;Travel Planning&quot; category and handle it<br>    if (response.contains(&quot;Travel Planning&quot;)) {<br>        result = result + &quot;\n\n\n&quot; + handleTravelPlanning(&quot;Context : &quot; + map.get(&quot;Context&quot;) + &quot;\n&quot; + map.get(&quot;Travel Planning&quot;));<br>    }<br><br>    // Step 5: Check if the response contains the &quot;Weather Information&quot; category and handle it<br>    if (response.contains(&quot;Weather Information&quot;)) {<br>        result = result + &quot;\n\n\n&quot; + handleWeather(&quot;Context : &quot; + map.get(&quot;Context&quot;) + &quot;\n&quot; + map.get(&quot;Weather Information&quot;));<br>    }<br><br>    // Step 6: Check if the response contains the &quot;Currency Conversion&quot; category and handle it<br>    if (response.contains(&quot;Currency Conversion&quot;)) {<br>        result = result + &quot;\n\n\n&quot; + handleCurrencyConversion(&quot;Context : &quot; + map.get(&quot;Context&quot;) + &quot;\n&quot; + map.get(&quot;Currency Conversion&quot;));<br>    }<br><br>    // Step 7: Wrap the aggregated result into a ChatResponseLocal object and return it<br>    return new ChatResponseLocal(result);<br>}</pre><p><strong>Step 4:</strong> Travel planning agent. In this example, the travel planning agent generates a detailed itinerary, saves it as a PDF file, and places it on the user’s desktop for easy access. While this serves as a simple demonstration, a real-world implementation can be significantly enhanced by integrating additional features, such as:</p><ol><li><strong>Ticket Booking Integration</strong>: Connect with third-party travel booking APIs to book flights, hotels, and other travel services directly based on the user’s preferences.</li><li><strong>Calendar Integration:</strong> Automatically schedule the planned events or itineraries in the user’s calendar (Google Calendar, Microsoft Outlook, etc.) to ensure they have timely reminders and updates.</li><li><strong>Collaboration &amp; Sharing:</strong> Provide options for sharing the itinerary with others via email, messaging apps, or collaborative platforms.</li></ol><pre>/**<br> * Handles Travel Planning queries by generating an itinerary and creating a PDF.<br> *<br> * @param query The user&#39;s travel-related query, including context and details about the itinerary.<br> * @return A String indicating the file path of the generated PDF or an error message if the PDF creation fails.<br> *<br> * Steps:<br> * 1. **Log the Query**: Logs the travel query for debugging purposes.<br> * 2. **Generate Itinerary**: Uses the ChatClient to generate an itinerary by providing the user&#39;s query to a travel planner assistant.<br> *    - The assistant is instructed to provide strictly itinerary details.<br> * 3. **Create PDF**: Calls the `createPdf` method to generate a PDF file on the user&#39;s desktop with the itinerary details.<br> * 4. **Return Response**: Returns a message with the file path of the generated PDF or an error message if something goes wrong.<br> */<br>private String handleTravelPlanning(String query) {<br>    // Step 1: Log the travel query<br>    System.out.println(&quot;Travel planner : &quot; + query);<br><br>    // Step 2: Generate itinerary using ChatClient<br>    String response = ChatClient.create(chatModel).prompt().user(<br>            u -&gt; u.text(&quot;You are a Travel planner assistant. Please help the user strictly with itinerary details : \&quot;&quot; + query))<br>            .call().content();<br><br>    // Step 3: Create a PDF with the generated itinerary<br>    String fileName = createPdf(&quot;Travel_Plan.pdf&quot;, response);<br><br>    // Step 4: Return response with PDF file path<br>    return &quot;I am your Travel Planning agent : \n\n&quot; + fileName;<br>}<br><br>/**<br> * Creates a PDF file with the given content and saves it to the user&#39;s desktop.<br> *<br> * @param fileName The name of the PDF file to be created.<br> * @param content The content to be written into the PDF.<br> * @return A String indicating the file path of the created PDF or an error message if the creation fails.<br> *<br> * Steps:<br> * 1. **Determine File Path**: Constructs the file path using the user&#39;s desktop directory.<br> * 2. **Create PDF Document**: Uses Apache PDFBox to create a PDF document with one page.<br> * 3. **Add Content to PDF**: Writes the provided content into the PDF using a content stream.<br> *    - The content is split into lines to ensure proper formatting.<br> *    - Adjusts line spacing for better readability.<br> * 4. **Save and Close**: Saves the PDF file to the desktop and closes the document.<br> * 5. **Handle Exceptions**: Catches and logs any IOExceptions that occur during the process.<br> */<br>public String createPdf(String fileName, String content) {<br>    // Step 1: Determine the file path for the PDF<br>    String userHome = System.getProperty(&quot;user.home&quot;);<br>    String desktopPath = userHome + File.separator + &quot;Desktop&quot; + File.separator + fileName;<br><br>    try (PDDocument document = new PDDocument()) {<br>        // Step 2: Create a new PDF document with one page<br>        PDPage page = new PDPage();<br>        document.addPage(page);<br><br>        // Step 3: Add content to the PDF<br>        try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {<br>            contentStream.beginText();<br>            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 8);<br>            contentStream.newLineAtOffset(100, 700);<br><br>            // Split the text into lines manually and write each line<br>            String[] lines = content.split(&quot;\n&quot;);<br>            for (String line : lines) {<br>                contentStream.showText(line);<br>                contentStream.newLineAtOffset(0, -20); // Move to the next line (adjust spacing as needed)<br>            }<br>            contentStream.endText();<br>        }<br><br>        // Step 4: Save the PDF to the specified path<br>        document.save(desktopPath);<br>        return &quot;Planned PDF created at : &quot; + desktopPath;<br><br>    } catch (IOException e) {<br>        // Step 5: Handle exceptions and return error message<br>        e.printStackTrace();<br>        return &quot;Error creating PDF: &quot; + e.getMessage();<br>    }<br>}</pre><p><strong>Step 5:</strong> Weather reporter agent. In this example, we connect to an LLM (Large Language Model) to generate weather-related suggestions based on the user’s query. However, in a real-world implementation, this step can be enhanced by integrating with a reliable weather service or API (e.g., OpenWeatherMap, WeatherStack, or AccuWeather) to fetch accurate, real-time weather data. This approach ensures that the user receives up-to-date and precise weather information tailored to their location or query.</p><p>Additionally, you can implement fallback mechanisms to handle cases where the weather API is unavailable or returns incomplete data, such as reverting to cached data or providing a generic response.</p><pre>/**<br> * Handles queries related to Weather Information by providing weather details.<br> *<br> * @param query The user&#39;s weather-related query, including context and details about the location or weather information needed.<br> * @return A String containing the response generated by the Weather Information provider.<br> *<br> * Steps:<br> * 1. **Log the Query**: Logs the weather query for debugging purposes.<br> * 2. **Generate Weather Details**: Uses the ChatClient to generate weather information by providing the user&#39;s query to a weather information provider assistant.<br> *    - The assistant is instructed to provide strictly weather-related details.<br> * 3. **Return Response**: Returns the weather information as a response.<br> */<br>private String handleWeather(String query) {<br>    // Step 1: Log the weather query<br>    System.out.println(&quot;Weather reporter : &quot; + query);<br><br>    // Step 2: Generate weather details using ChatClient<br>    String response = ChatClient.create(chatModel).prompt()<br>            .user(u -&gt; u.text(&quot;You are a Weather information provider. Please help the user strictly with Weather details : \&quot;&quot; + query))<br>            .call().content();<br><br>    // Step 3: Return response with weather information<br>    return &quot;I am your Weather Information provider agent : \n\n&quot; + response;<br>}</pre><p><strong>Step 6:</strong> Currency converter agent.In this example, we connect to an LLM (Large Language Model) to generate currency conversion suggestions based on the user’s query. While this approach provides a conceptual demonstration, in a real-world implementation, it is recommended to integrate with a dedicated currency conversion API (e.g., Open Exchange Rates, XE, or CurrencyLayer). These APIs offer reliable and real-time exchange rates, ensuring the user receives accurate and up-to-date information.</p><pre>/**<br> * Handles queries related to Currency Conversion by providing conversion details.<br> *<br> * @param query The user&#39;s currency conversion query, including details about the currencies and amounts involved.<br> * @return A String containing the response generated by the Currency Conversion helper.<br> *<br> * Steps:<br> * 1. **Log the Query**: Logs the currency conversion query for debugging purposes.<br> * 2. **Generate Conversion Details**: Uses the ChatClient to generate currency conversion details by providing the user&#39;s query to a currency conversion helper assistant.<br> *    - The assistant is instructed to provide strictly currency conversion-related details.<br> * 3. **Return Response**: Returns the currency conversion information as a response.<br> */<br>private String handleCurrencyConversion(String query) {<br>    // Step 1: Log the currency conversion query<br>    System.out.println(&quot;currency converter : &quot; + query);<br><br>    // Step 2: Generate currency conversion details using ChatClient<br>    String response = ChatClient.create(chatModel).prompt()<br>            .user(u -&gt; u.text(&quot;You are a Currency convert helper. Please help the user strictly with currency conversion : \&quot;&quot; + query))<br>            .call().content();<br><br>    // Step 3: Return response with currency conversion details<br>    return &quot;I am your Currency converter agent : \n\n&quot; + response;<br>}</pre><p><strong>Step 9:</strong> Render the response in chat UI -</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br> <br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Full-Screen Chat&lt;/title&gt;<br>    &lt;style&gt;<br>        * {<br>            margin: 0;<br>            padding: 0;<br>            box-sizing: border-box;<br>        }<br> <br>        body {<br>            font-family: Arial, sans-serif;<br>            height: 100vh;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            background-color: #f4f4f9;<br>        }<br> <br>        #chat-container {<br>            width: 100%;<br>            height: 100%;<br>            display: flex;<br>            flex-direction: column;<br>            background: #ffffff;<br>        }<br> <br>        #chat-header {<br>            padding: 15px;<br>            background-color: #007bff;<br>            color: white;<br>            text-align: center;<br>            font-size: 18px;<br>            font-weight: bold;<br>        }<br> <br>        #chat-messages {<br>            flex: 1;<br>            padding: 10px;<br>            overflow-y: auto;<br>            border-top: 1px solid #ddd;<br>            border-bottom: 1px solid #ddd;<br>        }<br> <br>        .message-container {<br>            display: flex;<br>            align-items: flex-start;<br>            margin-bottom: 10px;<br>        }<br> <br>        .message-container.user {<br>            justify-content: flex-end;<br>        }<br> <br>        .message-container.bot {<br>            justify-content: flex-start;<br>        }<br> <br>        .avatar {<br>            width: 40px;<br>            height: 40px;<br>            border-radius: 50%;<br>            background-color: #ddd;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            font-weight: bold;<br>            color: white;<br>            margin: 0 10px;<br>        }<br> <br>        .avatar.user {<br>            background-color: #007bff;<br>        }<br> <br>        .avatar.bot {<br>            background-color: #ff5c5c;<br>        }<br> <br>        .message {<br>            max-width: 70%;<br>            padding: 10px;<br>            border-radius: 10px;<br>            font-size: 14px;<br>            line-height: 1.5;<br>        }<br> <br>        .message.user {<br>            background: #e9f5ff;<br>            color: #007bff;<br>            border-radius: 10px 10px 0 10px;<br>        }<br> <br>        .message.bot {<br>            background: #007bff;<br>            color: white;<br>            border-radius: 10px 10px 10px 0;<br>        }<br> <br>        #chat-input {<br>            display: flex;<br>            padding: 10px;<br>            background-color: #f9f9f9;<br>            border-top: 1px solid #ddd;<br>        }<br> <br>        #chat-input input {<br>            flex: 1;<br>            border: 1px solid #ddd;<br>            border-radius: 4px;<br>            padding: 10px;<br>            font-size: 16px;<br>        }<br> <br>        #chat-input button {<br>            margin-left: 10px;<br>            background-color: #007bff;<br>            color: #fff;<br>            border: none;<br>            border-radius: 4px;<br>            padding: 10px 15px;<br>            font-size: 16px;<br>            cursor: pointer;<br>        }<br> <br>        #chat-input button:hover {<br>            background-color: #0056b3;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br> <br>&lt;body&gt;<br>    &lt;div id=&quot;chat-container&quot;&gt;<br>        &lt;div id=&quot;chat-header&quot;&gt;Spring AI Agent&lt;/div&gt;<br>        &lt;div id=&quot;chat-messages&quot;&gt;&lt;/div&gt;<br>        &lt;div id=&quot;chat-input&quot;&gt;<br>            &lt;input type=&quot;text&quot; id=&quot;message-input&quot; placeholder=&quot;Type your message...&quot; /&gt;<br>            &lt;button id=&quot;send-button&quot;&gt;Send&lt;/button&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br> <br>    &lt;script&gt;<br>        const chatMessages = document.getElementById(&#39;chat-messages&#39;);<br>        const messageInput = document.getElementById(&#39;message-input&#39;);<br>        const sendButton = document.getElementById(&#39;send-button&#39;);<br> <br>        // Function to format the response before rendering<br>        function formatResponse(content) {<br>            // Example: Parse JSON and format it with indentation<br>            try {<br>                const jsonObject = JSON.parse(content); // Parse JSON string into an object<br>                return JSON.stringify(jsonObject, null, 2) // Format JSON with 2 spaces for indentation<br>                    .replace(/ /g, &#39; &#39;) // Replace spaces with HTML non-breaking spaces<br>                    .replace(/\n/g, &#39;&lt;br&gt;&#39;); // Replace newlines with &lt;br&gt; for HTML rendering<br>            } catch (error) {<br>                // If content is not JSON, return as-is<br>                return content<br>                    .replace(/\n/g, &#39;&lt;br&gt;&#39;) // Replace newlines with &lt;br&gt;<br>                    .trim(); // Remove extra whitespace<br>            }<br>        }<br> <br>        // Function to append messages to the chat<br>        function appendMessage(content, type, tempId = null) {<br>            const containerDiv = document.createElement(&#39;div&#39;);<br>            containerDiv.classList.add(&#39;message-container&#39;, type);<br> <br>            if (tempId) containerDiv.id = tempId; // Assign an ID for later replacement<br> <br>            const avatarDiv = document.createElement(&#39;div&#39;);<br>            avatarDiv.classList.add(&#39;avatar&#39;, type);<br>            avatarDiv.textContent = type === &#39;user&#39; ? &#39;U&#39; : &#39;B&#39;; // &quot;U&quot; for User, &quot;B&quot; for Bot<br> <br>            const messageDiv = document.createElement(&#39;div&#39;);<br>            messageDiv.classList.add(&#39;message&#39;, type);<br>            messageDiv.innerHTML = content;<br> <br>            containerDiv.appendChild(type === &#39;user&#39; ? messageDiv : avatarDiv);<br>            containerDiv.appendChild(type === &#39;user&#39; ? avatarDiv : messageDiv);<br> <br>            chatMessages.appendChild(containerDiv);<br>            chatMessages.scrollTop = chatMessages.scrollHeight; // Auto-scroll to the bottom<br>        }<br>        function updateMessage(tempId, content) {<br>            const containerDiv = document.getElementById(tempId);<br>            if (containerDiv) {<br>                const messageDiv = containerDiv.querySelector(&#39;.message&#39;);<br>                if (messageDiv) {<br>                    messageDiv.innerHTML = content;<br>                }<br>            }<br>        }<br> <br>        // Function to handle sending messages<br>        async function sendMessage() {<br>            const userMessage = messageInput.value.trim();<br>            if (!userMessage) return;<br> <br>            appendMessage(userMessage, &#39;user&#39;); // Display user&#39;s message<br>            messageInput.value = &#39;&#39;; // Clear input field<br> <br>            const tempId = `temp-${Date.now()}`;<br>            appendMessage(&#39;&lt;span class=&quot;typing-indicator&quot;&gt;Planning response...&lt;/span&gt;&#39;, &#39;bot&#39;, tempId);<br> <br>            try {<br>                // Call the GET API to fetch the bot&#39;s response<br>                const response = await fetch(`http://localhost:8080/travel?text=${encodeURIComponent(userMessage)}`);<br>                if (!response.ok) throw new Error(&#39;Failed to fetch response&#39;);<br> <br>                const data = await response.json();<br>                const formattedResponse = formatResponse(data.response);<br>                updateMessage(tempId, formattedResponse);<br>            } catch (error) {<br>                updateMessage(tempId, &#39;Error: Unable to connect to server&#39;);<br>            }<br>        }<br> <br>        // Add event listeners for send button and Enter key<br>        sendButton.addEventListener(&#39;click&#39;, sendMessage);<br>        messageInput.addEventListener(&#39;keypress&#39;, (event) =&gt; {<br>            if (event.key === &#39;Enter&#39;) sendMessage();<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br> <br>&lt;/html&gt;</pre><p><strong>Step 9:</strong> Chat output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdKGILILt_U-gTNLW_bQIA.png" /></figure><p>The Spring AI project showcases the integration of a conversational AI system within a Spring-based backend to provide intelligent, context-aware responses to user queries. The application implements a modular and extendable architecture, leveraging a Large Language Model (LLM) for understanding and generating responses. The system supports various functionalities, including travel planning, weather reporting, and currency conversion, while demonstrating how to extend these capabilities for real-world applications by integrating external APIs and services.</p><p>The project is designed to act as a multi-functional assistant capable of analyzing user inputs, identifying their intent, and delegating tasks to specific agents. These agents then handle context-specific requests and return actionable results to the user.</p><h3>Key Highlights:</h3><h3>1. Intelligent Query Processing</h3><ul><li>The system uses LLMs to analyze the user’s query and determine its intent.</li><li>Contexts such as <em>Travel Planning</em>, <em>Weather Information</em>, and <em>Currency Conversion</em> are identified and routed to dedicated agents.</li></ul><h3>2. Modular Agent Architecture</h3><ul><li>Each functionality is implemented as a separate agent:</li><li>Travel Planning Agent: Generates detailed itineraries and saves them as PDFs.</li><li>Weather Reporter Agent: Provides weather information based on the user’s query.</li><li>Currency Converter Agent: Handles currency conversion tasks with precise outputs.</li><li>Agents can be easily extended or replaced with real-world APIs or services.</li></ul><h3>3. LLM Integration</h3><ul><li>LLMs are utilized for generating responses and suggestions.</li><li>Provides a versatile fallback mechanism for generating content when external APIs are not integrated.</li></ul><h3>4. Travel Planner Highlights</h3><ul><li>Creates detailed itineraries in PDF format, saving them on the desktop.</li><li>Easily extendable to include:</li><li>Ticket booking via travel APIs.</li><li>Calendar integration for itinerary scheduling.</li></ul><h3>5. Weather Reporter Highlights</h3><ul><li>Uses LLMs for mock weather suggestions.</li><li>Extensible to fetch real-time weather data using APIs like OpenWeatherMap, AccuWeather, or WeatherStack.</li></ul><h3>6. Currency Converter Highlights</h3><ul><li>Processes currency conversion requests using LLMs for demonstration.</li><li>Can integrate APIs such as Open Exchange Rates or XE for real-time conversion rates.</li></ul><h3>7. Future Implementation Opportunities</h3><ul><li>Real-Time Data Integration: APIs for dynamic updates (e.g., weather, currency rates).</li><li>Calendar and Collaboration Features: Automated scheduling and sharing of results.</li><li>Enhanced Error Handling: Better fallback mechanisms for API failures.</li><li>Multi-Language Support: Localized responses for a broader audience.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc572a469612" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/spring-ai-meets-gpt-4o-creating-a-simple-multi-agent-ai-system-fc572a469612">Spring AI Meets GPT-4o: Creating a Simple Multi-Agent AI System</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Intelligent Chatbot with Spring AI and Milvus: A Hands-On Guide — new]]></title>
            <link>https://medium.com/walmartglobaltech/building-an-intelligent-chatbot-with-spring-ai-and-milvus-a-hands-on-guide-new-21a1b6ccfc0f?source=rss-c5ca8a7f81e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a1b6ccfc0f</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[milvus]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Dipak Maity]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 06:40:36 GMT</pubDate>
            <atom:updated>2025-09-02T06:40:36.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Intelligent Chatbot with Spring AI and Milvus: A Hands-On Guide</h3><figure><img alt="AI generated Image" src="https://cdn-images-1.medium.com/max/1024/1*inWJtlVyRkjxAUsKqWcdHw.png" /><figcaption>AI generated Image</figcaption></figure><p>Spring AI is a powerful extension of the widely used Spring Framework, designed to simplify the development of AI-based applications. It provides seamless integration with various AI models and tools, leveraging the flexibility and scalability of the Spring ecosystem to build AI-driven solutions. Spring AI abstracts much of the complexity of deploying AI models, allowing developers to focus on building and scaling applications rather than worrying about infrastructure details.</p><p>Spring AI supports a variety of machine learning and AI workflows, from natural language processing (NLP) to image recognition, making it a versatile choice for a wide range of projects. With Spring’s robust support for dependency injection, configuration management, and scalability, Spring AI makes it easy to build production-ready AI applications.</p><p><strong>Benefits of Using Spring AI</strong></p><p><strong><em>Seamless Integration with Spring Ecosystem:</em> </strong>Spring AI integrates seamlessly with the larger Spring Framework, allowing you to take advantage of Spring Boot, Spring Cloud, and other Spring projects for easy deployment, scalability, and maintenance.</p><p><strong><em>Modular and Flexible Architecture:</em></strong> Spring AI allows developers to choose the right AI models and frameworks without being locked into a specific technology. It provides flexibility in integrating popular AI and machine learning models with your application.</p><p><strong><em>Enhanced Developer Productivity:</em></strong> Spring AI abstracts many of the complexities of working with AI models, enabling developers to quickly prototype and implement AI functionality without needing to deep dive into every technical detail of the underlying model.</p><p><strong><em>Scalability:</em></strong> Since Spring AI leverages the core strengths of the Spring ecosystem, it provides out-of-the-box scalability features, making it easier to scale AI applications to handle larger volumes of data and traffic.</p><p><strong><em>Easy Model Deployment:</em></strong> Spring AI simplifies the process of deploying AI models as services, enabling you to integrate them into real-time applications like chatbots, recommendation systems, and more.</p><p><strong>Why I Chose Spring AI for This Project</strong></p><p>For this chatbot project, Spring AI was an ideal choice because of its ability to quickly integrate AI-powered models into a Spring-based application. Since I was already familiar with the Spring Framework, using Spring AI allowed me to stay within the Spring ecosystem and leverage its powerful features, such as dependency injection and easy configuration management.</p><p>Moreover, the modular and flexible nature of Spring AI allowed me to experiment with different AI models and embeddings without being tied to a specific approach. The clean integration with Spring Boot also made it straightforward to manage and deploy the application, giving me more time to focus on building the core chatbot functionality rather than worrying about complex infrastructure or dependencies.</p><p><strong><em>System Architecture Overview</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EstFznhIQr5xUA9WBjlURA.png" /></figure><p><strong><em>Flow</em>:</strong></p><ol><li>The client application sends a query to the Spring AI backend.</li><li>The Spring AI backend intercepts the request and sends the query to Milvus to retrieve relevant embeddings (context).</li><li>Next, the query (along with the retrieved context) is sent to OpenAI’s LLM for processing.</li><li>The OpenAI LLM generates a response and sends it back to the Spring AI backend.</li><li>The Spring AI backend sends the processed response to the client application.</li></ol><p><strong><em>Step-by-Step implementation</em></strong></p><p><strong>Step 1:</strong> Setting Up Spring AI project</p><p>Generate a sample Spring project by including below dependencies -</p><ol><li><strong>Azure OpenAI </strong>— Spring AI support for Azure’s OpenAI offering, powered by ChatGPT. It extends beyond traditional OpenAI capabilities, delivering AI-driven text generation with enhanced functionality. <a href="https://docs.spring.io/spring-ai/reference/api/chat/azure-openai-chat.html">Click here</a></li><li><strong>Milvus Vector Database</strong> — Spring AI vector database support for Milvus. It is an open-source vector database that has garnered significant attention in the fields of data science and machine learning. One of its standout features lies in its robust support for vector indexing and querying. <a href="https://docs.spring.io/spring-ai/reference/api/vectordbs/milvus.html">Click here</a></li><li><strong>Spring Web</strong> — Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container. <a href="https://docs.spring.io/spring-boot/3.4.5/reference/web/servlet.html">Click here</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJmyFWVOfG2k92hUSsTaag.png" /></figure><pre>&lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-ai-starter-model-azure-openai&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.azure&lt;/groupId&gt;<br>            &lt;artifactId&gt;azure-core&lt;/artifactId&gt;<br>            &lt;version&gt;1.55.3&lt;/version&gt; <br>        &lt;/dependency&gt;<br> <br>        &lt;dependency&gt;<br>            &lt;groupId&gt;com.azure&lt;/groupId&gt;<br>            &lt;artifactId&gt;azure-core-http-netty&lt;/artifactId&gt;<br>            &lt;version&gt;1.13.9&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.milvus&lt;/groupId&gt;<br>            &lt;artifactId&gt;milvus-sdk-java&lt;/artifactId&gt;<br>            &lt;version&gt;2.2.0&lt;/version&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;<br>            &lt;artifactId&gt;poi-ooxml&lt;/artifactId&gt;<br>            &lt;version&gt;5.2.3&lt;/version&gt;<br>        &lt;/dependency&gt;<br>         &lt;!-- gRPC dependencies --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-netty-shaded&lt;/artifactId&gt;<br>        &lt;version&gt;1.59.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-protobuf&lt;/artifactId&gt;<br>        &lt;version&gt;1.59.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>        &lt;artifactId&gt;grpc-stub&lt;/artifactId&gt;<br>        &lt;version&gt;1.59.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;</pre><p><strong>Step 2:</strong> Setting Up Milvus as the Vector Database in local</p><ol><li>Make sure Docker is installed and running on your system. <a href="https://docs.docker.com/get-started/get-docker/">Install Docker</a></li><li>Run the below command to pull latest milvus docker image -</li></ol><pre>docker pull milvusdb/milvus:latest</pre><p>3. Milvus can be started or stopped from the docker start/stop control -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XucdA7xzkzLDpw4NkpztXA.png" /></figure><p><strong>Step 3:</strong> Initialise the milvus DB</p><ol><li>Creates a new instance of the MilvusServiceClient using the connection parameters (connectParam).</li><li>Assigns the newly created MilvusServiceClient instance to the milvusClient variable.</li><li>Initialise the milvus connection (by default, milvus will be running in 19530 port)</li></ol><pre>import java.util.ArrayList;<br>import java.util.List;</pre><pre>import org.springframework.stereotype.Component;</pre><pre>import io.milvus.client.MilvusServiceClient;<br>import io.milvus.grpc.DataType;<br>import io.milvus.grpc.SearchResults;<br>import io.milvus.param.ConnectParam;<br>import io.milvus.param.IndexType;<br>import io.milvus.param.MetricType;<br>import io.milvus.param.R;<br>import io.milvus.param.RpcStatus;<br>import io.milvus.param.collection.CreateCollectionParam;<br>import io.milvus.param.collection.DropCollectionParam;<br>import io.milvus.param.collection.FieldType;<br>import io.milvus.param.collection.LoadCollectionParam;<br>import io.milvus.param.dml.InsertParam;<br>import io.milvus.param.dml.InsertParam.Field;<br>import io.milvus.param.dml.SearchParam;<br>import io.milvus.param.index.CreateIndexParam;<br>import io.milvus.response.SearchResultsWrapper;<br>import io.milvus.response.SearchResultsWrapper.IDScore;<br></pre><pre>private final String collectionName = &quot;Xls_embeddings&quot;;<br>private static MilvusServiceClient milvusClient;<br>/**<br> * Initializes the Milvus client connection.<br> * This method establishes a connection to the Milvus server (a vector database)<br> * using the provided host and port. If the `milvusClient` instance is null,<br> * it creates and initializes a new client connection.<br> *<br> * Note: Replace the default host (&quot;127.0.0.1&quot;) and port (19530) with the actual<br> * values of your Milvus server configuration.<br> */<br>public void initializeMilvus() {<br>    // Check if the Milvus client has not been initialized<br>    if (milvusClient == null) {<br>        // Create connection parameters for the Milvus server<br>        ConnectParam connectParam = ConnectParam.newBuilder()<br>                .withHost(&quot;127.0.0.1&quot;) // Replace with the hostname or IP address of your Milvus server<br>                .withPort(19530)       // Replace with the port number of your Milvus server<br>                .build();<br> <br>        // Initialize the Milvus client with the connection parameters<br>        milvusClient = new MilvusServiceClient(connectParam);<br>    }<br>}</pre><p><strong>Step 4:</strong> Build and Configure an OpenAIClientBuilder with Custom Headers.</p><p>Follow these steps to create and configure an OpenAIClientBuilder with a gateway URL and custom headers:</p><ol><li>Begin by instantiating the OpenAIClientBuilder object.</li><li>Set up a Reactor Netty HTTP Client to manage HTTP communication effectively.</li><li>Ensure SSL (Secure Sockets Layer) is enabled to facilitate secure and encrypted communication with the server.</li><li>Include any required custom HTTP headers for authentication or additional metadata.</li><li>Use the configured Reactor Netty HTTP Client to create an Azure HTTP Client.</li><li>Create HTTP Pipeline.</li><li>Finally, attach the Azure HTTP Client to the OpenAIClientBuilder to complete the setup.</li></ol><pre>import java.io.File;<br>import java.io.FileInputStream;<br>import java.io.IOException;<br>import java.security.KeyStore;<br>import java.security.cert.CertificateFactory;<br>import java.security.cert.X509Certificate;<br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;</pre><pre>import javax.net.ssl.TrustManagerFactory;</pre><pre>import com.azure.ai.openai.OpenAIClientBuilder;<br>import com.azure.core.http.HttpClient;<br>import com.azure.core.http.HttpPipelineBuilder;<br>import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;</pre><pre>import io.netty.handler.ssl.SslContext;<br>import io.netty.handler.ssl.SslContextBuilder;<br>import io.netty.handler.ssl.SslProvider;<br>import io.netty.handler.ssl.util.InsecureTrustManagerFactory;</pre><pre>/**<br> * Creates and configures an `OpenAIClientBuilder` with custom HTTP client settings.<br> *<br> * This method performs the following steps:<br> * 1. Sets up the OpenAI client builder with the specified endpoint (Gateway URL).<br> * 2. Configures a Reactor Netty HTTP client for secure communication, including:<br> *    - SSL context for HTTPS connections.<br> *    - Custom headers for HTTP requests.<br> * 3. Wraps the Reactor Netty HTTP client into an Azure-specific `NettyAsyncHttpClientBuilder`.<br> * 4. Builds an `HttpPipeline` that attaches the configured HTTP client.<br> * 5. Returns the fully configured `OpenAIClientBuilder`.<br> *<br> * @return A fully configured instance of `OpenAIClientBuilder`.<br> */<br>public static OpenAIClientBuilder getBuilder() {<br>    // Step 1: Initialize the OpenAIClientBuilder with the specified endpoint<br>    OpenAIClientBuilder builder = new OpenAIClientBuilder()<br>            .endpoint(&quot;Gateway URL&quot;); // Sets the endpoint (Gateway URL) for the OpenAI client. Replace with the actual URL.<br> <br>    // Step 2: Configure a Reactor Netty HTTP client<br>    reactor.netty.http.client.HttpClient reactorHttpClient = reactor.netty.http.client.HttpClient.create()<br>            // Configure SSL for secure communication<br>            .secure(sslSpec -&gt; {<br>                try {<br>                    // Create and set the SSL context for secure connections<br>                    sslSpec.sslContext(createSslContext());<br>                } catch (Exception e) {<br>                    // Handle potential exceptions during SSL context creation<br>                    e.printStackTrace();<br>                }<br>            })<br>            // Add custom headers to the HTTP requests<br>            .headers(headers -&gt; {<br>                headers.add(&quot;customHeader1_key&quot;, &quot;customHeader1_value&quot;); // Example header 1<br>                headers.add(&quot;customHeader2_key&quot;, &quot;customHeader2_value&quot;); // Example header 2<br>                headers.add(&quot;customHeader3_key&quot;, &quot;customHeader3_value&quot;); // Example header 3<br>                headers.add(&quot;customHeader4_key&quot;, &quot;customHeader4_value&quot;); // Example header 4<br>                headers.add(&quot;customHeader5_key&quot;, &quot;customHeader5_value&quot;); // Example header 5<br>                headers.add(&quot;customHeader6_key&quot;, &quot;customHeader6_value&quot;); // Example header 6<br>            });<br> <br>    // Step 3: Wrap the Reactor HTTP client into an Azure-specific HTTP client<br>    HttpClient azureHttpClient = new NettyAsyncHttpClientBuilder(reactorHttpClient).build();<br> <br>    // Step 4: Build an HTTP pipeline to attach the custom HTTP client<br>    HttpClient httpClient = new HttpPipelineBuilder()<br>            .httpClient(azureHttpClient) // Attach the Azure-specific HTTP client<br>            .build()<br>            .getHttpClient();<br> <br>    // Step 5: Attach the HTTP client to the OpenAIClientBuilder<br>    builder.httpClient(httpClient);<br> <br>    // Step 6: Return the configured OpenAIClientBuilder<br>    return builder;<br>}<br> <br>/**<br> * Creates an SSL context for secure communication using a custom Certificate Authority (CA) certificate.<br> *<br> * The method performs the following steps:<br> * 1. Loads the CA certificate from a specified path.<br> * 2. Creates a KeyStore containing the trusted CA certificate.<br> * 3. Initializes a TrustManagerFactory with the KeyStore.<br> * 4. Builds and returns an SslContext configured for client use.<br> *<br> * Note: Replace &quot;CERT PATH&quot; with the actual path to the CA certificate file.<br> *<br> * @return an SslContext configured for secure communication.<br> * @throws Exception if any step in the process fails (e.g., file not found, invalid certificate).<br> */<br>public static SslContext createSslContext() throws Exception {<br>    // Step 1: Load the CA certificate<br>    CertificateFactory cf = CertificateFactory.getInstance(&quot;X.509&quot;); // Create a CertificateFactory for X.509 certificates<br>    X509Certificate caCert;<br>    try (FileInputStream fis = new FileInputStream(&quot;CERT PATH&quot;)) { // Replace &quot;CERT PATH&quot; with the actual file path of the CA certificate<br>        caCert = (X509Certificate) cf.generateCertificate(fis); // Generate the CA certificate from the file<br>    }<br> <br>    // Step 2: Create a KeyStore containing the trusted CA<br>    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); // Create a new KeyStore instance for storing certificates<br>    keyStore.load(null, null); // Initialize the KeyStore with no password<br>    keyStore.setCertificateEntry(&quot;ca&quot;, caCert); // Add the CA certificate to the KeyStore with an alias &quot;ca&quot;<br> <br>    // Step 3: Create a TrustManager that trusts the CA in the KeyStore<br>    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Get the default TrustManagerFactory<br>    tmf.init(keyStore); // Initialize the TrustManagerFactory with the KeyStore<br> <br>    // Step 4: Build and return the SSL context for client use<br>    return SslContextBuilder.forClient() // Create a new SSL context builder for client-side SSL<br>            .sslProvider(SslProvider.JDK) // Use the JDK SSL provider<br>            .trustManager(InsecureTrustManagerFactory.INSTANCE) // Use an insecure TrustManager for demonstration purposes<br>            .build(); // Build the SSL context<br>}</pre><p><strong>Step 5:</strong> Create an AzureOpenAiEmbeddingModel bean using OpenAIClientBuilder — this will be used to create embeddings.</p><pre>import org.springframework.ai.azure.openai.AzureOpenAiChatModel;<br>import org.springframework.ai.azure.openai.AzureOpenAiChatOptions;<br>import org.springframework.ai.azure.openai.AzureOpenAiEmbeddingModel;<br>import org.springframework.context.annotation.Bean;<br>/**<br> * Configures and provides a bean for the Azure OpenAI Embedding Model.<br> *<br> * This method creates an instance of the `AzureOpenAiEmbeddingModel`, sets its default deployment options,<br> * and registers it as a Spring-managed bean. The model is used for generating embeddings, which are vector representations<br> * of text, leveraging Azure OpenAI&#39;s embedding services.<br> *<br> * @return an initialized and configured instance of `AzureOpenAiEmbeddingModel`.<br> */<br>@Bean<br>public AzureOpenAiEmbeddingModel azureOpenAiEmbeddingModel() {<br>    // Step 1: Create an instance of AzureOpenAiEmbeddingModel using a pre-configured builder<br>    // The builder is assumed to be configured in the previous step and provides the client connection<br>    AzureOpenAiEmbeddingModel model = new AzureOpenAiEmbeddingModel(&lt;&lt;Builder from previous step&gt;&gt;.buildClient());<br> <br>    // Step 2: Set the default deployment name for the embedding model<br>    // Replace &quot;text-embedding-3-large&quot; with the name of your preferred embedding model deployment<br>    model.getDefaultOptions().setDeploymentName(&quot;text-embedding-3-large&quot;);<br> <br>    // Step 3: Return the configured model as a Spring-managed bean<br>    return model;<br>}</pre><p><strong>Step 6:</strong> Generating and Storing <a href="https://docs.spring.io/spring-ai/reference/api/embeddings.html#:~:text=Embeddings%20are%20numerical%20representations%20of,text%2C%20images%2C%20and%20videos.">embeddings</a> in Milvus DB</p><p>In this step, we will generate embeddings for your content using an embedding model and store them in the Milvus database. This example demonstrates the process using a REST API to create embeddings and save them effectively. Follow the steps below:</p><ol><li>Process the content file. In this example, we are using an Excel file containing two columns: “Question” and “Answer”.</li><li>Extract the list of questions from the file. Send these questions to the embedding model to generate vector embeddings.</li><li>Insert the generated embeddings along with their corresponding answers into the Milvus database for efficient retrieval and query processing.</li></ol><pre>import java.io.File;<br>import java.io.FileInputStream;<br>import java.io.IOException;<br>import java.security.KeyStore;<br>import java.security.cert.CertificateFactory;<br>import java.security.cert.X509Certificate;<br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br>import java.util.stream.Collectors;</pre><pre>import javax.net.ssl.TrustManagerFactory;</pre><pre>import org.apache.poi.xwpf.usermodel.XWPFDocument;<br>import org.apache.poi.xwpf.usermodel.XWPFParagraph;<br>import org.apache.poi.ss.usermodel.*;<br>import org.apache.poi.xssf.usermodel.XSSFWorkbook;</pre><pre>import com.azure.ai.openai.OpenAIClientBuilder;<br>import com.azure.core.http.HttpClient;<br>import com.azure.core.http.HttpPipelineBuilder;<br>import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;</pre><pre>import io.netty.handler.ssl.SslContext;<br>import io.netty.handler.ssl.SslContextBuilder;<br>import io.netty.handler.ssl.SslProvider;<br>import io.netty.handler.ssl.util.InsecureTrustManagerFactory;<br></pre><pre>@Autowired<br>private AzureOpenAiEmbeddingModel embedModel;  <br> <br>/**<br> * Processes an Excel sheet to extract questions and answers.<br> *<br> * This method reads data from the first sheet of an Excel file and organizes it into two lists:<br> * one for questions and one for answers. Each row of the Excel sheet is expected to have<br> * the question in the first cell and the answer in the second cell. The processed data is<br> * returned as a map with two keys: &quot;question&quot; and &quot;answer&quot;.<br> *<br> * @return a map containing two lists:<br> *         - &quot;question&quot;: A list of questions extracted from the Excel sheet.<br> *         - &quot;answer&quot;: A list of answers corresponding to the questions.<br> * @throws RuntimeException if an I/O error occurs while reading the Excel file.<br> */<br>public Map&lt;String, List&lt;String&gt;&gt; processExcelSheet() {<br>    // Initialize lists to store questions and answers<br>    List&lt;String&gt; questions = new ArrayList&lt;&gt;();<br>    List&lt;String&gt; answers = new ArrayList&lt;&gt;();<br>     <br>    // Map to store processed data<br>    Map&lt;String, List&lt;String&gt;&gt; processedData = new HashMap&lt;&gt;();<br> <br>    // Try-with-resources block to ensure resources are closed after use<br>    try (FileInputStream fis = new FileInputStream(new File(&quot;Excel file path&quot;)); // Replace &quot;Excel file path&quot; with the actual path to the Excel file<br>         Workbook workbook = new XSSFWorkbook(fis)) { // Create a workbook instance for the Excel file<br>          <br>        // Get the first sheet of the workbook (index 0)<br>        Sheet sheet = workbook.getSheetAt(0);<br>         <br>        // Iterate through each row of the sheet<br>        for (Row row : sheet) {<br>            int i = 0; // Initialize column index<br>            // Iterate through each cell in the row<br>            for (Cell cell : row) {<br>                if (i == 0) {<br>                    // Add the value of the first column (question) to the questions list<br>                    questions.add(cell.getStringCellValue());<br>                } else {<br>                    // Add the value of the second column (answer) to the answers list<br>                    answers.add(cell.getStringCellValue());<br>                }<br>                i++; // Increment the column index<br>            }<br>        }<br>    } catch (IOException e) {<br>        // Catch and print any I/O exceptions that occur during file reading<br>        e.printStackTrace();<br>    }<br> <br>    // Add the lists of questions and answers to the map<br>    processedData.put(&quot;question&quot;, questions);<br>    processedData.put(&quot;answer&quot;, answers);<br> <br>    // Return the processed map<br>    return processedData;<br>}  <br> <br>/**<br> * Inserts embeddings and their associated tokens into a Milvus collection.<br> *<br> * The method performs the following steps:<br> * 1. Prepares the data to be inserted, including embeddings and tokens.<br> * 2. Drops the collection if it already exists.<br> * 3. Defines a schema for the collection, including fields for embeddings and tokens.<br> * 4. Creates a new Milvus collection with the defined schema.<br> * 5. Creates an index on the vector field for efficient similarity searches.<br> * 6. Inserts the embeddings and tokens into the collection.<br> *<br> * @param embeddingsList A list of embeddings (each embedding is a list of floats).<br> * @param tokens A list of tokens corresponding to the embeddings.<br> */<br>public void insertEmbeddingsToMilvus(List&lt;List&lt;Float&gt;&gt; embeddingsList, List&lt;String&gt; tokens) {<br>    // Step 1: Prepare data for insertion<br>    List&lt;Field&gt; allFields = new ArrayList&lt;&gt;();<br>    allFields.add(new Field(&quot;vector_field&quot;, embeddingsList)); // Add the vector embeddings to the &quot;vector_field&quot;<br>    allFields.add(new Field(&quot;description&quot;, tokens));         // Add the tokens to the &quot;description&quot; field<br> <br>    // Create an InsertParam object with the collection name and fields<br>    InsertParam insertParam = InsertParam.newBuilder()<br>            .withCollectionName(collectionName)<br>            .withFields(allFields)<br>            .build();<br> <br>    // Step 2: Drop the collection if it exists<br>    try {<br>        // Attempt to drop the existing collection<br>        milvusClient.dropCollection(DropCollectionParam.newBuilder()<br>                .withCollectionName(collectionName)<br>                .build());<br> <br>        System.out.println(&quot;Collection &#39;&quot; + collectionName + &quot;&#39; deleted successfully.&quot;);<br>    } catch (Exception e) {<br>        // Handle cases where the collection does not exist or other errors occur<br>        System.err.println(&quot;Failed to delete collection: &quot; + e.getMessage());<br>    }<br> <br>    // Step 3: Define the schema for the collection<br>    List&lt;FieldType&gt; fields = new ArrayList&lt;&gt;();<br>    fields.add(FieldType.newBuilder()<br>            .withName(&quot;id&quot;) // Primary key field<br>            .withDescription(&quot;Primary key&quot;)<br>            .withDataType(DataType.Int64)<br>            .withPrimaryKey(true)<br>            .withAutoID(true) // Auto-generate IDs for this field<br>            .build());<br>    fields.add(FieldType.newBuilder()<br>            .withName(&quot;description&quot;) // Field for tokens<br>            .withDescription(&quot;tokens&quot;)<br>            .withDataType(DataType.VarChar)<br>            .withMaxLength(2000) // Maximum length for the tokens<br>            .build());<br>    fields.add(FieldType.newBuilder()<br>            .withName(&quot;vector_field&quot;) // Field for vector embeddings<br>            .withDescription(&quot;Vector embeddings&quot;)<br>            .withDataType(DataType.FloatVector)<br>            .withDimension(embeddingsList.get(0).size()) // Set the dimension based on the first embedding&#39;s size<br>            .build());<br> <br>    // Step 4: Create the collection with the defined schema<br>    CreateCollectionParam createCollectionParam = CreateCollectionParam.newBuilder()<br>            .withCollectionName(collectionName)<br>            .withDescription(&quot;Collection for storing given embeddings&quot;)<br>            .withFieldTypes(fields)<br>            .build();<br>    milvusClient.createCollection(createCollectionParam);<br>    // Step 5: Create an index on the vector field<br>    R&lt;RpcStatus&gt; response = milvusClient.createIndex(CreateIndexParam.newBuilder()<br>            .withCollectionName(collectionName)<br>            .withFieldName(&quot;vector_field&quot;)<br>            .withIndexType(IndexType.IVF_FLAT) // Use IVF_FLAT index type for the vector field<br>            .withMetricType(MetricType.L2)    // Metric type for similarity search (e.g., L2, IP, COSINE)<br>            .build());<br>    System.out.println(response.getStatus()); // Print the status of the index creation<br>    // Step 6: Insert data into the collection<br>    milvusClient.insert(insertParam);<br>}<br> <br> <br>/**<br> * REST API endpoint to process an Excel sheet, generate embeddings for the data, and insert the results into Milvus.<br> *<br> * This method performs the following steps:<br> * 1. Reads an Excel sheet to extract data (questions and answers).<br> * 2. Generates embeddings for the extracted questions using an embedding model.<br> * 3. Initializes a Milvus client for database operations.<br> * 4. Inserts the generated embeddings and their corresponding answers into a Milvus collection.<br> *<br> * @return A success message with the count of embeddings inserted into the database.<br> */<br>@GetMapping(value = &quot;/embedding_xls&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>public String embedding_xls() {<br>    // Step 1: Initialize the embeddings list<br>    List&lt;List&lt;Float&gt;&gt; embeddingsList = new ArrayList&lt;&gt;();<br> <br>    // Step 2: Process the Excel sheet to extract questions and answers<br>    Map&lt;String, List&lt;String&gt;&gt; processedData = processExcelSheet();<br>    List&lt;String&gt; allToken = processedData.get(&quot;question&quot;); // Extract the list of questions<br> <br>    // Step 3: Generate embeddings for the questions<br>    EmbeddingResponse embeddingResponse = embedModel.embedForResponse(allToken); // Generate embeddings using the model<br>    List&lt;Embedding&gt; allEmbeddings = embeddingResponse.getResults();<br> <br>    // Step 4: Convert each embedding&#39;s output to a list of floats<br>    for (Embedding embedding : allEmbeddings) {<br>        List&lt;Float&gt; result = new ArrayList&lt;&gt;(embedding.getOutput().length);<br>        for (float f : embedding.getOutput()) {<br>            result.add(f);<br>        }<br>        embeddingsList.add(result); // Add each embedding to the embeddings list<br>    }<br> <br>    // Step 5: Initialize the Milvus client<br>    intializeMilvus();<br> <br>    // Step 6: Insert the embeddings and corresponding answers into Milvus<br>    insertEmbeddingsToMilvus(embeddingsList, processedData.get(&quot;answer&quot;));<br> <br>    // Step 7: Return a success message with the count of inserted embeddings<br>    return &quot;Successfully inserted : &quot; + embeddingsList.size();<br>}</pre><p><strong>Step 7:</strong> Create a AzureOpenAiChatModel bean using OpenAIClientBuilder</p><pre>/**<br> * Configures and provides a Spring-managed bean for the Azure OpenAI Chat Model.<br> *<br> * This method creates an instance of the `AzureOpenAiChatModel` with the following configuration:<br> * 1. Utilizes a custom OpenAI client builder for connecting to Azure OpenAI services.<br> * 2. Sets default options for the chat model, including deployment name, maximum tokens, and temperature.<br> * 3. Registers the configured `AzureOpenAiChatModel` instance as a Spring-managed bean.<br> *<br> * @return an initialized and configured instance of `AzureOpenAiChatModel`.<br> */<br>@Bean<br>public AzureOpenAiChatModel azureOpenAiChatModel() {<br>    return AzureOpenAiChatModel.builder()<br>            // Step 1: Set the OpenAI client builder<br>            .openAIClientBuilder(CommonUtil.getBuilder()) // Retrieves a pre-configured OpenAI client builder<br>             <br>            // Step 2: Configure default options for the chat model<br>            .defaultOptions(AzureOpenAiChatOptions.builder()<br>                    .deploymentName(&quot;gpt-4o&quot;) // Specify the deployment name for the model (e.g., &quot;gpt-4o&quot;)<br>                    .maxTokens(1000)         // Set the maximum number of tokens for responses<br>                    .temperature(0.1)       // Set the temperature for response creativity (lower values = more deterministic)<br>                    .build())<br>             <br>            // Step 3: Build the Azure OpenAI Chat Model instance<br>            .build();<br>}</pre><p><strong>Step 8:</strong> Initiating a Chat Using AzureOpenAiChatModel. The following steps outline the chat process leveraging the AzureOpenAiChatModel:</p><ol><li>Capture User Input: Retrieve the user’s input from the UI chat interface.</li><li>Generate Embeddings: Use the AzureOpenAiEmbeddingModel object to create embeddings for the user input.</li><li>Search in Milvus Database: Query the Milvus database using the generated embeddings to find the top matching results.</li><li>Analyze Search Results: Extract the results from Milvus, which include similarity scores for the matched entries.</li><li>Prepare and Interact with LLM: Construct a UserMessage using the user prompt and the retrieved information. Send this message to the Large Language Model (LLM) for an enhanced and contextually refined response.</li></ol><pre>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.Map;</pre><pre>import org.springframework.ai.azure.openai.AzureOpenAiChatModel;<br>import org.springframework.ai.azure.openai.AzureOpenAiEmbeddingModel;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.MediaType;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br></pre><pre>import org.springframework.ai.chat.messages.SystemMessage;<br>import org.springframework.ai.chat.messages.UserMessage;<br>import org.springframework.ai.chat.model.ChatResponse;<br>import org.springframework.ai.chat.prompt.Prompt;<br>import org.springframework.ai.embedding.Embedding;<br>import org.springframework.ai.embedding.EmbeddingResponse;<br></pre><pre>@Autowired<br>private AzureOpenAiChatModel chatModel;  <br>@Autowired<br>private AzureOpenAiEmbeddingModel embedModel;<br>/**<br> * REST API endpoint to process a query, search for relevant embeddings, and generate a chat response.<br> *<br> * This method performs the following steps:<br> * 1. Generates an embedding for the user-provided query text using an embedding model.<br> * 2. Searches the Milvus database for embeddings similar to the query embedding.<br> * 3. Constructs a chat prompt using the search results and a system message.<br> * 4. Sends the prompt to the chat model to generate a reply.<br> * 5. Returns the AI-generated response as a JSON string.<br> *<br> * @param queryText The user-provided query text for which a response is generated.<br> * @return A JSON string containing the AI-generated response.<br> */<br>@GetMapping(value = &quot;/getChatResponse&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>public String getChatReply(@RequestParam(&quot;text&quot;) String queryText) {<br>    // Step 1: Generate an embedding for the query text<br>    EmbeddingResponse embeddingResponse = embedModel.embedForResponse(List.of(queryText)); // Generate embedding<br>    float[] embedding = embeddingResponse.getResult().getOutput(); // Retrieve embedding as a float array<br> <br>    // Convert the embedding float array into a List&lt;Float&gt;<br>    List&lt;Float&gt; result = new ArrayList&lt;&gt;(embedding.length);<br>    for (float f : embedding) {<br>        result.add(f);<br>    }<br> <br>    // Step 2: Initialize the Milvus client<br>    milvusUtil.intializeMilvus();<br> <br>    // Step 3: Search for similar embeddings in the Milvus database<br>    String userMessageStr = searchEmbeddingsInMilvus(result, 4); // Retrieve top 4 matches from Milvus<br> <br>    // Step 4: Construct the chat prompt<br>    UserMessage userMessage = new UserMessage(userMessageStr); // Create a UserMessage with the search results<br>    SystemMessage systemMessage = new SystemMessage(&quot;You are an AI assistant.&quot;); // Provide a system message<br>    Prompt prompt = new Prompt(List.of(userMessage, systemMessage)); // Combine the messages into a Prompt object<br> <br>    // Step 5: Send the prompt to the chat model and retrieve the response<br>    ChatResponse response = this.chatModel.call(prompt); // Generate the chat model&#39;s response<br>    String res = response.getResult().getOutput().getText(); // Extract the text content from the response<br> <br>    // Step 6: Return the AI-generated response<br>    return res;<br>}<br> <br>/**<br> * Searches for similar embeddings in a Milvus collection and retrieves the top matches.<br> *<br> * This method performs the following steps:<br> * 1. Configures the search parameters for querying Milvus (e.g., collection name, query embeddings, metric type).<br> * 2. Loads the specified collection into memory for querying.<br> * 3. Executes the search query in Milvus and retrieves the results.<br> * 4. Extracts descriptions and similarity scores from the search results.<br> * 5. Formats the results into a readable string containing the top matches and their scores.<br> *<br> * @param queryEmbeddings A list of floats representing the query embedding vector.<br> * @param topK The number of top matches to retrieve from Milvus.<br> * @return A formatted string containing the top matches and their similarity scores, along with a prompt for analysis.<br> */<br>public String searchEmbeddingsInMilvus(List&lt;Float&gt; queryEmbeddings, int topK) {<br>    // Step 1: Configure the search parameters<br>    SearchParam searchParam = SearchParam.newBuilder()<br>            .withCollectionName(collectionName)     // Specify the collection name in Milvus<br>            .withVectors(List.of(queryEmbeddings))  // Provide the query embeddings as input<br>            .withVectorFieldName(&quot;vector_field&quot;)    // Specify the vector field name in the collection<br>            .withMetricType(MetricType.L2)          // Use L2 (Euclidean distance) as the similarity metric<br>            .withTopK(topK)                         // Specify the number of top matches to retrieve<br>            .addOutField(&quot;description&quot;)             // Include the &quot;description&quot; field in the output<br>            .build();<br> <br>    // Step 2: Load the collection into memory to prepare it for querying<br>    R&lt;RpcStatus&gt; loadStatus = milvusClient.loadCollection(<br>            LoadCollectionParam.newBuilder()<br>                    .withCollectionName(collectionName) // Load the specified collection<br>                    .build()<br>    );<br>    System.out.println(loadStatus.getStatus()); // Print the status of the load operation<br> <br>    // Step 3: Perform the search query in Milvus<br>    R&lt;SearchResults&gt; response = milvusClient.search(searchParam);<br>    SearchResults searchResults = response.getData();<br> <br>    // Step 4: Wrap the search results for easy access to fields and scores<br>    SearchResultsWrapper resultsWrapper = new SearchResultsWrapper(searchResults.getResults());<br> <br>    // Extract the descriptions of the matches from the &quot;description&quot; field<br>    List&lt;String&gt; descriptionList = (List&lt;String&gt;) resultsWrapper.getFieldData(&quot;description&quot;, 0);<br> <br>    // Extract the similarity scores for the matches<br>    List&lt;IDScore&gt; idScoreList = resultsWrapper.getIDScore(0);<br> <br>    // Step 5: Format the results into a readable string<br>    StringBuilder builder = new StringBuilder();<br>    int count = 0;<br>    for (IDScore idScore : idScoreList) {<br>        builder.append(String.format(&quot;%s, Score: %.4f&quot;,<br>                descriptionList.get(count++),       // Retrieve the description for the current result<br>                idScore.getScore()                  // Retrieve the similarity score<br>        ));<br>        builder.append(&quot;\n&quot;);<br>    }<br> <br>    // Print the list of descriptions for debugging purposes<br>    System.out.println(descriptionList);<br> <br>    // Return the formatted string containing the search results and a prompt for analysis<br>    return String.format(<br>            &quot;Based on the search results, the top matches are:\n%s\n\n&quot; +<br>                    &quot;Can you analyze and provide meaningful insights?&quot;,<br>            builder.toString()<br>    );<br>}</pre><p><strong>Step 9:</strong> Render the response in chat UI -</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br> <br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Full-Screen Chat&lt;/title&gt;<br>    &lt;style&gt;<br>        * {<br>            margin: 0;<br>            padding: 0;<br>            box-sizing: border-box;<br>        }<br> <br>        body {<br>            font-family: Arial, sans-serif;<br>            height: 100vh;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            background-color: #f4f4f9;<br>        }<br> <br>        #chat-container {<br>            width: 100%;<br>            height: 100%;<br>            display: flex;<br>            flex-direction: column;<br>            background: #ffffff;<br>        }<br> <br>        #chat-header {<br>            padding: 15px;<br>            background-color: #007bff;<br>            color: white;<br>            text-align: center;<br>            font-size: 18px;<br>            font-weight: bold;<br>        }<br> <br>        #chat-messages {<br>            flex: 1;<br>            padding: 10px;<br>            overflow-y: auto;<br>            border-top: 1px solid #ddd;<br>            border-bottom: 1px solid #ddd;<br>        }<br> <br>        .message-container {<br>            display: flex;<br>            align-items: flex-start;<br>            margin-bottom: 10px;<br>        }<br> <br>        .message-container.user {<br>            justify-content: flex-end;<br>        }<br> <br>        .message-container.bot {<br>            justify-content: flex-start;<br>        }<br> <br>        .avatar {<br>            width: 40px;<br>            height: 40px;<br>            border-radius: 50%;<br>            background-color: #ddd;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            font-weight: bold;<br>            color: white;<br>            margin: 0 10px;<br>        }<br> <br>        .avatar.user {<br>            background-color: #007bff;<br>        }<br> <br>        .avatar.bot {<br>            background-color: #ff5c5c;<br>        }<br> <br>        .message {<br>            max-width: 70%;<br>            padding: 10px;<br>            border-radius: 10px;<br>            font-size: 14px;<br>            line-height: 1.5;<br>        }<br> <br>        .message.user {<br>            background: #e9f5ff;<br>            color: #007bff;<br>            border-radius: 10px 10px 0 10px;<br>        }<br> <br>        .message.bot {<br>            background: #007bff;<br>            color: white;<br>            border-radius: 10px 10px 10px 0;<br>        }<br> <br>        #chat-input {<br>            display: flex;<br>            padding: 10px;<br>            background-color: #f9f9f9;<br>            border-top: 1px solid #ddd;<br>        }<br> <br>        #chat-input input {<br>            flex: 1;<br>            border: 1px solid #ddd;<br>            border-radius: 4px;<br>            padding: 10px;<br>            font-size: 16px;<br>        }<br> <br>        #chat-input button {<br>            margin-left: 10px;<br>            background-color: #007bff;<br>            color: #fff;<br>            border: none;<br>            border-radius: 4px;<br>            padding: 10px 15px;<br>            font-size: 16px;<br>            cursor: pointer;<br>        }<br> <br>        #chat-input button:hover {<br>            background-color: #0056b3;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br> <br>&lt;body&gt;<br>    &lt;div id=&quot;chat-container&quot;&gt;<br>        &lt;div id=&quot;chat-header&quot;&gt;DCSP bot&lt;/div&gt;<br>        &lt;div id=&quot;chat-messages&quot;&gt;&lt;/div&gt;<br>        &lt;div id=&quot;chat-input&quot;&gt;<br>            &lt;input type=&quot;text&quot; id=&quot;message-input&quot; placeholder=&quot;Type your message...&quot; /&gt;<br>            &lt;button id=&quot;send-button&quot;&gt;Send&lt;/button&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br> <br>    &lt;script&gt;<br>        const chatMessages = document.getElementById(&#39;chat-messages&#39;);<br>        const messageInput = document.getElementById(&#39;message-input&#39;);<br>        const sendButton = document.getElementById(&#39;send-button&#39;);<br> <br>        // Function to format the response before rendering<br>        function formatResponse(content) {<br>            // Example: Parse JSON and format it with indentation<br>            try {<br>                const jsonObject = JSON.parse(content); // Parse JSON string into an object<br>                return JSON.stringify(jsonObject, null, 2) // Format JSON with 2 spaces for indentation<br>                    .replace(/ /g, &#39; &#39;) // Replace spaces with HTML non-breaking spaces<br>                    .replace(/\n/g, &#39;&lt;br&gt;&#39;); // Replace newlines with &lt;br&gt; for HTML rendering<br>            } catch (error) {<br>                // If content is not JSON, return as-is<br>                return content<br>                    .replace(/\n/g, &#39;&lt;br&gt;&#39;) // Replace newlines with &lt;br&gt;<br>                    .trim(); // Remove extra whitespace<br>            }<br>        }<br> <br>        // Function to append messages to the chat<br>        function appendMessage(content, type, tempId = null) {<br>            const containerDiv = document.createElement(&#39;div&#39;);<br>            containerDiv.classList.add(&#39;message-container&#39;, type);<br> <br>            if (tempId) containerDiv.id = tempId; // Assign an ID for later replacement<br> <br>            const avatarDiv = document.createElement(&#39;div&#39;);<br>            avatarDiv.classList.add(&#39;avatar&#39;, type);<br>            avatarDiv.textContent = type === &#39;user&#39; ? &#39;U&#39; : &#39;B&#39;; // &quot;U&quot; for User, &quot;B&quot; for Bot<br> <br>            const messageDiv = document.createElement(&#39;div&#39;);<br>            messageDiv.classList.add(&#39;message&#39;, type);<br>            messageDiv.innerHTML = content;<br> <br>            containerDiv.appendChild(type === &#39;user&#39; ? messageDiv : avatarDiv);<br>            containerDiv.appendChild(type === &#39;user&#39; ? avatarDiv : messageDiv);<br> <br>            chatMessages.appendChild(containerDiv);<br>            chatMessages.scrollTop = chatMessages.scrollHeight; // Auto-scroll to the bottom<br>        }<br>        function updateMessage(tempId, content) {<br>            const containerDiv = document.getElementById(tempId);<br>            if (containerDiv) {<br>                const messageDiv = containerDiv.querySelector(&#39;.message&#39;);<br>                if (messageDiv) {<br>                    messageDiv.innerHTML = content;<br>                }<br>            }<br>        }<br> <br>        // Function to handle sending messages<br>        async function sendMessage() {<br>            const userMessage = messageInput.value.trim();<br>            if (!userMessage) return;<br> <br>            appendMessage(userMessage, &#39;user&#39;); // Display user&#39;s message<br>            messageInput.value = &#39;&#39;; // Clear input field<br> <br>            const tempId = `temp-${Date.now()}`;<br>            appendMessage(&#39;&lt;span class=&quot;typing-indicator&quot;&gt;Planning response...&lt;/span&gt;&#39;, &#39;bot&#39;, tempId);<br> <br>            try {<br>                // Call the GET API to fetch the bot&#39;s response<br>                const response = await fetch(`http://localhost:8080/getChatResponse?text=${encodeURIComponent(userMessage)}`);<br>                if (!response.ok) throw new Error(&#39;Failed to fetch response&#39;);<br> <br>                const data = await response.json();<br>                const formattedResponse = formatResponse(data.response);<br>                updateMessage(tempId, formattedResponse);<br>            } catch (error) {<br>                updateMessage(tempId, &#39;Error: Unable to connect to server&#39;);<br>            }<br>        }<br> <br>        // Add event listeners for send button and Enter key<br>        sendButton.addEventListener(&#39;click&#39;, sendMessage);<br>        messageInput.addEventListener(&#39;keypress&#39;, (event) =&gt; {<br>            if (event.key === &#39;Enter&#39;) sendMessage();<br>        });<br>    &lt;/script&gt;<br>&lt;/body&gt;<br> <br>&lt;/html&gt;</pre><p><strong>Step 9:</strong> Chat output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0He1D3PKc5KO-H41BlNug.png" /></figure><p>In this blog, we explore the process of creating an intelligent chatbot by leveraging the power of Spring AI and Milvus, a vector database for similarity search. The guide walks you through a hands-on approach to building a scalable, efficient, and intelligent chatbot capable of understanding and responding to user queries with context-aware insights.</p><h3>Key Highlights:</h3><ul><li><strong>Integration with Spring AI:</strong> Learn how to configure and use Spring AI for embedding generation and conversational AI capabilities.</li><li><strong>Milvus for Vector Search: </strong>Discover how Milvus enables similarity-based searches by storing and retrieving vector embeddings efficiently.</li><li><strong>End-to-End Implementation:</strong> From embedding generation to Milvus integration and chatbot response handling, the blog provides a step-by-step guide to building the entire system.</li></ul><p>Whether you’re a developer looking to enhance your chatbot’s intelligence or someone curious about integrating vector search with conversational AI, this guide provides practical insights and actionable steps to help you get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a1b6ccfc0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/building-an-intelligent-chatbot-with-spring-ai-and-milvus-a-hands-on-guide-new-21a1b6ccfc0f">Building an Intelligent Chatbot with Spring AI and Milvus: A Hands-On Guide — new</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>