<?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 Nouhaila Zahraoui on Medium]]></title>
        <description><![CDATA[Stories by Nouhaila Zahraoui on Medium]]></description>
        <link>https://medium.com/@noune.nouhaila?source=rss-e681432b70c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gPgeIXq0W3qIzE3O0snZRg.jpeg</url>
            <title>Stories by Nouhaila Zahraoui on Medium</title>
            <link>https://medium.com/@noune.nouhaila?source=rss-e681432b70c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:16:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noune.nouhaila/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 Log Analysis Pipeline with LangGraph, Elasticsearch, and MCP]]></title>
            <link>https://medium.com/@noune.nouhaila/building-an-ai-powered-log-analysis-pipeline-with-langgraph-elasticsearch-and-mcp-efa216b82143?source=rss-e681432b70c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/efa216b82143</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[pipeline]]></category>
            <dc:creator><![CDATA[Nouhaila Zahraoui]]></dc:creator>
            <pubDate>Tue, 19 May 2026 14:35:32 GMT</pubDate>
            <atom:updated>2026-05-19T14:35:32.917Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You’re three hours into debugging a production incident. You’ve got 47 browser tabs open, each with a different error message. Elasticsearch is showing you thousands of log lines, and somewhere in that noise is the one event that caused everything to cascade. Sound familiar?</em></p><p><em>I built Log Analyzer because I got tired of being that person. Not just a log aggregator, a pipeline that understands context, correlates events across time, and tells you what actually went wrong and why.</em></p><p><em>Log Analyzer is built as a pipeline, each component has one job, and they chain together cleanly. Here’s the full picture</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*pVIYeFcsaX-4ezS1FENN8Q.png" /><figcaption>Figure1: The complete system architecture.</figcaption></figure><p><em>Starting from the left:</em></p><p><strong><em>Flask</em></strong><em> acts as the chaos generator, it intentionally produces the kind of errors you’d see in a real production app: OOM errors, database timeouts, failed authentications. This gives the pipeline something real to reason about.</em></p><p><strong><em>Logstash</em></strong><em> sits right after and acts as the filter, stripping out noise like blank lines and browser headers before anything hits storage. Garbage in, garbage out, so we stop it early.</em></p><p><strong><em>Elasticsearch + Redis</em></strong><em> store and index the cleaned logs. Elasticsearch handles the querying, Redis handles the fast time-based lookups that power the ±2 minute context window, more on that in a moment.</em></p><p><strong><em>LangGraph</em></strong><em> is where the reasoning happens. Three agents in sequence: an Analyzer that reads the logs, a Root Cause agent that forms a hypothesis, and a Validator that challenges it. Not a simple chain, a council.</em></p><p><strong><em>FastMCP</em></strong><em> wraps the whole pipeline as a tool that Claude Desktop can call directly. One question, one answer, no dashboard switching.</em></p><h3><strong>Part 1 : Setting Up the Environment</strong></h3><h4>Prerequisites</h4><p>Before writing a single line of code, make sure you have the following installed:</p><ul><li><strong>Python 3.14+</strong> : this project uses the latest Python features and uv will enforce the version from pyproject.toml</li><li><strong>uv</strong> : the modern Python package manager we’ll use throughout. Install it with:</li></ul><pre>pip install uv</pre><ul><li><strong>Docker + Docker Compose</strong> : for running Elasticsearch, Logstash, Redis, and Kibana locally</li><li><strong>An OpenAI API key</strong> : the agents use gpt-4o-mini</li><li><strong>Claude Desktop</strong> : for the MCP tool demo at the end</li></ul><h4>Create the project</h4><pre># Create and initialize the project<br>uv init log-analyzer<br># Move into it<br>cd log-analyzer<br># Create the virtual environment<br>uv venv<br># Activate it<br># Windows:<br>.venv\Scripts\activate<br># Mac/Linux:<br>source .venv/bin/activate</pre><p>If you prefer plain pip, replace every uv pip install in this tutorial with pip install. Everything else stays the same.</p><h4>Project structure</h4><p>Before installing anything, create the following folder and file structure. This is the full layout of what we’re building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YVXZVXqY1CpUtCAzEzexA.png" /><figcaption>Figure 2: The final repository layout and directory structure for the project.</figcaption></figure><p>Create the folders in one command:</p><pre># Windows (PowerShell)<br>mkdir agents, elk\logstash\pipeline, elk\sample_logs, img, sample_logs<br><br># Mac/Linux<br>mkdir -p agents elk/logstash/pipeline elk/sample_logs img sample_logs</pre><p>Then create the empty Python files:</p><pre># Windows<br>New-Item agents\__init__.py, agents\elk.py, agents\graph.py, agents\prompts.py, agents\utils.py, App.py, flask_login_app.py, main.py, mcp_server.py, queue_worker.py -ItemType File<br># Mac/Linux<br>touch agents/__init__.py agents/elk.py agents/graph.py agents/prompts.py agents/utils.py App.py flask_login_app.py main.py mcp_server.py queue_worker.py</pre><h4>Dependencies</h4><p>Your pyproject.toml should look like this:</p><pre>[project]<br>name = &quot;log-analyzer&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;AI-powered log analysis pipeline&quot;<br>readme = &quot;README.md&quot;<br>requires-python = &quot;&gt;=3.14&quot;<br>dependencies = [<br>    &quot;langchain-openai&gt;=1.1.12&quot;,<br>    &quot;langgraph&gt;=1.1.6&quot;,<br>    &quot;mcp[cli]&gt;=1.27.0&quot;,<br>    &quot;python-dotenv&gt;=1.2.2&quot;,<br>    &quot;requests&gt;=2.33.1&quot;,<br>    &quot;streamlit&gt;=1.56.0&quot;,<br>]</pre><p>And your Requirements.txt with the additional packages needed at runtime:</p><pre>streamlit<br>langgraph<br>langchain-openai<br>langchain-core<br>python-dotenv<br>fastmcp<br>redis<br>requests<br>flask<br>python-logstash<br>mcp[cli]<br>Install everything:<br>uv pip install -r Requirements.txt</pre><h4>Environment variables</h4><p>Create a .env file at the root of the project:</p><pre>OPENAI_API_KEY=your_openai_api_key_here</pre><p>That’s the only required variable. The Elasticsearch and Redis URLs are hardcoded to localhost in elk.py which is fine for local development, if you’re deploying this, move those to .env as well.</p><p>⚠️ <strong>Important:</strong> Add your .env file to .gitignore before pushing to GitHub. It contains your OpenAI API key and should never be public.</p><p>And the project structure on vs code should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*kGzmaGLq_FonY3UgYdaAvQ.png" /><figcaption>Figure 3: The project file tree view in VS Code.</figcaption></figure><h3>Part 2 : The Chaos Generator</h3><p>Before analyzing logs, we need logs worth analyzing. flask_login_app.py is a small Flask app that simulates a real service generating realistic production errors on demand.</p><p>The key design decision here is <strong>structured logging</strong>. Every log ships as JSON with named fields like service, ip, attempts, duration_ms. not plain text strings. This is what makes them machine-readable downstream in Logstash and queryable in Elasticsearch.</p><p>The only non-obvious piece is the logger setup:</p><pre>logstash_handler = logstash.TCPLogstashHandler(<br>  host=&quot;localhost&quot;,<br>  port=5000,<br>  version=1,<br>)<br>logger.addHandler(logstash_handler)</pre><p>TCPLogstashHandler ships every logger.error() call directly to Logstash over TCP as JSON, no file writing, no delay. The extra dict you pass to each log call becomes a queryable field in Elasticsearch.</p><p>The app exposes six routes:</p><pre>def home() # basic health check log<br>def login() # random: success / wrong password / account locked<br>def db_query() # random: fast query / slow query / connection timeout<br>def timeout() # circuit breaker trip, fires 2 logs in sequence<br>def error() # unhandled exception with full stacktrace<br>def noise() # INFO/DEBUG logs that Logstash will drop<br>def stress() # floods the pipeline with 10 random scenarios at once</pre><p>/stress is your best friend during development, hit it a few times and you’ll have enough varied data in Elasticsearch to test the full pipeline.</p><p>Full code: flask_login_app.py on GitHub</p><h3>Part 3 :The Filter (Logstash)</h3><p>Logstash sits between the Flask app and Elasticsearch. Its job is simple but critical: parse the incoming JSON, rename fields to a clean schema, and drop everything that isn’t worth analyzing.</p><p>The pipeline has three blocks: input, filter, and output.</p><p>Input listens on two sources:</p><pre>tcp { port =&gt; 5000 } # receives logs directly from the Flask app<br>file { path =&gt; &quot;/logs/*.log&quot; } # watches a folder for dropped log files</pre><p>Filter is where the noise gets killed. It parses the JSON message, renames nested fields to top-level ones, then applies two drop rules:</p><pre>if &quot;_jsonparsefailure&quot;         → drop  # kills malformed lines, browser headers, blank lines<br>if log_level not in ERROR/WARN → drop  # kills INFO and DEBUG — we only care about problems</pre><p>This second rule is an important design decision. By the time a log reaches Elasticsearch, it’s already been pre-filtered to only errors and warnings. The agents never see INFO spam.</p><p>Output ships to Elasticsearch on a daily index pattern:</p><pre>index =&gt; &quot;logs-%{+YYYY.MM.dd}&quot; # e.g. logs-2026.05.15</pre><p>Daily indices make it easy to query a specific day and to set up retention policies later.</p><p>Full config: elk/logstash/pipeline/logstash.conf on GitHub</p><h4>Part 4 : The Storage Layer (Elasticsearch + Redis)</h4><p>elk.py handles everything related to fetching, queuing, and storing logs. It’s the bridge between the ELK stack and the agent pipeline.</p><p>The functions split into four responsibilities:</p><pre># Fetching<br>def fetch_recent_logs() # get last N logs from Elasticsearch<br>def fetch_logs_by_level() # filter by ERROR or WARN<br>def fetch_distinct_services() # list all services seen in the index<br># The context window<br>def fetch_context_logs() # ±2 min window around a target log<br># The queue<br>def enqueue_logs() # push unseen log IDs into Redis<br>def fetch_next_from_queue() # pop next log ID, fetch full doc from ES<br># Persistence<br>def save_analysis() # store agent results back into Elasticsearch<br>def fetch_analyses() # retrieve past analyses</pre><p>The most important function is fetch_next_from_queue(). Here’s what it does beyond just fetching a log:</p><pre># fetch surrounding context logs from same service<br>context = fetch_context_logs(timestamp=raw_ts, service=svc)<br># remove the target log itself to avoid duplication<br>context = [line for line in context if line != log_text]<br>if context:<br>  log_text = f&quot;{context_block}\n - - TARGET LOG - -\n{log_text}\n - - END TARGET - -&quot;</pre><p>This is the context window,<strong> </strong>the most important architectural decision in the whole project. Instead of sending a single log line to the agents, it sends everything that happened on the same service in the ±2 minutes around that log. The agents don’t just see the error, they see what led up to it.</p><p>Redis acts as the queue manager. It stores log IDs (not full documents) using two structures:</p><pre>QUEUE_KEY → list # ordered queue of log refs to process<br>SEEN_SET_KEY → set # deduplication - never process the same log twice</pre><p>This means you can call enqueue_logs() repeatedly without worrying about duplicates flooding the pipeline.</p><p>Full code: agents/elk.py on GitHub</p><h3>Part 5 :The Agent Pipeline (LangGraph)</h3><p>This is the brain of the system. The pipeline is built with LangGraph and runs three agents in sequence, with a feedback loop.</p><h4>The prompts</h4><p>Each agent has a focused, strict prompt in prompts.py:</p><pre>def analyzer_prompt(logs) # extract: error type, service, events list<br>def root_cause_prompt(analyzer_output) # identify: why it happened, how to fix it<br>def validator_prompt(combined) # verify: does the fix match the error? is it complete?</pre><p>Every prompt ends with the same instruction: return only valid JSON, no markdown, no explanation. This is what makes extract_json() in utils.py reliable , the model never wraps the output in prose.</p><h4>The graph</h4><p>The state flows through three nodes:</p><pre>analyzer_node → root_node → validator_node</pre><p>The interesting part is what happens after the validator:</p><pre>def route(state: State) -&gt; str:<br>  if not state[&quot;validation&quot;].get(&quot;valid&quot;, True) and state[&quot;retries&quot;] &lt; 2:<br>    return &quot;root&quot;<br>  return END</pre><p>If the validator rejects the diagnosis, meaning the fix doesn’t logically match the error, it sends the state back to the root cause agent for another attempt. This retry loop runs up to 2 times before the pipeline accepts whatever it has.</p><p>This is why LangGraph was the right choice here over a simple LangChain chain. A linear chain can’t loop back. LangGraph treats the pipeline as a graph with conditional edges, which is exactly what this feedback pattern requires.</p><p>The full state shape:</p><pre>class State(TypedDict):<br>  logs: str # raw log input with context window<br>  analyzer: dict # output of analyzer agent<br>  root: dict # output of root cause agent<br>  validation: dict # output of validator agent<br>  retries: int # how many times root cause was retried</pre><p>Full code: agents/graph.py and agents/prompts.py on GitHub</p><h3>Part 6 : The MCP Tool (FastMCP)</h3><p>This is what makes the project go from “useful script” to “conversational SRE tool.” FastMCP wraps the entire pipeline as a tool that Claude Desktop can call by name.</p><pre>mcp = FastMCP(&quot;Log Investigator&quot;)<br>@mcp.tool()<br>def analyze_log(log_text: str) -&gt; dict:<br>  &quot;&quot;&quot;<br>  Analyze a raw log and return the root cause and fix.<br>  Runs a 3-agent LangGraph pipeline…<br>  &quot;&quot;&quot;<br>  result = run_pipeline(log_text)<br>  return {<br>    &quot;error&quot;: result.get(&quot;analyzer&quot;, {}).get(&quot;error&quot;),<br>    &quot;root_cause&quot;: result.get(&quot;root&quot;, {}).get(&quot;root_cause&quot;),<br>    &quot;fix&quot;: result.get(&quot;root&quot;, {}).get(&quot;fix&quot;),<br>    &quot;valid&quot;: result.get(&quot;validation&quot;, {}).get(&quot;valid&quot;),<br>    &quot;confidence&quot;: result.get(&quot;validation&quot;, {}).get(&quot;confidence&quot;),<br>    &quot;retries&quot;: result.get(&quot;retries&quot;, 0),<br>    }</pre><p>The docstring matters here, Claude Desktop reads it to understand when and how to call the tool. Write it like an API contract, not a code comment.</p><p>The file also registers two extras:</p><pre>@mcp.resource(&quot;logs://samples/{name}&quot;) # serve sample log files to Claude<br>@mcp.prompt() # pre-built investigation prompt</pre><p>To connect it to Claude Desktop, add this to your claude_desktop_config.json:</p><pre>{<br>&quot;mcpServers&quot;: {<br>  &quot;log-investigator&quot;: {<br>    &quot;command&quot;: &quot;python&quot;,<br>    &quot;args&quot;: [&quot;path/to/mcp_server.py&quot;]<br>}}}</pre><p>Restart Claude Desktop and you’ll see the analyze_log tool available. You can then literally ask: <em>“Why is the payment service failing?”</em> and Claude will call the tool, run the full pipeline, and give you a diagnosis in plain English.</p><p>Full code: mcp_server.py on GitHub</p><h3>Part 7 :Running Everything Together</h3><p>Now that all the pieces are built, here’s how to bring the full stack up in the right order.</p><h4>1. Start the Docker stack</h4><pre>cd elk<br>docker compose up -d</pre><p>This spins up Elasticsearch, Logstash, Redis, and Kibana. Wait about 30 seconds for Elasticsearch to be healthy before moving on. You can verify with:</p><pre>curl http://localhost:9200/_cluster/health</pre><p>You should see “status”:”green” or “status”:”yellow”, both are fine.</p><h4>2. Start the Flask chaos generator</h4><p>In a new terminal:</p><pre>python flask_login_app.py</pre><p>The app starts on port 6001. Hit the stress endpoint a few times to flood the pipeline with varied logs:</p><pre>curl http://localhost:6001/stress</pre><h4>3. Start the queue worker</h4><p>In another terminal:</p><pre>python queue_worker.py</pre><p>This pulls logs from Elasticsearch into the Redis queue and feeds them into the LangGraph pipeline one by one.</p><h4>4. Start the Streamlit dashboard</h4><pre>streamlit run App.py</pre><p>Open <a href="http://localhost:8501/">http://localhost:8501</a>, you’ll see logs being analyzed in real time, with the error type, root cause, fix, confidence score, and retry count for each one.</p><p>Here’s what the dashboard looks like in action. Each analyzed log shows the detected error, root cause, suggested fix, confidence score, and how many times the validator forced a retry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0caBSaKSPmQ2h_BElfzxw.png" /><figcaption>Figure 4: The Streamlit dashboard displaying the final pipeline result.</figcaption></figure><p>The real payoff, asking Claude Desktop a plain English question and getting a surgical diagnosis back in seconds, powered by the full 3-agent pipeline running under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OGQIXzOp-RTPX-nnHPz-g.png" /><figcaption>Figure 5: Claude Desktop natively executing the log-analyzer MCP tool to diagnose a pasted log sequence directly in the chat window.</figcaption></figure><p>That’s it. You just built a pipeline that does the painful part of being an engineer for you.<br>The stack is open source, the agents are yours to extend, and the only limit is what chaos you throw at it. Go break something. 🔥</p><p>The full code is on GitHub: <a href="https://github.com/Nouhaila-Zahraoui/log-analyzer-ai">here</a>. You can see the full demo on LinkedIn: <a href="https://www.linkedin.com/in/nouhaila-zahraoui-21b118172">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efa216b82143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka vs. RabbitMQ: Decoding the Messaging Titans of Modern Systems ⚡]]></title>
            <link>https://medium.com/@noune.nouhaila/kafka-vs-rabbitmq-decoding-the-messaging-titans-of-modern-systems-1f14b7da5320?source=rss-e681432b70c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f14b7da5320</guid>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-streaming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nouhaila Zahraoui]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 21:24:57 GMT</pubDate>
            <atom:updated>2026-05-19T14:49:50.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPgXxeAeaxyBrrqWJiVLow.png" /></figure><p>Kafka and RabbitMQ. If I were to mention these names in a group of people, especially those outside the tech world, confusion would likely spread across the room. What’s the connection between a philosophical writer and a small furry animal 🐇? Shouldn’t it be Kafka and the Beetle if we’re talking about metaphors? After all, Kafka’s universe was often surreal, perplexing, and filled with a peculiar sense of order during chaos, much like the intricate dance of messages in a distributed system.</p><p>In reality, Kafka (the distributed streaming platform) and RabbitMQ (a message broker) are two of the most essential tools in modern software engineering, enabling systems to communicate efficiently. They may not write novels, but they help write the story of how data moves through applications.</p><p>In this article, we’ll explore the intricate world of Kafka and RabbitMQ, two giants in the messaging landscape. 🏗️ Here’s what we’ll cover:</p><ul><li>A deep dive into their <strong>global architectures</strong> 🧩</li><li>The role and interactions of key <strong>components</strong> in each system 🔗</li><li>Common <strong>use cases</strong> and scenarios where each tool excels 📊</li><li>A balanced view of their <strong>advantages and disadvantages</strong> ⚖️</li><li>A quick <strong>summary of key differences</strong> to help you choose wisely 🤔</li></ul><p>KAFKA</p><p><strong>1-Global architecture<br></strong>Kafka is an open-source distributed streaming platform designed for handling large volumes of real-time data with scalability, fault tolerance, and low latency. Its producer-subscriber model and distributed cluster architecture power event-driven systems and streaming pipelines worldwide.<br>Kafka’s global architecture can be schematized like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*21QOHUeQnYYMisWzVoTWEw.png" /><figcaption>Kafka’s architecture</figcaption></figure><p><strong>2-Components</strong></p><p>Kafka’s architecture is composed of: <br><strong>2.1 Topics</strong><br>A topic is a logical channel where messages are stored and categorized. Producers write messages to topics, and consumers read from them. Topics can be divided into partitions for parallelism.<br><strong>2. 2 Partitions</strong><br>Each topic is split into partitions, which are segments of the topic’s log. Partitions enable distributed storage and processing. Each message in a partition has a unique sequential ID called an offset.<br><strong>2.3 Producers</strong><br>Producers are applications or services that send messages to Kafka topics. They decide the topic and partition for each message and can add metadata like keys for message ordering.<br><strong>2.4 Consumers</strong><br>Consumers read messages from topics. They can be part of consumer groups, which allow multiple consumers to process messages in parallel by dividing partitions among group members.<br><strong>2.5 Brokers</strong><br>Brokers are Kafka servers that store topic data and handle client requests. A Kafka cluster consists of multiple brokers, each responsible for a subset of partitions. Brokers coordinate to ensure fault tolerance.<br><strong>2.6 Cluster</strong><br>A Kafka cluster is a group of brokers working together to provide distributed, scalable message handling. It ensures high availability by replicating partitions across multiple brokers.<br><strong>2.7 Zookeeper (or KRaft in newer versions)</strong><br>Kafka relies on Zookeeper (or KRaft in the newer architecture) for cluster coordination, leader election, and metadata management. It keeps track of the status of brokers and partitions.<br><strong>2.8 Replication</strong><br>Kafka ensures fault tolerance by replicating partitions across multiple brokers. One replica acts as the leader, while others are followers. Only the leader handles client requests for that partition.</p><p><strong>3-Interaction in the Kafka architecture</strong></p><p>Kafka’s architecture is a well-orchestrated system of producers, brokers, partitions, and consumers, with Zookeeper handling metadata and coordination. <br><strong>3.1 Producers and Brokers</strong><br><em>Interaction:</em> Producers send messages to Kafka topics on a broker.<br><em>Details: </em>Producers decide the topic and partition for each message, often using a key for deterministic partitioning.<br>Messages are batched for efficiency and sent to the broker responsible for the specified partition (the leader partition).<br>The broker acknowledges the reception to the producer.<br><strong>3.2 Brokers and Partitions</strong><br><em>Interaction: </em>Brokers manage partitions for topics, with one broker serving as the leader for each partition.<br><em>Details:</em> Each partition has a leader (handling client requests) and followers (replicating the leader’s data).<br>Brokers coordinate to replicate data across partitions for fault tolerance.<br><strong>3.3 Consumers and Brokers</strong><br><em>Interaction:</em> Consumers pull messages from brokers by subscribing to topics.<br><em>Details:</em> Consumers can belong to consumer groups, where partitions are distributed among group members for parallel processing.<br>Each consumer tracks its offsets, indicating the last processed message in each partition.<br><strong>3.4 Zookeeper/KRaft and Brokers</strong><br><em>Interaction</em>: Zookeeper (or KRaft in newer versions) manages the state and metadata of the Kafka cluster.<br><em>Details</em>: Tracks which brokers are active and assigns leadership for partitions.<br>Monitors changes in the cluster, such as broker failures, triggering leader re-elections when needed.<br><strong>3.5 Producers and Partitions</strong><br><em>Interaction</em>: Producers determine how messages are distributed across partitions.<br><em>Details</em>: Messages with a key are consistently routed to the same partition, ensuring order for specific keys.<br>Without a key, partitions are selected using round-robin or other partitioning logic.<br><strong>3.6 Consumers and Partitions</strong><br><em>Interaction:</em> Consumers fetch messages from specific partitions within a topic.<br><em>Details:</em> In consumer groups, Kafka ensures that each partition is consumed by only one consumer in the group.<br>Offsets allow consumers to control processing (e.g., replaying messages by resetting offsets).</p><p><strong>4. Use cases</strong></p><p>Kafka excels in scenarios where high-throughput streaming is required without the need for complex routing. It’s particularly well-suited for use cases like event sourcing, stream processing, and modeling system changes as a sequence of events. Additionally, Kafka is ideal for processing data in multi-stage pipelines.<br>In essence, Kafka is the go-to solution when you need a framework for storing, reading, re-reading, and analyzing streaming data. Its ability to retain messages makes it perfect for systems requiring routine audits or permanent storage. Simply put, Kafka truly shines in real-time data processing and analytics.</p><p><strong>5. Advantages and Disadvantages<br></strong><br><strong>5.1 Advantages</strong><br><em>-High Throughput:</em> Handles massive amounts of data efficiently, making it ideal for high-scale, real-time streaming.<br><strong>-</strong><em>Scalability:</em> Designed for distributed systems; easily scales horizontally by adding more brokers.<br><em>-Message Retention:</em> Stores messages for a configurable duration, enabling event replay and audit trails.<br><em>-Durability and Fault Tolerance: </em>Ensures data persistence and high availability with partition replication across brokers.<br><strong>-</strong><em>Real-Time Processing:</em> Supports stream processing with tools like Kafka Streams and ksqlDB for real-time analytics.<br><em>-Integration:</em> Seamlessly integrates with modern big data tools like Spark, Flink, and Hadoop.<br><br><strong>5.2 Disadvantages</strong><br><em>-Complexity:</em> More challenging to set up and maintain, with steep learning curve.<br><em>-High Resource Usage:</em><strong><em> </em></strong>Requires significant memory, CPU, and disk space, especially for large-scale deployments.<br><em>-Limited Routing Options</em></p><p>RABBITMQ</p><p><strong>1-Global architecture<br></strong>RabbitMQ can me modelized like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*GgL9ztPdfmILsIsomgavAQ.png" /><figcaption>RabbitMQ’s architecture</figcaption></figure><p><strong>2- Components<br></strong>RabbitMQ’s architecture consists of several key components that facilitate message delivery and routing:<br><strong>2.1 Producer</strong><br><em>Definition:</em> Applications or services that send messages to RabbitMQ.<br><em>Role: </em>Producers publish messages to exchanges, not directly to queues. They don’t need to know the queue structure as the exchange handles routing.<br><strong>2.2 Exchange</strong><br><em>Definition:</em> A component responsible for routing messages to one or more queues based on routing rules.<br><em>Types:</em><br>*Direct: Routes messages to a queue with a specific routing key.<br>*Fanout: Broadcasts messages to all bound queues.<br>*Topic: Routes messages to queues based on pattern-matching rules in the routing key.<br>*Headers: Routes messages based on message header attributes instead of routing keys.<br><strong>2.3 Queue</strong><br><em>Definition:</em> A storage area where messages are held until consumed.<br><em>Role:</em> Messages are sent to queues after routing by an exchange. Consumers retrieve messages from queues. Queues support features like durability, TTL (time-to-live), and dead-lettering.<br><strong>2.4 Consumer</strong><br><em>Definition:</em> Applications or services that receive and process messages from RabbitMQ queues.<br><em>Role:</em> Consumers acknowledge messages after processing, ensuring reliable delivery. Multiple consumers can work on the same queue for load balancing.<br><strong>2.5 Binding</strong><br><em>Definition:</em> A link between an exchange and a queue.<br><em>Role: </em>Bindings determine which messages an exchange should route to which queues based on routing keys or header attributes.<br><strong>2.6 Routing Key</strong><br><em>Definition: </em>A string used by producers to label messages.<br><em>Role:</em> The routing key is used by exchanges to determine how to route the message to the appropriate queue(s).<br><strong>2.7 Virtual Host (vHost)</strong><br><em>Definition: </em>A logical grouping of exchanges, queues, and bindings.<br><em>Role:</em> vHosts provide multi-tenancy by allowing multiple users or applications to share a single RabbitMQ instance while keeping their configurations and data isolated.<br><strong>2.8 Broker</strong><br><em>Definition:</em> The RabbitMQ server itself, which acts as the message broker.<br><em>Role: </em>Handles the interactions between producers, exchanges, queues, and consumers, ensuring message delivery and reliability.</p><p><strong>3-Interaction in the RABBITMQ architecture</strong></p><p><strong>3.1 Producer to Exchange</strong><br><em>Interaction:</em> Producers publish messages to exchanges.<br><em>Details: </em>The producer specifies the exchange and a routing key for the message.<br>The exchange does not store messages but acts as a router, determining where the message should go.<br>If no queues are bound to the exchange (or no match for the routing key exists), the message can be discarded unless configured otherwise.<br><strong>3.2 Exchange to Queue</strong><br><em>Interaction: </em>Exchanges route messages to queues based on bindings and routing keys.<br><em>Details: * </em>Direct Exchange: Routes messages to queues with a matching routing key.<br>*Fanout Exchange: Broadcasts the message to all bound queues, ignoring routing keys.<br>*Topic Exchange: Uses pattern-matching rules (e.g., *.critical.*) in the routing key to determine queue routing.<br>*Headers Exchange: Matches message header attributes with binding criteria instead of routing keys.<br><strong>3.3 Queue to Consumer</strong><br><em>Interaction:</em> Consumers retrieve messages from queues.<br><em>Details: </em>Consumers can pull messages (poll the queue) or set up a subscription to have messages pushed to them.<br>RabbitMQ removes messages from the queue once they are delivered to consumers, but only after they’re acknowledged.<br><strong>3.4 Acknowledgment from Consumer to Queue</strong><br><em>Interaction:</em> Consumers acknowledge messages back to RabbitMQ after processing.<br><em>Details: </em>If the consumer successfully processes the message, it sends a positive acknowledgment, and RabbitMQ deletes the message.<br>If the consumer fails or doesn’t acknowledge within a timeout, RabbitMQ can redeliver the message to another consumer.<br><strong>3.5 Dead Letter Exchange (DLX)</strong><br><em>Interaction:</em> Messages that can’t be processed are routed to a Dead Letter Exchange.<br><em>Details: </em>Messages may end up here if they are rejected, expired, or hit a maximum delivery attempt limit.<br>DLXs provide a way to handle or log problematic messages for debugging or reprocessing.<br><strong>3.6 Virtual Hosts (vHosts)</strong><br><em>Interaction:</em> vHosts isolate resources for multiple applications or users.<br><em>Details: </em>Each vHost contains its own set of exchanges, queues, and bindings.<br>Producers and consumers connected to one vHost cannot interact with those in another.</p><p><strong>4. Use cases</strong></p><p>RabbitMQ is a popular choice for handling high-throughput, reliable background jobs and facilitating integration and communication between applications. Developers rely on RabbitMQ for complex message routing to consumers and connecting multiple services with sophisticated routing logic. <br>It’s particularly well-suited for web servers requiring fast request-response cycles and for distributing workloads among workers under heavy load (e.g., 20K+ messages per second). RabbitMQ also excels at managing background tasks and long-running operations, such as PDF conversion, file scanning, or image resizing. <br>In summary, RabbitMQ is ideal for long-running tasks, dependable background job execution, and seamless communication and integration within and across applications.</p><p><strong>5. Advantages and inconvinients</strong></p><p><strong>5.1 Advantages</strong><br><em>Flexibility in Routing: </em>Offers advanced routing mechanisms (direct, fanout, topic, and headers exchanges).<br><em>Ease of Use:</em> Simple setup and intuitive management interface, making it accessible for smaller teams.<br><em>Wide Protocol Support:</em><strong><em> </em></strong>Supports AMQP, MQTT, STOMP, and other messaging protocols, ensuring compatibility with various systems.<br><em>Lightweight :</em> Efficient resource usage compared to Kafka, suitable for smaller or less resource-intensive applications.<br><em>Reliability:</em> Ensures reliable message delivery with acknowledgments, retries, and dead-letter queues.<br><em>Task Processing:</em> Ideal for task-based systems and background job execution (e.g., image processing, email sending).<br><em>Message Prioritization:</em> Supports message priority queues to handle high-priority tasks first.</p><p><strong>5.2 Disadvantages</strong><br><em>Lower Throughput:</em> Can struggle with extremely high message rates compared to Kafka.<br><em>No Native Data Retention: </em>Messages are removed once consumed unless explicitly configured with dead-letter queues.<br><em>Scaling Challenges: </em>Horizontal scaling can be more complex, especially for large workloads.<br><em>Shorter Message Lifespan:</em> Not designed for long-term message storage or event replay.</p><p><strong>Wrap-Up 🌟</strong></p><p>In the battle of Kafka vs. RabbitMQ, there’s no one-size-fits-all answer. 🎭 Kafka shines as the king of high-throughput, real-time streaming systems, while RabbitMQ rules with its flexibility, reliability, and intuitive management. 🛠️<br>Whether you’re processing millions of events in real-time or ensuring reliable background job execution, both tools offer unique advantages tailored to different needs. The choice between Kafka and RabbitMQ ultimately depends on your system’s requirements, scale, and complexity. <br>So, whether you’re building your next big data pipeline or orchestrating seamless communication between microservices, rest assured you’re in good company with Kafka and RabbitMQ. Happy messaging! 📨✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f14b7da5320" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Mystery of the Smart Alpaca : Unleashing Ollama’s AI Power]]></title>
            <link>https://medium.com/@noune.nouhaila/solving-the-mystery-of-the-smart-alpaca-unleashing-ollamas-ai-power-c126cffcede1?source=rss-e681432b70c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c126cffcede1</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nouhaila Zahraoui]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 19:41:17 GMT</pubDate>
            <atom:updated>2026-05-19T14:52:01.186Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous <a href="https://medium.com/@pen.darkknight/building-a-conversational-ai-chatbot-with-ollama-spring-boot-and-angular-163011232461">tutorial</a>, we explored how to build a chatbot using Ollama and Spring Boot, giving you a hands-on introduction to this cutting-edge language model. Now, let’s take a deeper dive into Ollama itself. Whether you’re working on AI-driven chatbots, automating content generation, or exploring new possibilities with code assistance, Ollama is a powerful tool with endless applications. In this article, we’ll break down its core principles, structure, and technical details to show you why Ollama is a must-have in any developer’s toolkit. On y va !</p><p><strong>Understanding the core of Ollama</strong></p><p>Let’s kick things off with a fun fact: did you know that the word “Lama” in Arabic stands for Alpaca 🦙, which also happens to be the logo of Ollama? Coincidence? I think not! 😄 Maybe there’s a smart alpaca behind the scenes, helping answer all our questions.</p><p>But in reality, Ollama is much more than a charming mascot. It’s an advanced language model designed to revolutionize the way we interact with AI. From crafting code to generating content, Ollama is built on powerful principles. Let’s dive into how it all works.</p><p>At the heart of Ollama’s capabilities is the Transformer model, a groundbreaking architecture introduced in 2017. If you’ve ever wondered how Ollama can grasp complex concepts, generate text that feels natural, or respond to queries with human-like understanding, the answer lies in this model.</p><p>The Transformer’s self-attention mechanism allows it to understand the relationship between words in a sentence, even if they’re far apart. For example, it helps Ollama determine how words like “alpaca” and “lama” relate, ensuring that responses are not only accurate but also contextually appropriate.</p><p><strong>Transformers: More Than Meets the AI 🤖</strong></p><p>The Transformer model handles translation tasks by analyzing the entire input sentence all at once, rather than word by word. This is possible thanks to its self-attention mechanism, which helps it understand the relationships between words, no matter where they appear in the sentence. Let’s break it down with an example:</p><p>Imagine you’re translating the English sentence “The cat sat on the mat” into French.</p><p><strong>Input Encoding:</strong> The first step is breaking down the input sentence into individual words or tokens. The Transformer then uses positional encoding to understand the order of the words, so it knows which word comes first, second, and so on. This is crucial because in different languages, word order can change.</p><p><strong>Self-Attention Mechanism:</strong> At this stage, the model looks at each word in the sentence and checks how it relates to other words. For example, in “The cat sat on the mat,” the word “sat” is closely related to “cat” (who is doing the action), while “the mat” is the object of the action. The self-attention layer helps the model understand these relationships so it can produce a grammatically correct translation in French, where word order and structure might differ.</p><p><strong>Multi-Head Attention:</strong> The model doesn’t just look at one relationship at a time. It uses multi-head attention, where different “heads” or parts of the model focus on different aspects of the sentence. For example, one head might focus on understanding the subject (“cat”), while another might focus on the preposition (“on”) or the object (“mat”). This allows the model to capture all relevant information and ensure the translation is accurate.</p><p><strong>Decoding:</strong> After understanding the relationships in the input sentence, the Transformer generates the output sentence in the target language (French, in this case). It starts with the first word (“Le” for “The”) and uses the information learned in the encoding step to predict each subsequent word, producing the complete sentence: “Le chat s’est assis sur le tapis.”</p><p>The Transformer’s ability to look at the entire sentence at once and understand the connections between words is why it’s so effective for tasks like translation. It ensures that meaning is preserved, and the translated sentence flows naturally in the target language, even when the word order or grammar differs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*HenVxasjiKX2CKyDKM7FuQ.png" /><figcaption>The Transformer architecture</figcaption></figure><p><strong>Under the Hood: Technical Aspects of Ollama</strong></p><p>While Ollama’s ease of use is one of its strengths, it also offers powerful customization options for developers looking to fine-tune and deploy language models for specific tasks. Let’s explore some of these technical aspects.</p><ol><li><strong>Fine-Tuning Capabilities:</strong><br>Ollama shines in its ability to be fine-tuned for specific domains or industries. Whether you’re working in healthcare, finance, or tech, Ollama can be tailored to understand domain-specific language and context. This is particularly useful when building a chatbot or content generator that needs to speak the language of a particular industry. Fine-tuning can be done with minimal data, making it cost-effective and efficient to create highly specialized models.<br>The process of customizing an Ollama model typically involves the following steps:</li></ol><p><strong>Data Collection:</strong> Gather a dataset relevant to the domain or task you want the model to excel in.<br> <strong>Training:</strong> Use this dataset to fine-tune the base model, adjusting its parameters to better handle the specific language and context of your data.<br> <strong>Evaluation:</strong> Assess the performance of the customized model to ensure it meets your requirements and performs well on the targeted tasks.<br> <strong>Deployment:</strong> Once fine-tuning is complete, deploy the customized model using Ollama’s flexible deployment options, integrating it seamlessly into your applications.</p><p>2.<strong> Deployment Flexibility<br></strong>Ollama supports flexible deployment options, allowing developers to easily integrate it into their existing tech stack. It can be deployed on local servers or within a company’s infrastructure for in-house applications, or on cloud-based services for more scalable solutions. For smaller projects or those with fluctuating demand, serverless platforms like AWS Lambda or Google Cloud Functions are excellent choices, allowing for auto-scaling without managing underlying servers.</p><p><strong>3. API Integration<br></strong>For developers looking to quickly incorporate Ollama into their projects, its API integration capabilities are a major plus. With RESTful APIs, you can connect Ollama to any front-end application, whether it’s built in Angular (as demonstrated in our previous tutorial) or any other framework. The ease of API integration ensures that you can get started with Ollama without the need for deep machine learning expertise.</p><p><strong>A Pleasant Surprise: Ollama’s Web UI Tools</strong></p><p>Ollama’s backend capabilities are already well-known for their natural language processing (NLP) prowess, but what makes this platform truly exceptional is how accessible it is from the frontend as well. You don’t need to be a frontend wizard to start interacting with Ollama in a seamless and user-friendly way. Thanks to various <strong>web-based UI tools</strong>, you can harness the power of Ollama without diving deep into frontend development. Let’s explore some of the standout tools you can use:</p><ol><li><strong>Open WebUI<br></strong>Open <a href="https://github.com/open-webui/open-webui">WebUI </a>is an incredibly versatile and customizable tool designed to simplify your interaction with Ollama. It allows you to access and use Ollama’s powerful AI models through a clean and straightforward interface.</li></ol><ul><li><strong>Customizability</strong>: Open WebUI provides pre-built widgets and components that can be easily adjusted to meet your specific project requirements. You can create a tailored user experience without worrying about building everything from scratch.</li><li><strong>Quick Setup</strong>: With simple integration into Ollama’s APIs, you can get started quickly without needing extensive frontend knowledge or resources.</li><li><strong>Open-Source Advantage</strong>: As an open-source solution, Open WebUI allows developers to modify and extend the tool, fostering community-driven innovation and custom features that fit various use cases.</li></ul><p><strong>2. Ollama UI<br></strong><a href="https://github.com/ollama-ui/ollama-ui">Ollama UI</a> is specifically tailored to integrate with Ollama’s language models, making it a natural choice for those seeking a dedicated interface for working with the platform’s features. It offers a polished user experience designed to get the most out of Ollama’s capabilities.</p><ul><li><strong>User-Friendly Design</strong>: Ollama UI is designed with simplicity in mind, enabling you to interact with the AI with minimal learning curve. Its intuitive interface allows developers and non-developers alike to navigate the system effortlessly.</li><li><strong>Interactive Dashboards</strong>: The built-in dashboards provide real-time insights and data visualization, helping you monitor model performance and fine-tune interactions as needed.</li><li><strong>Built-In Functionality</strong>: Ollama UI comes with built-in tools for managing API calls, handling queries, and customizing responses, making it a one-stop solution for deploying AI models.</li></ul><p><strong>3. Hollama<br></strong><a href="https://github.com/fmaclen/hollama">Hollama </a>brings a minimalist approach to web UI design, offering a lightweight interface that makes using Ollama effortless. It is ideal for developers who need quick access to Ollama’s power without complicated setup processes.</p><ul><li><strong>No Signup Required</strong>: One of Hollama’s key selling points is its publicly hosted version, where users don’t need to create an account or deal with signup processes. It’s ready to go as soon as you open it, making it incredibly easy for new users or those looking to experiment with Ollama’s features.</li><li><strong>Data Stored Locally</strong>: Hollama prioritizes privacy and security by ensuring that all data is stored locally, which means your data remains on your device without being shared or uploaded to external servers. This makes it a great option for privacy-conscious users or those working in sensitive fields.</li><li><strong>Minimal Design, Maximum Efficiency</strong>: Hollama’s interface is designed to be as simple and efficient as possible, stripping away unnecessary features while maintaining a smooth user experience for NLP tasks.</li></ul><h4>4. Lobe Chat</h4><p><a href="https://github.com/lobehub/lobe-chat">Lobe Chat<strong> </strong></a>is a privacy-focused, local-first solution that brings a ChatGPT-like interface to Ollama. It emphasizes user privacy and local deployment, making it the go-to choice for those seeking secure, local interactions with Ollama.</p><ul><li><strong>Privacy and Security</strong>: Lobe Chat ensures all interactions happen locally, with no data being transmitted to cloud servers. This makes it an excellent choice for industries or projects that prioritize user privacy.</li><li><strong>Simple Setup</strong>: The local-first approach doesn’t mean sacrificing convenience, Lobe Chat is easy to install and run, making it a perfect balance between security and user experience.</li></ul><h4>5. Minimal LLM UI</h4><p>For users who prefer sleek, modern designs, <strong>M</strong><a href="https://github.com/richawo/minimal-llm-ui">inimal LLM UI</a> offers a clean web interface built with React, tailored for Ollama’s capabilities.</p><ul><li><strong>Clean &amp; Modern Design</strong>: Minimal LLM UI focuses on aesthetics and user-friendliness. It provides a visually appealing interface that combines simplicity and functionality, delivering a professional, elegant user experience.</li><li><strong>React Integration</strong>: Since it’s built with React, Minimal LLM UI offers flexibility in customizing the interface to meet specific project needs. Whether you need a lightweight prototype or a polished final product, Minimal LLM UI is a versatile option.</li><li><strong>Customizable &amp; Lightweight</strong>: While maintaining a minimal design, this UI provides extensive customization options, allowing developers to fine-tune the UI for their specific use cases without unnecessary bloat.</li></ul><h4>6. Additional Streamlined UI Frameworks</h4><p>Beyond these, other streamlined UI frameworks are available to make Ollama even more accessible:</p><ul><li><strong>Customizable Templates</strong>: For those who want a bit more control, several UI frameworks offer customizable templates, allowing you to design specific features for your chatbot, content generation tools, or other NLP applications.</li><li><strong>Drag-and-Drop Features</strong>: Some tools even include drag-and-drop functionality, making it easy to adjust the UI without writing extensive code. This can be particularly useful for users unfamiliar with frontend development.</li></ul><p><strong>Wrapping Up: The Alpaca and the AI Revolution</strong></p><p>As we journeyed through the world of Ollama, from its powerful Transformer-based models to the user-friendly web UI tools, it’s clear that this platform is more than just a tool, it’s a game-changer in the world of AI. Whether you’re fine-tuning models, exploring deployment options, or leveraging sleek interfaces like Open WebUI and Minimal LLM UI, Ollama proves to be a versatile and accessible choice for developers.</p><p>So, next time you interact with Ollama, picture that savvy alpaca, with its fluffy exterior and sharp intellect, guiding you through the complexities of natural language processing. With the tools and insights we’ve covered, you’re now equipped to harness the full potential of this powerful AI with ease and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c126cffcede1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Conversational AI Chatbot with Ollama, Spring Boot, and Angular]]></title>
            <link>https://medium.com/@noune.nouhaila/building-a-conversational-ai-chatbot-with-ollama-spring-boot-and-angular-163011232461?source=rss-e681432b70c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/163011232461</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Nouhaila Zahraoui]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 18:46:26 GMT</pubDate>
            <atom:updated>2024-09-08T18:46:26.383Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous article, ‘Unlocking Generative AI Power in Spring Boot Applications, we explored the potential of LLMs and RAG agents, which you can read <a href="https://medium.com/@pen.darkknight/unlocking-generative-ai-power-in-spring-boot-applications-85c15465df82"><strong><em>here</em></strong></a> . Now, let’s dive deeper into their practical implementation by creating a chatbot using Ollama, Spring Boot, and Angular.</p><p>Ollama offers a streamlined API and flexible tools, making it an excellent choice for developers to build conversational AI systems efficiently and without the heavy complexity found in some other platforms..</p><p>Before we begin, it’s important to highlight the growing prominence of large language models (LLMs) in AI today, with industry leaders like OpenAI’s ChatGPT, Google’s LaMDA, and Microsoft’s Megatron-Turing NLG.</p><p>By the end of this tutorial, you’ll have a chatbot architecture like the one shown in the schema below, demonstrating the seamless integration of Ollama, Spring Boot, and Angular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*eqAQ1f_v77m9-24TCL6vWA.png" /></figure><p>Let’s get started and bring this powerful chatbot to life!</p><h3><strong>Installing and running Ollama</strong></h3><p>There are two primary ways to install and run Ollama, depending on your preferences and project needs.</p><h4>Option 1: Downloading and Running Directly</h4><p>I chose to run Ollama directly on my device for several reasons:</p><ul><li><strong>Simplicity</strong>: For small-scale projects or prototyping, running Ollama directly can be simpler and faster to set up, especially if you’re already familiar with the underlying technology.</li><li><strong>Customization</strong>: Running directly allows for more control over the environment, enabling customization to suit specific needs.</li><li><strong>Educational Value</strong>: For those learning about Ollama or LLMs, this method offers a hands-on experience and a deeper understanding of the system.</li></ul><p>To run Ollama directly, follow these steps:</p><ol><li><strong>Download Ollama</strong>: Visit <a href="https://github.com/ollama/ollama"><strong><em>Ollama on GitHub</em></strong></a> to download the appropriate version for your operating system.</li><li><strong>Run Ollama</strong>: After downloading, use the following command to run Ollama with the “llama3.1” model:</li></ol><pre>ollama run llama3.1</pre><h4>Option 2: Using Docker Images</h4><p>If you prefer a more scalable and isolated environment, Docker images offer a great alternative. Docker simplifies deployment by providing a containerized setup, ensuring consistency across different platforms.</p><ol><li><strong>Pull the Ollama Image</strong>: Open a terminal and run the following command to download the latest Ollama image:</li></ol><pre>docker pull ollama/ollama:latest</pre><p>2. <strong>Run the Ollama Container</strong>: Start an Ollama container and run the “llama3.1” model with the following command:</p><pre>docker run -it --rm ollama/ollama:latest ollama run llama3.1</pre><p>Both methods have their advantages, and the choice depends on your project needs and personal preferences.</p><h3>Backend</h3><h4>Project Setup</h4><p>First, we need to create a new Spring Boot project using your preferred IDE (mine is IntelliJ IDEA) or the<strong><em> </em></strong><a href="https://start.spring.io/"><strong><em>Spring Initializr</em></strong></a><strong><em>.</em></strong> I chose Spring Boot because it offers robust support for building scalable applications and integrates seamlessly with Maven for easy project management and dependency handling. Its flexibility and extensive ecosystem allow smooth integration with AI tools like Ollama, enabling efficient chatbot development.</p><h4>Adding Dependencies and Properties</h4><p>Once the project is set up, open the pom.xml file to add the necessary dependencies for Spring AI and Ollama.</p><p>Start by defining the Java version and the Spring AI version to ensure compatibility across the project:</p><pre>&lt;properties&gt;<br>   &lt;java.version&gt;17&lt;/java.version&gt;<br>   &lt;spring-ai.version&gt;1.0.0-M1&lt;/spring-ai.version&gt;<br>&lt;/properties&gt;</pre><p>Next, add the spring-ai-ollama-spring-boot-starter dependency:</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>To centralize dependency management and avoid version conflicts when adding multiple Spring AI dependencies, include the BOM (Bill of Materials):</p><pre>&lt;dependencyManagement&gt;<br>   &lt;dependencies&gt;<br>       &lt;dependency&gt;<br>           &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>           &lt;artifactId&gt;spring-ai-bom&lt;/artifactId&gt;<br>           &lt;version&gt;${spring-ai.version}&lt;/version&gt;<br>           &lt;type&gt;pom&lt;/type&gt;<br>           &lt;scope&gt;import&lt;/scope&gt;<br>       &lt;/dependency&gt;<br>   &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>Lastly, add the Spring Milestones repository to fetch early releases of Spring AI components:</p><pre>&lt;repositories&gt;<br>   &lt;repository&gt;<br>       &lt;id&gt;spring-milestones&lt;/id&gt;<br>       &lt;name&gt;Spring Milestones&lt;/name&gt;<br>       &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;<br>       &lt;snapshots&gt;<br>           &lt;enabled&gt;false&lt;/enabled&gt;<br>       &lt;/snapshots&gt;<br>   &lt;/repository&gt;<br>&lt;/repositories&gt;</pre><h4>Configuring Application Properties</h4><p>Open the application.properties file and configure it to interact with Ollama:</p><pre>spring.application.name=springOllama<br>spring.ai.ollama.base-url=http://localhost:11434<br>spring.ai.ollama.chat.options.model=llama3</pre><p>This configuration sets the application name, defines the base URL for the Ollama API running locally, and specifies the LLaMA model to be used.</p><h4>Creating the Chat Service</h4><p>Now that the dependencies and properties are configured, let’s create the business logic.</p><ol><li>Create a new Java class annotated with @Service to handle the chatbot&#39;s interactions with Ollama:</li></ol><pre>@Service<br>public class ChatService {<br>   private final OllamaChatModel chatModel;<br><br>   @Autowired<br>   public ChatService(OllamaChatModel chatModel) {<br>       this.chatModel = chatModel;<br>   }<br><br>   public String generateResponse(String message) {<br>       return chatModel.call(message);<br>   }<br>}</pre><p>2. Create another class for the REST controller and annotate it with @RestController:</p><pre>@RestController<br>public class ChatController {<br>   private final ChatService chatService;<br><br>   @Autowired<br>   public ChatController(ChatService chatService) {<br>       this.chatService = chatService;<br>   }<br><br>   @GetMapping(&quot;/ai/generate&quot;)<br>   public Map&lt;String, String&gt; generate(@RequestParam(value = &quot;message&quot;,<br>   defaultValue = &quot;What&#39;s your name?&quot;) String message) {<br>       String response = chatService.generateResponse(message);<br>       return Map.of(&quot;generation&quot;, response);<br>   }<br>}</pre><h4>Configuring CORS</h4><p>To avoid cross-origin issues when connecting the frontend, configure CORS by creating a new Java class:</p><pre>@Configuration<br>public class WebConfig {<br><br>   @Bean<br>   public WebMvcConfigurer corsConfigurer() {<br>       return new WebMvcConfigurer() {<br>           @Override<br>           public void addCorsMappings(CorsRegistry registry) {<br>               registry.addMapping(&quot;/**&quot;).allowedOrigins(&quot;http://localhost:4200&quot;);<br>           }<br>       };<br>   }<br>}</pre><p>Now, you can run the backend and test the API using Postman or another API testing tool. The full backend code is available on<strong><em> </em></strong><a href="https://github.com/Nouhaila-Zahraoui/OllamaChatBotBackend.git"><strong><em>my github</em></strong></a>.</p><h3>Frontend</h3><h4>Project Setup</h4><p>To create the frontend for our chatbot, we’ll use Angular 18. I chose Angular because it provides a robust structure for developing single-page applications (SPA) and integrates seamlessly with REST APIs, such as the one we built using Spring Boot. Angular’s two-way data binding and powerful CLI simplify creating and managing a responsive, interactive UI.</p><p>To get started, create a new Angular project using the Angular CLI. If you haven’t installed the Angular CLI yet, you can do so by running the following command:</p><pre>npm install -g @angular/cli</pre><p>Then, create a new project by running:</p><pre>ng new chatbot-frontend</pre><h4>Add Dependencies and Configure API Integration</h4><p>Now that the project is set up, let’s integrate the Angular frontend with our Spring Boot backend.</p><ol><li><strong>Import HttpClientModule</strong>: Angular’s HttpClient is part of the framework, so you don’t need to install it separately. To use it, open the app.module.ts file and add the following import:</li></ol><pre>import { HttpClientModule } from &#39;@angular/common/http&#39;;</pre><p>Then, include HttpClientModule in the imports array:</p><pre>@NgModule({<br>  declarations: [],<br>  imports: [<br>    BrowserModule,<br>    HttpClientModule<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p><strong>2. Create a Chatbot Service</strong>: To manage API communication with the backend, create a new service by running:</p><pre>ng generate service chatbot</pre><p>In the newly created chatbot.service.ts file, add the following code to handle API requests:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ChatbotService {<br>  private apiUrl = &#39;http://localhost:8080/ai/generate&#39;;<br><br>  constructor(private http: HttpClient) {}<br><br>  generateResponse(message: string): Observable&lt;any&gt; {<br>    return this.http.get&lt;any&gt;(`${this.apiUrl}?message=${message}`);<br>  }<br>}</pre><p>This service handles the interaction with the backend API, sending the user’s message and receiving the chatbot’s response.</p><h4>Create the Chat Component</h4><p>Next, we’ll create the UI component that will handle user interactions and communicate with the chatbot service.</p><ol><li><strong>Generate the Chat Component</strong>: Run the following command to create the chat component:</li></ol><pre>ng generate component chat</pre><p>In the generated chat.component.ts file, add the following logic for handling messages:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { ChatbotService } from &#39;../chatbot.service&#39;;<br>import { faPaperPlane } from &#39;@fortawesome/free-solid-svg-icons&#39;;<br><br>@Component({<br>  selector: &#39;app-chat&#39;,<br>  templateUrl: &#39;./chat.component.html&#39;,<br>  styleUrls: [&#39;./chat.component.css&#39;]<br>})<br>export class ChatComponent {<br>  value: string = &#39;&#39;;<br>  messages = [{ author: &#39;bot&#39;, content: &#39;Welcome to ChatCat!&#39; }];<br>  faPaperPlane = faPaperPlane;<br><br>  constructor(private chatService: ChatbotService) {}<br><br>  sendMessage() {<br>    if (this.value.trim()) {<br>      this.messages.push({ author: &#39;user&#39;, content: this.value });<br>      this.chatService.generateResponse(this.value).subscribe(<br>        (response) =&gt; {<br>          this.messages.push({ author: &#39;bot&#39;, content: response.generation });<br>        },<br>        (error) =&gt; {<br>          console.error(&#39;Error fetching response from backend:&#39;, error);<br>        }<br>      );<br>      this.value = &#39;&#39;;<br>    }<br>  }<br>}</pre><p><strong>2. Update the Chat Component Template</strong>: In chat.component.html, create the chat interface:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;chat-section&quot;&gt;<br>    &lt;div class=&quot;header&quot;&gt;<br>      &lt;img src=&quot;../src/app/images/kitty.png&quot; alt=&quot;CatChat Logo&quot; class=&quot;logo&quot;&gt;<br>      &lt;h1&gt;ChatCat&lt;/h1&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;message-container&quot;&gt;<br>      &lt;ng-container *ngFor=&quot;let message of messages&quot;&gt;<br>        &lt;div class=&quot;message&quot; [ngClass]=&quot;{ &#39;to&#39;: message.author === &#39;bot&#39;, &#39;from&#39;: message.author === &#39;user&#39; }&quot;&gt;<br>          &lt;ng-container *ngIf=&quot;message.author === &#39;user&#39;&quot;&gt;<br>            &lt;div class=&quot;message-content-wrapper&quot;&gt;<br>              &lt;div class=&quot;message-content&quot;&gt;{{ message.content }}&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/ng-container&gt;<br>          &lt;ng-container *ngIf=&quot;message.author === &#39;bot&#39;&quot;&gt;<br>            &lt;div class=&quot;message-content-wrapper&quot;&gt;<br>              &lt;div class=&quot;avatar&quot;&gt;<br>                &lt;img src=&quot;../src/app/images/kitty.png&quot; alt=&quot;Bot Avatar&quot;&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;message-content&quot;&gt;{{ message.content }}&lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/ng-container&gt;<br>        &lt;/div&gt;<br>      &lt;/ng-container&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;chat-input-container&quot;&gt;<br>      &lt;input [(ngModel)]=&quot;value&quot; (keyup.enter)=&quot;sendMessage()&quot; type=&quot;text&quot; class=&quot;styled-input&quot; placeholder=&quot;Type your message here...&quot;&gt;<br>      &lt;fa-icon [icon]=&quot;faPaperPlane&quot; class=&quot;send-icon&quot; (click)=&quot;sendMessage()&quot;&gt;&lt;/fa-icon&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>The template creates a basic chat interface where user and bot messages are displayed in a chat bubble format, and it includes an input field for sending messages.</p><h4>Conclusion</h4><p>With the frontend set up and connected to the backend, you can now run the application and interact with your chatbot. The full frontend code, including the CSS styles and additional components, is available on <a href="https://github.com/Nouhaila-Zahraoui/OllamaChatBotFrontend.git"><strong><em>GitHub</em></strong></a><strong><em>.</em></strong></p><p>The final UI (after adding css) should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1dKb5vf2FTfqf-CsQ6Vhg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163011232461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Generative AI Power in Spring Boot Applications]]></title>
            <link>https://medium.com/@noune.nouhaila/unlocking-generative-ai-power-in-spring-boot-applications-85c15465df82?source=rss-e681432b70c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/85c15465df82</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nouhaila Zahraoui]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 18:30:32 GMT</pubDate>
            <atom:updated>2024-07-24T18:30:32.059Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of Artificial Intelligence (AI) is rapidly evolving, with Generative AI at the forefront of this revolution. Python stands as a giant to the creation of strong Large Language Models (LLMs) such as GPT and Llama, these models are not basically restricted to Python applications only. There is good news that other programming languages have capacity to use these LLMs for increased functionality. Nevertheless, your integration method may vary according to your programming language and framework.</p><p>Let’s explore how Java software engineers can harness the power of Generative AI, focusing on Large Language Models (LLMs) and Retrieval-Augmented Generation (RAG) agents, and their integration into Spring Boot applications.</p><h4>Generative AI: A New Frontier</h4><p>Generative AI refers to a subfield of AI that creates new data, often in the form of text, code, or images. This capability unlocks exciting possibilities for various applications. Java developers, familiar with Spring Boot’s development framework, can leverage Generative AI to enhance their applications in innovative ways.</p><h4>LLMs: The Powerhouse of Generative AI</h4><p>Large Language Models (LLMs) are a type of Generative AI model trained on massive amounts of text data. They can generate human-quality text, translate languages, write creative content, and answer questions informatively. Imagine integrating an LLM into your Spring Boot application to automatically generate marketing copy, translate user interfaces, or create chatbot responses.</p><h4>RAG Agents: Bridging the Gap Between User and LLM</h4><p>While LLMs are powerful, interacting with them directly can be challenging. Retrieval-Augmented Generation (RAG) agents act as intermediaries, understanding user queries and retrieving relevant information from a knowledge base before feeding it to the LLM for refined text generation. This approach ensures the LLM receives the proper context for accurate and relevant outputs. In a Spring Boot application, a RAG agent could bridge the gap between a user’s search query and the LLM, providing more focused and informative results.</p><h4>Spring Boot and Generative AI: A Perfect Match</h4><p>Spring Boot offers a robust and efficient framework for building modern Java applications. Its ability to integrate with various external services and libraries makes it ideal for incorporating Generative AI models like LLMs and RAG agents.</p><h4>Prompt Engineering: The Key to Unlocking Potential</h4><p>Prompt engineering is a crucial aspect of working with Generative AI models. It involves crafting clear and concise instructions that guide the LLM towards the desired output. As Java developers, mastering prompt engineering allows us to leverage the full potential of LLMs within our Spring Boot applications.</p><h4>Beyond the Hype: Practical Applications</h4><p>Generative AI offers more than just novelty. Here are some practical applications for Java developers using Spring Boot:</p><ul><li><strong>Automated Content Generation</strong>: Generate product descriptions, marketing copy, or code documentation.</li><li><strong>Enhanced Chatbots</strong>: Create more natural and informative chatbot interactions.</li><li><strong>Personalized User Experiences</strong>: Tailor content and recommendations based on user data.</li><li><strong>Data Augmentation</strong>: Generate synthetic data for training other AI models.</li></ul><h4>Spring Boot’s Versatility: Interaction Across Languages</h4><p>One of Spring Boot’s strengths is its ability to interact with libraries and frameworks written in various programming languages. This is crucial because many Generative AI models, like GPT-3, are primarily developed in Python. Spring Boot allows Java developers to bridge the language gap and seamlessly integrate these models into their Java applications.</p><h4>Conclusion</h4><p>The world of Generative AI is brimming with possibilities for Java developers. By leveraging Spring Boot’s integration capabilities and understanding concepts like LLMs, RAG agents, and prompt engineering, they can create innovative and intelligent applications that push the boundaries of what’s possible.</p><p><strong>Summary:</strong></p><p>How You Can Exploit the Power of Generative AI in Your Spring Boot Applications Artificial Intelligence (AI) is changing fast, and Generative AI is one of the lead players in this game. In this article we have discussed how Java software engineers can tap into the power of Generative AI, specifically Large Language Models (LLMs) and Retrieval-Augmented Generation (RAG) agents that are built into Spring Boot applications.</p><p>Generative AI: A New Frontier Generative AI refers to a subfield of AI that creates new data, often in the form of text, code, or images. This capability unlocks exciting possibilities for various applications. Java developers who are familiar with Spring Boot’s solid development architecture may use Generative AI in innovative ways to enhance their applications.</p><p>LLMs: The Powerhouse of Generative AI LLMs are a category on their own within Generative AI models and were trained on vast amounts of textual data. These models can generate human-like text, translate languages, write creatively and provide informative answers when questioned. Just imagine integrating an LLM into your Spring Boot application so as to generate marketing copies automatically, translate GUIs or even produce chatbot speech. RAG Agents: Bridging the Gap Between User and LLM While LLMs are powerful, their direct interaction can be complicated. Retrieval-Augmented Generation (RAG) agents act as mediators between users and LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*XAycA-0xp5rsMAfk4ehLkw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85c15465df82" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>