<?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 Sajal halder on Medium]]></title>
        <description><![CDATA[Stories by Sajal halder on Medium]]></description>
        <link>https://medium.com/@newtonh48?source=rss-d5c27f35a0ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VKPtzbOgks3lSxsh</url>
            <title>Stories by Sajal halder on Medium</title>
            <link>https://medium.com/@newtonh48?source=rss-d5c27f35a0ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:14:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@newtonh48/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 an AI-Powered Expense Tracker with Spring AI and Ollama]]></title>
            <link>https://medium.com/@newtonh48/building-an-ai-powered-expense-tracker-with-spring-ai-and-ollama-1e8f256ccc3a?source=rss-d5c27f35a0ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e8f256ccc3a</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[ai-vision-system]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sajal halder]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 16:40:46 GMT</pubDate>
            <atom:updated>2025-11-04T16:40:46.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Wl0Vw4bE18mkN6Yrn2OkwQ.png" /></figure><h3>What is Spring AI?</h3><p>Spring AI is Spring’s official framework for building AI-powered applications in Java. It provides a unified abstraction layer over various AI providers (OpenAI, Azure, Anthropic, Ollama, etc.), making it easy to integrate AI capabilities into Spring applications without vendor lock-in.</p><h3>Tech Stack</h3><pre>- **Spring Boot 3.x** - Core framework<br>- **Spring AI** - AI integration framework<br>- **Ollama** - Local LLM inference (qwen3:8b for chat, gemma3:4b for vision)<br>- **H2 Database** - In-memory database<br>- **Java 17+** - Modern Java features and functional programming</pre><h3>Architecture</h3><p>The application follows a clean architecture with three main AI components:</p><ol><li>AIConfig — Configuration for chat and vision clients</li><li>DBTool — Function calling tool for database operations</li><li>AIExpenseController — REST endpoints for AI interactions</li></ol><h3>Setting Up Spring AI with Ollama</h3><p>First, add the Spring AI dependencies to your project:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-ollama-spring-boot-starter&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Configure Ollama in `application.properties`:</p><pre># Spring AI Configuration<br>spring.ai.ollama.base-url=http://localhost:11434<br>spring.ai.ollama.chat.model=qwen3:8b<br>spring.ai.ollama.vision.model=gemma3:4b<br>spring.ai.ollama.chat.options.temperature=0.7</pre><h3>Creating AI-Powered Tools</h3><p>Spring AI supports function calling, where the AI can invoke Java methods to perform operations. Here’s how we define tools using the `@Tool` annotation:</p><pre>@Component<br>public class DBTool {<br>    private final ExpenseService expenseService;<br><br>    @Tool(description = &quot;Get all expenses from the database&quot;)<br>    public String getAllExpenses() {<br>        logger.info(&quot;AI Tool: Getting all expenses&quot;);<br>        return getAllExpensesResponse();<br>    }<br><br>    @Tool(description = &quot;Get expenses filtered by category&quot;)<br>    public String getExpensesByCategory(<br>            @ToolParam(description = &quot;The category to filter by&quot;) String category) {<br>        logger.info(&quot;AI Tool: Getting expenses by category: {}&quot;, category);<br>        return getExpensesByCategoryResponse(category);<br>    }<br><br>    @Tool(description = &quot;Create a new expense in the database&quot;)<br>    public String createExpense(<br>            @ToolParam(description = &quot;Description of the expense&quot;) String description,<br>            @ToolParam(description = &quot;Amount of the expense&quot;) BigDecimal amount,<br>            @ToolParam(description = &quot;Category of the expense&quot;) String category,<br>            @ToolParam(description = &quot;Date in ISO-8601 format&quot;) String date) {<br>        logger.info(&quot;AI Tool: Creating expense&quot;);<br>        return createExpenseResponse(description, amount, category, date);<br>    }<br>}</pre><p>The `@Tool` annotation makes methods discoverable by the AI model, and `@ToolParam` provides parameter descriptions that help the model understand how to use them.</p><h3>Configuring ChatClient with System Prompts</h3><p>The ChatClient is the main interface for interacting with AI models. Here’s how to configure it with a system prompt:</p><pre>@Configuration<br>public class AIConfig {<br>    public static final String SYSTEM_PROMPT = &quot;&quot;&quot;<br>        You are an intelligent expense tracking assistant.<br>        Your role is to help users manage their expenses efficiently.<br><br>        You have access to tools that can:<br>        - Get current date and time information<br>        - Retrieve all expenses or filter by category or ID<br>        - Calculate total spending (overall or by category)<br>        - Create new expense records<br>        - Update existing expense records<br>        - Delete expense records<br><br>        When users ask about expenses:<br>        - Be conversational and helpful<br>        - Use the appropriate tools to fetch or modify data<br>        - Present information in a clear, organized manner<br>        - For monetary values, always use proper currency formatting<br>        &quot;&quot;&quot;;<br><br>    @Bean(&quot;chatClient&quot;)<br>    public ChatClient chatClient(OllamaChatModel chatModel) {<br>        return ChatClient.builder(chatModel)<br>                .defaultSystem(SYSTEM_PROMPT)<br>                .build();<br>    }<br>}</pre><h3>Natural Language Query Endpoint</h3><p>Here’s the controller endpoint that handles natural language queries:</p><pre>@RestController<br>@RequestMapping(&quot;/api/ai/expenses&quot;)<br>public class AIExpenseController {<br>    private final ChatClient chatClient;<br>    private final DBTool dbTool;<br>    private final DateTimeTool dateTimeTool;<br><br>    @PostMapping(&quot;/chat&quot;)<br>    public Map&lt;String, String&gt; chat(@RequestBody Map&lt;String, String&gt; request) {<br>        String userMessage = request.get(&quot;message&quot;);<br>        logger.info(&quot;Received AI chat request: {}&quot;, userMessage);<br><br>        String response = chatClient<br>                .prompt()<br>                .user(userMessage)<br>                .tools(dbTool, dateTimeTool)<br>                .call()<br>                .content();<br><br>        return Map.of(&quot;response&quot;, response);<br>    }<br>}</pre><blockquote>This simple endpoint allows users to ask questions like:<br>- “What’s my total spending?”<br>- “Show me all expenses in the Food category”<br>- “Add a new expense for lunch at $25 in Food category today”</blockquote><h3>Vision AI for Receipt Processing</h3><p>One of the most powerful features is using vision models to extract expense data from receipt images:</p><pre>@PostMapping(&quot;/extract-from-image&quot;)<br>public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; extractExpenseFromImage(<br>        @RequestParam(&quot;image&quot;) MultipartFile image) {<br><br>    logger.info(&quot;Received image upload: {}&quot;, image.getOriginalFilename());<br><br>    // Validate image<br>    ImageValidator.ValidationResult validationResult =<br>        ImageValidator.validateAndProcess(image);<br><br>    if (!validationResult.isValid()) {<br>        return ResponseEntity.badRequest()<br>                .body(Map.of(&quot;error&quot;, validationResult.errorMessage()));<br>    }<br><br>    // Call vision model to extract expense information<br>    ExpenseRequests expenseRequests = visionChatClient.prompt()<br>            .user(u -&gt; u<br>                    .text(AIConfig.VISION_PROMPT)<br>                    .media(MimeTypeUtils.parseMimeType(validationResult.contentType()),<br>                           validationResult.imageResource())<br>            )<br>            .call()<br>            .entity(ExpenseRequests.class);<br><br>    // Create expenses from extracted data<br>    expenseRequests.expenseRequests().forEach(expenseService::createExpense);<br><br>    return ResponseEntity.ok(Map.of(<br>            &quot;success&quot;, true,<br>            &quot;message&quot;, &quot;Expenses created successfully!&quot;,<br>            &quot;count&quot;, expenseRequests.expenseRequests().size()<br>    ));</pre><p>The vision prompt instructs the AI to extract structured data:</p><pre>public static final String VISION_PROMPT = &quot;&quot;&quot;<br>    Analyze this receipt/bill/invoice image and extract ALL expense items visible.<br>    For each item, extract:<br>    1. Description: What was purchased or the service provided<br>    2. Amount: The total amount (just the number, no currency symbols)<br>    3. Category: Classify into: Food, Transport, Entertainment, Shopping,<br>       Bills, Healthcare, Education, Other<br>    4. Date: The date in ISO-8601 format (YYYY-MM-DDTHH:mm:ss)<br><br>    Extract all line items from the receipt as separate expenses.<br>    &quot;&quot;&quot;;</pre><h3>Key Takeaways</h3><ol><li><strong>Spring AI simplifies AI integration</strong>— No need to deal with raw API calls or complex prompting logic</li><li><strong>Function calling is powerful </strong>— Let the AI decide which operations to perform based on user intent</li><li><strong>Local LLMs with Ollama</strong> — Run AI models locally for privacy and cost savings</li><li><strong>Vision models unlock new UX </strong>— Receipt scanning eliminates manual data entry</li><li><strong>Clean architectur</strong>e — AI features integrate seamlessly with traditional Spring patterns</li></ol><h3>Challenges and Considerations</h3><ul><li><strong>Model Selection</strong>: Different models have varying capabilities. Experiment to find the right balance between performance and accuracy.</li><li><strong>Prompt Engineering</strong>: Clear, detailed prompts are crucial for reliable tool usage.</li><li><strong>Error Handling</strong>: AI responses can be unpredictable; robust validation is essential.</li><li><strong>Performance</strong>: Local models require significant compute resources.</li></ul><h3>What’s Next?</h3><ul><li>Add user authentication and multi-user support</li><li>Implement expense categories auto-learning</li><li>Add budget tracking and alerts</li><li>Support for multiple currencies</li><li>Export functionality (PDF, CSV)</li><li>Integration with banking APIs</li></ul><h3>Conclusion</h3><p>Spring AI makes it remarkably easy to add AI capabilities to traditional Spring applications. By combining function calling, vision models, and natural language processing, we can create intuitive, powerful user experiences that would have been extremely complex to build just a few years ago.</p><p>The complete source code is available on GitHub. Feel free to clone it, experiment, and build your own AI-powered applications!</p><p>Github : <a href="https://github.com/sajal48/expence_ai">https://github.com/sajal48/expence_ai</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e8f256ccc3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running a Kafka Cluster with KRaft Mode Using Docker]]></title>
            <link>https://medium.com/@newtonh48/running-a-kafka-cluster-with-kraft-mode-using-docker-b0392121e700?source=rss-d5c27f35a0ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0392121e700</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kafka-cluster]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Sajal halder]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 14:21:19 GMT</pubDate>
            <atom:updated>2025-02-24T14:24:54.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJZJDeAFegVcEGcDd32Isg.jpeg" /></figure><p>KRaft (Kafka Raft) is a <strong>self-managed metadata quorum</strong> built into Kafka, eliminating the need for Zookeeper. It uses the <strong>Raft consensus algorithm</strong> to manage metadata, ensuring fault tolerance and scalability.</p><h3>Why Move Away</h3><p>Apache Kafka has been the go-to distributed event streaming platform for handling real-time data at scale. Until now, Kafka has relied on <strong>Zookeeper</strong> for managing metadata, configurations, and controller election. However, <strong>ZooKeeper has been deprecated since Kafka 3.5.0</strong> and is planned for <strong>removal in Kafka 4.0</strong> 🚀. This means the <strong>KRaft (Kafka Raft) mode</strong> is the way forward!</p><p>In this article, we will explore <strong>KRaft mode</strong>, its advantages, and how to set up a Kafka cluster without Zookeeper using Docker.</p><h3>** from Zookeeper?** 🎉</h3><ol><li><strong>Simplified Architecture</strong> — Removes an extra dependency, reducing operational complexity.</li><li><strong>Better Scalability</strong> — Kafka can now scale metadata operations more efficiently.</li><li><strong>Improved Fault Tolerance</strong> — The Raft algorithm ensures robust leader election and consistency.</li><li><strong>Faster Recovery</strong> — KRaft speeds up broker restarts and controller elections.</li><li><strong>Lower Latency</strong> — Reduces the overhead of separate Zookeeper communications.</li></ol><h3>How KRaft Works</h3><ul><li>Kafka replaces <strong>Zookeeper with an internal metadata quorum</strong> that operates using Raft.</li><li>The <strong>KRaft controller</strong> is a dedicated Kafka broker responsible for metadata management.</li><li>Metadata updates are replicated across quorum members for consistency.</li><li>Regular Kafka brokers communicate with the controller instead of Zookeeper</li></ul><h3>Setting Up a Kafka Cluster with KRaft Mode Using Docker</h3><p>We will now set up a <strong>Kafka cluster running in KRaft mode</strong> using Docker, eliminating the need for Zookeeper. The steps include configuring the Kafka cluster, initializing metadata storage, and starting the brokers.</p><h3>Prerequisites</h3><p>Ensure you have the following installed:</p><ul><li>Docker and Docker Compose</li></ul><h3>Step 1: Define the Docker Compose File</h3><p>Below is the docker-compose.yml file to set up a <strong>three-node Kafka cluster with KRaft mode</strong> and a <strong>Kafka UI</strong> for monitoring.</p><pre>version: &#39;3&#39;<br><br>x-kafka-defaults: &amp;kafka-defaults<br>  image: confluentinc/cp-kafka:7.9.0<br>  environment: &amp;kafka-default-env<br>    KAFKA_CONTROLLER_QUORUM_VOTERS: &#39;1@kafka1:29093,2@kafka2:29094,3@kafka3:29095&#39;<br>    KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: &#39;CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT&#39;<br>    KAFKA_INTER_BROKER_LISTENER_NAME: &#39;PLAINTEXT&#39;<br>    KAFKA_CONTROLLER_LISTENER_NAMES: &#39;CONTROLLER&#39;<br>    KAFKA_PROCESS_ROLES: &#39;broker,controller&#39;<br>    CLUSTER_ID: &#39;ciWo7IWazngRchmPES6q5A==&#39;<br>    KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 3<br>    KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0<br>  networks:<br>    - kafka-net<br><br>services:<br>  kafka1:<br>    &lt;&lt;: *kafka-defaults<br>    container_name: kafka1<br>    ports:<br>      - &quot;9092:9092&quot;<br>    environment:<br>      &lt;&lt;: *kafka-default-env<br>      KAFKA_NODE_ID: 1<br>      KAFKA_ADVERTISED_LISTENERS: &#39;PLAINTEXT://kafka1:29092,PLAINTEXT_HOST://localhost:9092&#39;<br>      KAFKA_LISTENERS: &#39;CONTROLLER://kafka1:29093,PLAINTEXT://kafka1:29092,PLAINTEXT_HOST://0.0.0.0:9092&#39;<br><br>  kafka2:<br>    &lt;&lt;: *kafka-defaults<br>    container_name: kafka2<br>    ports:<br>      - &quot;9093:9093&quot;<br>    environment:<br>      &lt;&lt;: *kafka-default-env<br>      KAFKA_NODE_ID: 2<br>      KAFKA_ADVERTISED_LISTENERS: &#39;PLAINTEXT://kafka2:29092,PLAINTEXT_HOST://localhost:9093&#39;<br>      KAFKA_LISTENERS: &#39;CONTROLLER://kafka2:29094,PLAINTEXT://kafka2:29092,PLAINTEXT_HOST://0.0.0.0:9093&#39;<br><br>  kafka3:<br>    &lt;&lt;: *kafka-defaults<br>    container_name: kafka3<br>    ports:<br>      - &quot;9094:9094&quot;<br>    environment:<br>      &lt;&lt;: *kafka-default-env<br>      KAFKA_NODE_ID: 3<br>      KAFKA_ADVERTISED_LISTENERS: &#39;PLAINTEXT://kafka3:29092,PLAINTEXT_HOST://localhost:9094&#39;<br>      KAFKA_LISTENERS: &#39;CONTROLLER://kafka3:29095,PLAINTEXT://kafka3:29092,PLAINTEXT_HOST://0.0.0.0:9094&#39;<br><br>  kafka-ui:<br>    image: provectuslabs/kafka-ui:latest<br>    container_name: kafka-ui<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      KAFKA_CLUSTERS_0_NAME: local<br>      KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka1:29092,kafka2:29092,kafka3:29092<br>    networks:<br>      - kafka-net<br><br>networks:<br>  kafka-net:<br>    driver: bridge</pre><p>Note :</p><ol><li>KAFKA_PROCESS_ROLES: &#39;broker,controller&#39; - This defines the roles for each node to act as both a broker and a controller</li><li>KAFKA_CONTROLLER_QUORUM_VOTERS - This specifies the KRaft controller quorum</li><li>KAFKA_CONTROLLER_LISTENER_NAMES: &#39;CONTROLLER&#39; - This sets up the controller listeners</li><li>CLUSTER_ID - This provides a unique ID for the cluster in KRaft mode</li></ol><h3>Step 2: Adding More Brokers</h3><p>To add more brokers, duplicate one of the existing Kafka broker configurations (kafka1, kafka2, etc.), increment the KAFKA_NODE_ID, change ports accordingly, and update KAFKA_CONTROLLER_QUORUM_VOTERS to include the new broker.</p><p>For example, to add kafka4:</p><pre>  kafka4:<br>    &lt;&lt;: *kafka-defaults<br>    container_name: kafka4<br>    ports:<br>      - &quot;9095:9095&quot;<br>    environment:<br>      &lt;&lt;: *kafka-default-env<br>      KAFKA_NODE_ID: 4<br>      KAFKA_ADVERTISED_LISTENERS: &#39;PLAINTEXT://kafka4:29092,PLAINTEXT_HOST://localhost:9095&#39;<br>      KAFKA_LISTENERS: &#39;CONTROLLER://kafka4:29096,PLAINTEXT://kafka4:29092,PLAINTEXT_HOST://0.0.0.0:9095&#39;</pre><p>Don’t forget to update KAFKA_CONTROLLER_QUORUM_VOTERS to include the new broker&#39;s controller ID and port.</p><h3>Step 3: Start the Kafka Cluster</h3><p>Run the following command in the directory where docker-compose.yml is located:</p><pre>docker-compose up -d</pre><p>If you need to scale or only start specific services, you can use:</p><pre>docker-compose up -d kafka1 kafka-ui</pre><p>If you encounter issues, ensure no conflicting ports are in use and that the CLUSTER_ID remains consistent across all brokers.</p><h3>Conclusion 🎯</h3><p>KRaft mode is the future of Apache Kafka, offering a <strong>lighter, faster, and more scalable</strong> approach to metadata management. By eliminating Zookeeper, Kafka simplifies its architecture while improving fault tolerance and recovery times.</p><p>With Docker, setting up a Kafka cluster in KRaft mode becomes seamless. Now, you have a fully functioning Kafka cluster with KRaft mode, ready for real-world event streaming applications. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0392121e700" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>