<?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 Marouane Lasmak on Medium]]></title>
        <description><![CDATA[Stories by Marouane Lasmak on Medium]]></description>
        <link>https://medium.com/@marouane.lasmak?source=rss-622e237d5f1a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G7-qeP3sbsqCL0Ysd8BrIw.jpeg</url>
            <title>Stories by Marouane Lasmak on Medium</title>
            <link>https://medium.com/@marouane.lasmak?source=rss-622e237d5f1a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:18:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marouane.lasmak/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[Building a Multimodal RAG System for PDF Files with Langchain4j, Gemini, and Hugging Face]]></title>
            <link>https://medium.com/@marouane.lasmak/building-a-multimodal-rag-system-for-pdf-files-with-langchain4j-gemini-and-hugging-face-399be16250cf?source=rss-622e237d5f1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/399be16250cf</guid>
            <dc:creator><![CDATA[Marouane Lasmak]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 21:58:40 GMT</pubDate>
            <atom:updated>2025-02-10T21:58:40.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*l9kRQhv2c0A55pspd-d7-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*TC0Nq2njOcIasmnCSv5ZYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*we1TqAoPYsaOF2U-FQU6LA.png" /></figure><h3>Introduction :</h3><p>In this article, we will walk through a Java-based application that processes PDF documents, extracts both text and images, generates image descriptions using an LLM (Gemini), and indexes the content with embeddings (via Hugging Face) to enable retrieval-augmented generation (RAG). We use <strong>Langchain4j</strong> to tie all these pieces together in a Spring Boot application.</p><p>The system leverages the following core features:</p><ul><li><strong>PDF Processing:</strong> Using Apache PDFBox to parse PDFs and extract text and images.</li><li><strong>Multimodal Interaction:</strong> Combining text and images into a single document. For each image, we generate a description using the Gemini language model.</li><li><strong>Embedding Ingestion:</strong> Using Hugging Face’s embedding model to create vector representations of text segments, enabling efficient similarity search.</li><li><strong>Chat Memory Management:</strong> Storing chat history and vector representations of text segments.</li><li><strong>Reactive Chat Interface:</strong> Leveraging a reactive service to interact with users in real time.</li></ul><p>Below, we explain the main configurations and code components.</p><h3>Prerequisites</h3><p>Before running the application, ensure you have the following installed:</p><ul><li><strong>Java 17 or higher</strong></li><li><strong>Maven</strong></li><li><strong>Docker</strong></li></ul><p>You also need to define your API keys in your application.properties (or .yml) file:</p><pre>GEMINI_API_KEY=your_gemini_api_key_here<br>HF_API_KEY=your_huggingface_api_key_here</pre><p><a href="https://ai.google.dev/gemini-api/docs/api-key">Tap here to get a Gemini API Key</a></p><p><a href="https://huggingface.co/docs/hub/security-tokens">How to get a Hugging Face Access Token</a></p><h3>Docker Environment</h3><p>Create a docker-compose.yml in your project root :</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  postgres:<br>    image: ankane/pgvector:latest<br>    ports:<br>      - &quot;5432:5432&quot;<br>    environment:<br>      POSTGRES_DB: postgres<br>      POSTGRES_USER: my_user<br>      POSTGRES_PASSWORD: my_password<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U my_user -d postgres&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br><br>volumes:<br>  postgres_data:</pre><h3>Project Setup</h3><h3>Dependencies</h3><p>Create a new Spring Boot project and add these dependencies to your pom.xml:</p><pre> &lt;dependencies&gt;<br><br>    &lt;!-- Provides essential dependencies for building web applications with Spring Boot (REST, servlets, etc.). --&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><br>    &lt;!-- Integrates Google&#39;s Gemini AI model for synchronous and streaming chat functionalities. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-google-ai-gemini&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Supports storing and searching embeddings in PostgreSQL using the PgVector extension. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-pgvector&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Uses Apache PDFBox to parse PDF documents for extracting text and images. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-document-parser-apache-pdfbox&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Connects to Hugging Face&#39;s API to generate text embeddings for semantic search and RAG. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-hugging-face&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Enables integration with Docker Compose for managing containerized services in a Spring Boot environment. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-docker-compose&lt;/artifactId&gt;<br>        &lt;scope&gt;runtime&lt;/scope&gt;<br>        &lt;optional&gt;true&lt;/optional&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Simplifies the configuration and integration of Langchain4j within a Spring Boot application. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-spring-boot-starter&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Adds support for reactive programming with Project Reactor for non-blocking, asynchronous operations. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-reactor&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>&lt;/dependencies&gt;</pre><h3>Memory and Embedding Store Configuration</h3><p>Before setting up the Gemini-based LLM services, we configure the beans responsible for maintaining chat history and for managing the embedding store. This configuration helps preserve the semantic context from previous interactions and supports robust document indexing.</p><pre>@Configuration<br>public class MemoConfig {<br>    private EmbeddingModel embeddingModel;<br><br>    public MemoConfig(EmbeddingModel embeddingModel) {<br>        this.embeddingModel = embeddingModel;<br>    }<br><br>    @Bean<br>    public ChatMemoryProvider chatMemoryProvider() {<br>        return chatId -&gt; MessageWindowChatMemory.withMaxMessages(10);<br>    }<br><br>    @Bean<br>    public EmbeddingStore&lt;TextSegment&gt; embeddingStore() {<br>        return PgVectorEmbeddingStore.builder()<br>                .host(&quot;localhost&quot;)<br>                .port(5432)<br>                .database(&quot;postgres&quot;)<br>                .user(&quot;my_user&quot;)<br>                .password(&quot;my_password&quot;)<br>                .table(&quot;my_embeddings&quot;)<br>                .dimension(embeddingModel.dimension())<br>                .createTable(true)<br>                .build();<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li><strong>ChatMemoryProvider:</strong><br>This helps the system remember recent interactions and maintain context.</li><li><strong>EmbeddingStore:</strong><br>Here, we set up an embedding store using the PgVector extension, which will hold the vector representations (embeddings) of text segments. This allows for efficient similarity searches during retrieval.</li></ul><h3><strong>Embedding Configuration</strong></h3><pre>@Configuration<br>public class EmbeddingConfig {<br><br>    /**<br>     * Creates an EmbeddingStoreIngestor bean.<br>     * This component is responsible for splitting documents into manageable segments,<br>     * generating embeddings for each segment using the Hugging Face model, and ingesting<br>     * these embeddings into the embedding store.<br>     */<br>    @Bean<br>    public EmbeddingStoreIngestor embeddingStoreIngestor(EmbeddingModel embeddingModel,<br>                                                         EmbeddingStore&lt;TextSegment&gt; embeddingStore) {<br>        return EmbeddingStoreIngestor.builder()<br>                .documentSplitter(DocumentSplitters.recursive(1000, 100))<br>                .embeddingModel(embeddingModel)<br>                .embeddingStore(embeddingStore)<br>                .build();<br>    }<br><br>    /**<br>     * Sets up an EmbeddingStoreContentRetriever bean.<br>     * This bean retrieves relevant text segments based on semantic similarity.<br>     * It uses the embedding store and the Hugging Face embedding model for computing similarity.<br>     */<br>    @Bean<br>    public EmbeddingStoreContentRetriever embeddingStoreContentRetriever(EmbeddingStore&lt;TextSegment&gt; embeddingStore,<br>                                                                          EmbeddingModel embeddingModel) {<br>        return EmbeddingStoreContentRetriever.builder()<br>                .embeddingStore(embeddingStore)<br>                .embeddingModel(embeddingModel)<br>                .maxResults(3)<br>                .minScore(0.6)<br>                .build();<br>    }<br>}</pre><h3>Configuration with Gemini and Hugging Face</h3><p>The configuration class sets up the beans required for interacting with the Gemini LLM and Hugging Face’s embedding service. Below is the annotated code with comments:</p><pre>@Configuration<br>public class GeminiConfig {<br><br>    // The Gemini API key is injected from application properties<br>    @Value(&quot;${GEMINI_API_KEY}&quot;)<br>    private String apiKey;<br><br>    // Hugging Face API key for embedding generation<br>    @Value(&quot;${HF_API_KEY}&quot;)<br>    private String HF_API_KEY;<br><br>    /**<br>     * Configures a synchronous chat model using Google AI Gemini.<br>     */<br>    @Bean<br>    public ChatLanguageModel chatGeminiLanguageModel() {<br>        return GoogleAiGeminiChatModel.builder()<br>                .apiKey(apiKey) // Set the API key for authentication<br>                .modelName(&quot;gemini-1.5-flash&quot;)<br>                .temperature(0.0) // Deterministic output<br>                .topP(0.95)<br>                .topK(64)<br>                .maxOutputTokens(8192)<br>                .timeout(ofSeconds(60))<br>                .logRequestsAndResponses(true)<br>                .build();<br>    }<br><br>    /**<br>     * Configures a streaming version of the Gemini chat model.<br>     */<br>    @Bean<br>    public StreamingChatLanguageModel streamingGeminiChatLanguageModel() {<br>        return GoogleAiGeminiStreamingChatModel.builder()<br>                .apiKey(apiKey)<br>                .modelName(&quot;gemini-1.5-flash&quot;)<br>                .temperature(0.0)<br>                .topP(0.95)<br>                .topK(64)<br>                .maxOutputTokens(8192)<br>                .timeout(ofSeconds(60))<br>                .logRequestsAndResponses(true)<br>                .build();<br>    }<br><br>    /**<br>     * Sets up the Hugging Face embedding model.<br>     */<br>    @Bean<br>    public EmbeddingModel embeddingModel() {<br>        return HuggingFaceEmbeddingModel.builder()<br>                .accessToken(HF_API_KEY)<br>                .modelId(&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>                .waitForModel(true)<br>                .timeout(ofSeconds(60))<br>                .build();<br>    }<br>}</pre><h3>Explanation</h3><ul><li><strong>Gemini Beans:</strong><br>Two beans are created — one for synchronous and one for streaming chat interactions. Both use the same configuration (model name, temperature, etc.), ensuring consistent responses.</li><li><strong>Hugging Face Embedding Bean:</strong><br>The embedding model is configured to use the &quot;sentence-transformers/all-MiniLM-L6-v2&quot; model. This model converts text into embeddings (vector representations) which can later be used for similarity search and retrieval.</li></ul><h3>The AI Chat Service</h3><p>This service defines the interface for our chat interaction. The system message in the annotation instructs the AI on how to respond to user inputs.</p><pre>@AiService<br>public interface AiChatService {<br><br>    @SystemMessage(&quot;&quot;&quot;<br>            You are an AI Agent, responsible for chatting with users.<br>            Users upload documents in different formats, and it is processed by the system.<br>            You are responsible for chatting with the user and providing responses.<br>            Your responses should be based on data sent in this prompt that is extracted from the documents.<br>            Ensure that you respond with the same language as the user.<br>            &quot;&quot;&quot;)<br>    Flux&lt;String&gt; chat(String message);<br>}</pre><h3>Explanation</h3><ul><li><strong>@AiService Annotation:</strong><br>Marks the interface as a service for AI interactions, Spring automatically injects the necessary dependencies. In this case, it means that the pre-configured beans (chatGeminiLanguageModel, streamingGeminiChatLanguageModel,embeddingStoreIngestor, embeddingStoreContentRetriever, and embeddingModel) are automatically provided, without requiring manual instantiation.</li><li><strong>System Message:</strong><br>Provides context to the AI so that it can generate responses based on the uploaded document’s content and maintain the language consistency with the user.</li></ul><h3>The RAG Service: Processing and Ingestion</h3><p>The RagService class handles the core logic of processing PDF files, extracting multimodal segments (text and images), and ingesting the results into an embedding store.</p><p><strong>Processing the PDF Document</strong></p><pre>@Service<br>public class RagService {<br><br>    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // Maximum file size (10 MB)<br>    private static final String UPLOAD_DIR = &quot;src/main/resources/docs&quot;;<br>    private static final Logger log = LoggerFactory.getLogger(RagService.class);<br><br>    private EmbeddingStoreIngestor embeddingStoreIngestor;<br>    private EmbeddingStore&lt;TextSegment&gt; embeddingStore;<br>    private ChatLanguageModel chatLanguageModel;<br><br>    public RagService(EmbeddingStoreIngestor embeddingStoreIngestor,<br>                      EmbeddingStore&lt;TextSegment&gt; embeddingStore,<br>                      ChatLanguageModel chatLanguageModel) {<br>        this.embeddingStoreIngestor = embeddingStoreIngestor;<br>        this.embeddingStore = embeddingStore;<br>        this.chatLanguageModel = chatLanguageModel;<br>    }<br><br>    /**<br>     * Reads a PDF document, extracts text and images, and ingests them as segments.<br>     * Each image is processed by Gemini to generate a textual description.<br>     */<br>    public void saveMultimodalSegments(Resource resource, String prompt) throws IOException {<br>        log.info(&quot;Removing all segments ...&quot;);<br>        embeddingStore.removeAll();<br><br>        log.info(&quot;Loading document ...&quot;);<br>        try (PDDocument document = PDDocument.load(resource.getFile())) {<br>            PDPageTree pdPages = document.getPages();<br>            PDFTextStripper pdfTextStripper = new PDFTextStripper();<br>            int index = 0;<br>            int page = 0;<br>            for (PDPage pdPage : pdPages) {<br>                ++page;<br>                // Set the page range to extract text from the current page only<br>                pdfTextStripper.setStartPage(page);<br>                pdfTextStripper.setEndPage(page);<br><br>                PDResources resources = pdPage.getResources();<br>                List&lt;String&gt; media = new ArrayList&lt;&gt;();<br>                // Extract text from the current page<br>                String textContent = pdfTextStripper.getText(document);<br><br>                // Iterate over XObjects to extract images<br>                for (var c : resources.getXObjectNames()) {<br>                    PDXObject pdxObject = resources.getXObject(c);<br>                    if (pdxObject instanceof PDImageXObject image) {<br>                        ++index;<br>                        BufferedImage imageImage = image.getImage();<br><br>                        // Save image to disk<br>                        String imagePath = &quot;images/page_&quot; + page + &quot;_im_&quot; + index + &quot;.png&quot;;<br>                        try (FileOutputStream fileOutputStream = new FileOutputStream(imagePath)) {<br>                            ImageIO.write(imageImage, &quot;png&quot;, fileOutputStream);<br>                        }<br><br>                        // Convert image to Base64 for transmission<br>                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();<br>                        ImageIO.write(imageImage, &quot;png&quot;, byteArrayOutputStream);<br>                        byte[] data = byteArrayOutputStream.toByteArray();<br>                        String imageBase64 = Base64.getEncoder().encodeToString(data);<br><br>                        // Create an Image object with the Base64 encoded data<br>                        Image img = Image.builder()<br>                                .base64Data(imageBase64)<br>                                .mimeType(&quot;image/png&quot;)<br>                                .build();<br><br>                        ImageContent imageContent = ImageContent.from(img);<br>                        media.add(imagePath);<br><br>                        // Create a user message that includes the prompt and image content.<br>                        // The message instructs the AI to extract all necessary information from the image.<br>                        UserMessage userMessage = UserMessage.from(<br>                                TextContent.from(&quot;The user query is : \n&quot; + prompt +<br>                                        &quot;\n Extract all necessary information from the image&quot;),<br>                                imageContent<br>                        );<br><br>                        // Send the message to the Gemini LLM and receive a description<br>                        Response&lt;AiMessage&gt; response = chatLanguageModel.generate(userMessage);<br>                        String imageDescription = response.content().text();<br><br>                        // Append the image description to the page text<br>                        textContent = textContent + &quot;\n&quot; + &quot;IMAGE : &quot; + imagePath +<br>                                      &quot; Description of the image :\n&quot; + imageDescription;<br>                    }<br>                }<br><br>                // Build metadata for the document segment<br>                Metadata metadata = new Metadata();<br>                metadata.add(&quot;Page&quot;, page);<br>                metadata.add(&quot;media&quot;, media);<br><br>                // Create a document with text and metadata, then ingest it into the embedding store<br>                Document doc = new Document(textContent, metadata);<br>                embeddingStoreIngestor.ingest(doc);<br>            }<br>        }<br>    }<br><br>    /**<br>     * Saves the uploaded file to a designated directory and returns it as a Resource.<br>     */<br>    public Resource saveDocument(MultipartFile file) {<br>        try {<br>            if (file.getSize() &gt; MAX_FILE_SIZE) {<br>                throw new IllegalArgumentException(&quot;The file size must not exceed 10 MB&quot;);<br>            }<br><br>            File directory = new File(UPLOAD_DIR);<br>            if (!directory.exists()) {<br>                directory.mkdirs();<br>            }<br><br>            // Generate a unique filename<br>            String fileName = UUID.randomUUID().toString() + &quot;_&quot; + file.getOriginalFilename();<br>            Path filePath = Paths.get(UPLOAD_DIR, fileName);<br>            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);<br>            return new UrlResource(filePath.toUri());<br>        } catch (IOException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><h3>The REST Controller</h3><p>The controller exposes an endpoint to handle PDF uploads and user queries. Depending on whether a file is provided, the system either processes the PDF or directly passes the query to the chat service.</p><pre>@PostMapping(&quot;/pdf&quot;)<br>public Flux&lt;String&gt; load(@RequestParam(defaultValue = &quot;What is the content of the document?&quot;) String message,<br>                         @RequestParam(value = &quot;file&quot;, required = false) MultipartFile file) throws IOException {<br>    if(file == null || file.isEmpty()) {<br>        log.info(&quot;File is empty&quot;);<br>        return chatService.chat(message);<br>    }<br><br>    log.info(&quot;Saving document ...&quot;);<br>    Resource resource = ragService.saveDocument(file);<br>    log.info(&quot;Document saved&quot;);<br><br>    log.info(&quot;/////////////////////////&quot;);<br>    log.info(&quot;Saving segments ...&quot;);<br>    ragService.saveMultimodalSegments(resource, message);<br>    log.info(&quot;Segments saved&quot;);<br><br>    return chatService.chat(message);<br>}</pre><h3>Conclusion</h3><p>This article demonstrated how to create a multimodal RAG system that processes PDF files, extracts both text and images, and leverages advanced language models and embeddings to power a responsive chat interface. The additional configuration for chat memory and embedding storage ensures that the system can maintain context over previous interactions, thereby preserving semantic continuity across conversations.</p><p>By combining Langchain4j with Gemini and Hugging Face — and with Spring Boot’s powerful dependency injection that automatically injects beans into your @AiService components—you are well-equipped to build robust retrieval-augmented systems capable of handling both text and image data.</p><p>Feel free to reach out if you have any questions or need further enhancements. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=399be16250cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RAG Chatbot with Spring Boot, Langchain4j and Ollama (Example with DeepSeek R1)]]></title>
            <link>https://medium.com/@marouane.lasmak/building-a-rag-chatbot-with-spring-boot-langchain4j-and-ollama-example-with-deepseek-r1-74a36983fd51?source=rss-622e237d5f1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/74a36983fd51</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Marouane Lasmak]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 20:11:30 GMT</pubDate>
            <atom:updated>2025-01-30T20:53:01.518Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Retrieval-Augmented Generation (RAG) is revolutionizing how we build AI applications by combining the power of Large Language Models (LLMs) with custom knowledge bases. In this tutorial, we’ll build a chatbot that can understand and answer questions about your documents using Spring Boot, Langchain4j, and Ollama with DeepSeek R1 as our example model.</p><h3>Prerequisites</h3><p>Before we begin, make sure you have:</p><ul><li>Java 17 or higher</li><li>Maven</li><li>Docker</li><li>Ollama</li></ul><h3><strong>Project Setup</strong></h3><h3>Dependencies</h3><p>Create a new Spring Boot project and add these dependencies to your pom.xml:</p><pre>&lt;dependencies&gt;<br><br>    &lt;!-- Core Spring MVC for web application capabilities --&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><br>    &lt;!-- LangChain4j has an &quot;Easy RAG&quot; feature that makes it as easy as possible to get started with RAG --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-easy-rag&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Enables integration with Ollama for local LLM hosting --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-ollama&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- LangChain4j integrates seamlessly with PGVector, allowing developers to store and query vector embeddings directly in PostgreSQL --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-pgvector&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- To auto start the docker-compose when running the app --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-docker-compose&lt;/artifactId&gt;<br>        &lt;scope&gt;runtime&lt;/scope&gt;<br>        &lt;optional&gt;true&lt;/optional&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- LangChain4j provides a Spring Boot starter for auto-configuring AI Services, RAG, Tools etc. --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-spring-boot-starter&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- The AI Service can stream response token-by-token when using the Flux&lt;String&gt;. For this, please import langchain4j-reactor module --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;dev.langchain4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;langchain4j-reactor&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha1&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>&lt;/dependencies&gt;</pre><h3>Docker Environment</h3><p>Create a docker-compose.yml in your project root :</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  postgres:<br>    image: ankane/pgvector:latest<br>    ports:<br>      - &quot;5432:5432&quot;<br>    environment:<br>      POSTGRES_DB: postgres<br>      POSTGRES_USER: my_user<br>      POSTGRES_PASSWORD: my_password<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U my_user -d postgres&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 5<br><br>volumes:<br>  postgres_data:</pre><h3>Core Components</h3><h3>1. LLM Configuration</h3><p>Configures the DeepSeek model through Ollama :</p><pre>@Configuration<br>public class OllamaConfig {<br>    private static final String BASE_URL = &quot;http://localhost:11434&quot;;<br>    private static final String MODEL_NAME = &quot;deepseek-r1:1.5b&quot;;<br><br>    @Bean<br>    public ChatLanguageModel chatLanguageModel() {<br>        // Creates standard chat model for:<br>        // - Regular question-answering<br>        // - Single response generation<br>        // - Zero temperature for consistent outputs<br>        return OllamaChatModel.builder()<br>                .baseUrl(BASE_URL)<br>                .temperature(0.0)  // Deterministic responses<br>                .modelName(MODEL_NAME)<br>                .build();<br>    }<br><br>    @Bean<br>    public StreamingChatLanguageModel streamingChatLanguageModel() {<br>        // Creates streaming model for:<br>        // - Real-time response generation<br>        // - Token-by-token output<br>        // - Better user experience with immediate feedback<br>        return OllamaStreamingChatModel.builder()<br>                .baseUrl(BASE_URL)<br>                .temperature(0.0)<br>                .modelName(MODEL_NAME)<br>                .build();<br>    }<br><br>    @Bean<br>    public EmbeddingModel embeddingModel() {<br>        // Creates embedding model for:<br>        // - Converting text to vectors<br>        // - Document indexing<br>        // - Similarity search<br>        return OllamaEmbeddingModel.builder()<br>                .baseUrl(BASE_URL)<br>                .modelName(MODEL_NAME)<br>                .build();<br>    }<br>}</pre><h3>2. Memory and Database Configuration</h3><p>Manages conversation history and vector storage :</p><pre>@Configuration<br>public class MemoConfig {<br>    private EmbeddingModel embeddingModel;<br><br>    public MemoConfig(EmbeddingModel embeddingModel) {<br>        this.embeddingModel = embeddingModel;<br>    }<br><br>    @Bean<br>    public ChatMemoryProvider chatMemoryProvider() {<br>        // Creates a memory provider that:<br>        // - Maintains separate chat history for each chat ID<br>        // - Keeps last 10 messages in memory for context<br>        // - Helps maintain conversation coherence<br>        return chatId -&gt; MessageWindowChatMemory.withMaxMessages(10);<br>    }<br><br>    @Bean<br>    public EmbeddingStore&lt;TextSegment&gt; embeddingStore() {<br>        // Configures PostgreSQL with pgvector extension to:<br>        // - Store document embeddings as vectors<br>        // - Enable similarity search<br>        // - Auto-create required tables<br>        // - Match embedding dimensions with model<br>        return PgVectorEmbeddingStore.builder()<br>                .host(&quot;localhost&quot;)<br>                .port(5432)<br>                .database(&quot;postgres&quot;)<br>                .user(&quot;my_user&quot;)<br>                .password(&quot;my_password&quot;)<br>                .table(&quot;my_embeddings&quot;)<br>                .dimension(embeddingModel.dimension())  // Automatically matches model&#39;s embedding size<br>                .createTable(true)  // Creates table if it doesn&#39;t exist<br>                .build();<br>    }<br>}</pre><h3>3. Embedding Configuration</h3><p>This handles document processing and retrieval :</p><pre>@Configuration<br>public class EmbeddingConfig {<br><br>    @Bean<br>    public EmbeddingStoreIngestor embeddingStoreIngestor(EmbeddingModel embeddingModel,<br>                                                         EmbeddingStore&lt;TextSegment&gt; embeddingStore) {<br>        // Creates a document ingestor that:<br>        // - Splits documents into chunks of 1000 tokens<br>        // - Uses 100 tokens overlap to maintain context between chunks<br>        // - Uses the provided embedding model to convert text to vectors<br>        // - Stores the vectors in the provided embedding store<br>        return EmbeddingStoreIngestor.builder()<br>                .documentSplitter(DocumentSplitters.recursive(1000, 100))<br>                .embeddingModel(embeddingModel)<br>                .embeddingStore(embeddingStore)<br>                .build();<br>    }<br><br>    @Bean<br>    public EmbeddingStoreContentRetriever embeddingStoreContentRetriever(<br>            EmbeddingStore&lt;TextSegment&gt; embeddingStore,<br>            EmbeddingModel embeddingModel) {<br>        // Creates a content retriever that:<br>        // - Uses vector similarity search to find relevant document segments<br>        // - Returns maximum 3 most relevant results<br>        // - Only returns results with similarity score above 0.6<br>        // - Uses the same embedding model for query encoding<br>        return EmbeddingStoreContentRetriever.builder()<br>                .embeddingStore(embeddingStore)<br>                .embeddingModel(embeddingModel)<br>                .maxResults(3)  // Adjust this based on how many context segments you want<br>                .minScore(0.6)  // Minimum similarity threshold (0-1)<br>                .build();<br>    }<br>}</pre><h3>4. AI Service Interface</h3><p>The AiChatService interface is annotated with @AiService, an annotation provided by Langchain4j. This annotation plays a crucial role in configuring our chatbot service. It automatically injects all the necessary beans defined earlier, such as:</p><ul><li><strong>ChatLanguageModel</strong>: The language model (DeepSeek R1 in our case) responsible for generating responses.</li><li><strong>StreamingChatLanguageModel</strong>: The streaming language model for real-time responses.</li><li><strong>EmbeddingModel</strong>: The embedding model used to transform text into vectors.</li><li><strong>EmbeddingStoreContentRetriever</strong>: The component responsible for retrieving relevant documents from the vector store.</li><li><strong>ChatMemoryProvider</strong>: The conversation memory manager that maintains the context of user interactions.</li></ul><p>Thanks to this annotation, Langchain4j automatically configures the service by injecting these dependencies, greatly simplifying the setup and allowing you to focus on the chatbot’s business logic.</p><pre>@AiService<br>public interface AiChatService {<br>    @SystemMessage(&quot;&quot;&quot;<br>            You are an AI Agent, responsible for chatting with users.<br>            Ensure that you respond with the same language as the user.<br>            &quot;&quot;&quot;)<br>    Flux&lt;String&gt; chat(String message);<br>}</pre><h3>5. RAG Service</h3><p>Handles document processing and storage :</p><pre>@Service<br>public class RagService {<br>    private static final long MAX_FILE_SIZE = 3 * 1024 * 1024;  // 3MB limit<br>    private static final String UPLOAD_DIR = &quot;src/main/resources/docs&quot;;<br>    private static final Logger log = LoggerFactory.getLogger(RagService.class);<br><br>    private final EmbeddingStoreIngestor embeddingStoreIngestor;<br>    private final EmbeddingStore&lt;TextSegment&gt; embeddingStore;<br><br>    public RagService(EmbeddingStoreIngestor embeddingStoreIngestor, <br>                     EmbeddingStore&lt;TextSegment&gt; embeddingStore) {<br>        this.embeddingStoreIngestor = embeddingStoreIngestor;<br>        this.embeddingStore = embeddingStore;<br>    }<br><br>    public void saveSegments(Resource resource) throws IOException {<br>        // Process and store document segments:<br>        // 1. Clear existing segments to avoid duplicates<br>        log.info(&quot;Removing all segments ...&quot;);<br>        embeddingStore.removeAll();<br><br>        try {<br>            // 2. Load document from file system<br>            log.info(&quot;Loading document ...&quot;);<br>            Document document = FileSystemDocumentLoader.loadDocument(resource.getFile().toPath());<br>            <br>            // 3. Process and store document embeddings<br>            log.info(&quot;Ingesting document ...&quot;);<br>            embeddingStoreIngestor.ingest(document);<br>            log.info(&quot;Document ingested&quot;);<br>        } catch (BlankDocumentException e) {<br>            log.error(&quot;Document is empty&quot;);<br>        }<br>    }<br><br>    public Resource saveDocument(MultipartFile file) {<br>        try {<br>            // Validate and save uploaded file:<br>            // 1. Check file size<br>            if (file.getSize() &gt; MAX_FILE_SIZE) {<br>                throw new IllegalArgumentException(&quot;File size must not exceed 3MB&quot;);<br>            }<br><br>            // 2. Create upload directory if needed<br>            File directory = new File(UPLOAD_DIR);<br>            if (!directory.exists()) {<br>                directory.mkdirs();<br>            }<br><br>            // 3. Generate unique filename and save<br>            String fileName = UUID.randomUUID().toString() + &quot;_&quot; + file.getOriginalFilename();<br>            Path filePath = Paths.get(UPLOAD_DIR, fileName);<br>            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);<br><br>            // 4. Return file resource for further processing<br>            return new UrlResource(filePath.toUri());<br>        } catch (IOException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}</pre><h3>5. Chat Controller</h3><p>REST endpoints for the chatbot:</p><pre>@RestController<br>@RequestMapping(&quot;/chat&quot;)<br>@CrossOrigin(origins = &quot;*&quot;)<br>public class ChatController {<br>    private static final Logger log = LoggerFactory.getLogger(ChatController.class);<br>    private final AiChatService chatService;<br>    private final RagService ragService;<br><br>    public ChatController(AiChatService chatService, RagService ragService) {<br>        this.chatService = chatService;<br>        this.ragService = ragService;<br>    }<br><br>    @GetMapping<br>    public Flux&lt;String&gt; rag(@RequestParam(defaultValue = &quot;Hello&quot;) String message) {<br>        // Simple chat endpoint:<br>        // - Handles basic questions without document context<br>        // - Returns streaming response<br>        return chatService.chat(message);<br>    }<br><br>    @PostMapping(&quot;/load&quot;)<br>    public Flux&lt;String&gt; load(@RequestParam(defaultValue = &quot;What is the content of the document?&quot;) String message,<br>                           @RequestParam(value = &quot;file&quot;, required = false) MultipartFile file) throws IOException {<br>        // Document-aware chat endpoint:<br>        // 1. Check if file is provided<br>        if(file == null || file.isEmpty()) {<br>            log.info(&quot;File is empty&quot;);<br>            return chatService.chat(message);<br>        }<br><br>        // 2. Process uploaded document<br>        log.info(&quot;Saving document ...&quot;);<br>        Resource resource = ragService.saveDocument(file);<br>        log.info(&quot;Document saved&quot;);<br><br>        // 3. Extract and store document segments<br>        log.info(&quot;Saving segments ...&quot;);<br>        ragService.saveSegments(resource);<br>        log.info(&quot;Segments saved&quot;);<br><br>        // 4. Generate response using document context<br>        return chatService.chat(message);<br>    }<br>}</pre><h3>Implementation Details</h3><h3>How RAG Works in This Implementation</h3><ol><li>Document Processing Flow:</li></ol><ul><li>Document is uploaded through /chat/load endpoint</li><li>File is saved to disk and converted to a Document object</li><li>Document is split into segments with overlap</li><li>Each segment is converted to embeddings</li><li>Embeddings are stored in PGVector database</li></ul><p>2. Query Processing Flow:</p><ul><li>User question is received</li><li>Question is converted to embedding</li><li>Similar document segments are retrieved</li><li>Context is combined with chat history</li><li>DeepSeek generates response</li></ul><p>3. Conversation Management:</p><ul><li>Chat history is maintained per session</li><li>Last 10 messages provide context</li><li>Responses are streamed in real-time</li></ul><h3>Running the Application</h3><ol><li>Start Ollama with DeepSeek:</li></ol><pre>docker run -d --name ollama -v ollama:/root/.ollama -p 11434:11434 ollama/ollama<br>docker exec -it ollama ollama run deepseek-r1:1.5b</pre><p>2. Run your Spring Boot application</p><p>The application will automatically:</p><ul><li>Start <strong><em>PostgreSQL</em></strong> with <strong><em>PGVector</em></strong></li><li>Connect to your running Ollama instance</li><li>Initialize the vector database</li><li>Start the web server</li></ul><h3><strong>Testing the Chatbot</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*bMOxO-5JgoqK2y8jenQ60Q.png" /><figcaption>RAG with a .pdf file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*DPfmTs09DWIAi0ozpGct9g.png" /><figcaption>RAG with a .docx file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiRz8UIpBxIqe_Csek86Hw.png" /></figure><h3>Conclusion</h3><p>This implementation demonstrates how to build a production-ready RAG chatbot using modern Java tools. The combination of Spring Boot, Langchain4j, and Ollama provides a robust foundation for document-aware AI applications.</p><p>The complete code for this project shows how to:</p><ul><li>Process and embed documents</li><li>Store and retrieve vector embeddings</li><li>Maintain conversation context</li><li>Stream responses in real-time</li><li>Handle document uploads</li><li>Integrate with local LLMs</li></ul><h3>Additional Resources</h3><ul><li><a href="https://docs.langchain4j.dev/get-started">Langchain4j Documentation</a></li><li><a href="https://ollama.com/library/deepseek-r1">DeepSeek Models</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74a36983fd51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>