<?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 Sifayathf on Medium]]></title>
        <description><![CDATA[Stories by Sifayathf on Medium]]></description>
        <link>https://medium.com/@sifayathf?source=rss-f76f9c8b15ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jYDmXHVjopWgm0Wf</url>
            <title>Stories by Sifayathf on Medium</title>
            <link>https://medium.com/@sifayathf?source=rss-f76f9c8b15ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:41:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sifayathf/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[Teaching a Tiny LLM Your Own Documents: A Fine-Tuning Story]]></title>
            <link>https://medium.com/@sifayathf/teaching-a-tiny-llm-your-own-documents-a-fine-tuning-story-4addc017ba1d?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/4addc017ba1d</guid>
            <category><![CDATA[llm-finetuning]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[llm-guardrails]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 12:09:54 GMT</pubDate>
            <atom:updated>2026-10-03T12:09:54.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRT2oy7pwelXt8yG1zileQ.png" /><figcaption>Train your own LLM with in 10 minutes using Colab</figcaption></figure><h3>It started with a PDF nobody reads</h3><p>Every company has one. A troubleshooting guide, a policy manual, a product handbook. It is 80 pages long, it was last updated two quarters ago, and it holds the answer to almost every question your support team gets.</p><p>And yet the same questions keep coming. “What does error E-102 mean?” “How much of my juniors expenses or telephone bill can I approve without a supervisor?” “What is the reset procedure for the router?” Agents search, scroll, guess, and escalate.</p><p>So I asked myself a simple question. What if a small AI model could just <em>know</em> that document? Not a giant cloud model that sends our data somewhere else. A tiny, open-source model that runs on a laptop and answers like someone who has read the manual cover to cover.</p><p>My first attempt was a disaster, and honestly that is where the real learning began. I fed the model my own resume as a test document. I asked it about my background. It confidently told me I was a Certified Public Accountant with 15 years in retail finance. I am an AI architect. The model had not learned a single fact. It had simply made things up, fluently and with total confidence.</p><p>This article is the story of how I went from that embarrassing answer to a model that actually answers from the document. Along the way I will explain what fine-tuning is, why you might want it, what it unlocks, and why each piece of the code looks the way it does.</p><p>For the impatient techie, the github link is provided at the bottom of this article. So you can scroll down and download the ipynb… hahaha.</p><h3>The problem statement</h3><p>Here is the problem in one sentence: <strong>general-purpose chatbots know the world, but they do not know your company.</strong></p><p>If you ask a public model about your internal error codes, your refund policy, or your escalation matrix, and one of two things happens. It either admits it does not know, or worse, it invents something plausible. In a call center, a plausible but wrong troubleshooting step is more dangerous than no answer at all.</p><p>Then you need to train your call center employee how to reject nonsense coming out of AI after training them how to use AI. Two steps additional for the same problem, which was solved using a problem or service manual.</p><p>There are three practical walls most teams hit:</p><ul><li><strong>Privacy.</strong> Many company documents cannot be pasted into a public chatbot. Contracts, customer procedures and internal pricing need to stay inside.</li><li><strong>Cost and scale.</strong> Calling a large hosted model thousands of times a day adds up quickly, and so does latency.</li><li><strong>Behaviour.</strong> You want the assistant to answer in your tone, follow your format, and say “this is not in our documentation” instead of improvising.</li></ul><p>So the goal I set was concrete. Take any document (PDF, Word or text), and produce a small open-source model that answers questions about it accurately, refuses politely when the answer is not there, and runs locally without a GPU once trained.</p><h3>Why train your own LLM at all?</h3><p>Before writing any code, it is worth being honest about the options. You do not always need fine-tuning. There are really three ways to get your document into a model’s answers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ZkSRIAd0h2sXmQ_m8cTg_g.png" /></figure><p>The surprise for me was that these are not rivals. Fine-tuning shines at teaching <em>behaviour</em>: how to answer, what format to use, when to say “I don’t know”. Retrieval shines at supplying <em>facts</em> exactly as written. The best setup I found uses both, and my results later in this article show why.</p><p>So why fine-tune a small model instead of just using a big one with retrieval?</p><ul><li><strong>It runs anywhere.</strong> A 0.5 billion parameter model, compressed, is under half a gigabyte. It runs on a laptop CPU, inside a private network, or on an edge device.</li><li><strong>Your data stays home.</strong> Training and inference can happen entirely inside your infrastructure.</li><li><strong>It is cheap.</strong> I trained on a free Google Colab GPU in a couple of minutes.</li><li><strong>You own the behaviour.</strong> The model learns your refusal sentence, your tone and your domain vocabulary, and nobody can change that behaviour under you with a silent update.</li></ul><h3>The vocabulary, in plain words</h3><p>The fine-tuning world is full of acronyms. Here are the only ones you need for this project.</p><p><strong>SFT (Supervised Fine-Tuning).</strong> You show the model pairs of “question” and “ideal answer” and nudge its weights so it produces that answer next time. Think of it as flashcards for a language model.</p><p><strong>PEFT (Parameter-Efficient Fine-Tuning).</strong> Instead of retraining every one of the model’s hundreds of millions of weights, you freeze them and train a small add-on. It is faster, cheaper, and the model forgets less of what it already knew.</p><p><strong>LoRA (Low-Rank Adaptation).</strong> The most popular PEFT method. It attaches thin “adapter” matrices to the model’s layers. In my runs only about 1.75% of the parameters were trainable, roughly 8.8 million out of 500 million.</p><p><strong>QLoRA.</strong> LoRA on top of a model that has been compressed to 4-bit numbers. Memory use drops dramatically, which is why all of this fits on a free GPU.</p><p><strong>Teacher and student.</strong> A slightly larger model (the teacher) reads the document and writes practice questions and answers. A tiny model (the student) learns from them. The teacher is thrown away afterwards; the student is what you ship.</p><p><strong>GGUF.</strong> A file format for running compressed models on ordinary computers with tools like llama.cpp, LM Studio or Ollama. It is the “export to PDF” of the model world.</p><h3>Three mistakes that taught me more than any tutorial</h3><p>I want to share the failures first, because almost every beginner notebook online makes at least one of them.</p><p><strong>Mistake 1: training on one giant example.</strong> My first notebook had exactly one training example. The question was “Tell me about the candidate” and the answer was the entire resume pasted in. Fifteen training steps later, the model still invented a career in accounting. A model does not learn facts from reading a wall of text once. It learns them from many small question and answer pairs, each about one fact, each phrased in several ways.</p><p><strong>Mistake 2: silently cutting off the document.</strong> The resume was about 2,900 tokens long, but the training setting capped sequences at 2,048 tokens. The whole second half of my career, and the token that tells the model “stop talking here”, were simply chopped off. No error, no warning. Always check how long your examples really are.</p><p><strong>Mistake 3: the model that refused everything.</strong> This one was sneaky. In a later attempt I had 20 real questions and answers plus 4 “out of scope” questions, all answered with the same sentence: “The provided document does not contain this information.” After training, the model answered <em>every</em> question with that sentence. Why? The 20 real answers were all different, but the refusal was the single most repeated answer in the data. For a small model, it became the safest bet. On top of that, the system prompt told the model to use “the provided context”, and no context was ever provided, so the model was effectively told it had nothing to work with.</p><p>The lesson behind all three: <strong>fine-tuning is mostly a data problem.</strong> The training code is the easy part. What you put in front of the model, and in what proportions, decides everything.</p><h3>The pipeline that finally worked, and why each piece looks the way it does</h3><p>The working notebook runs on a free Colab T4 GPU. It reads the document, chunks it, lets a teacher write questions, filters out invented answers, splits into train and test, fine-tunes the student, then evaluates and exports. Here are the choices that matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsZoSHQBGXIW3wI2lv-VaA.png" /></figure><p>The teacher only writes and filters data; the held-out test questions bypass training so the evaluation stays honest.</p><h3>1. Read any document, decided by content, not file name</h3><pre>def detect_format(path):<br>    head = open(path, &quot;rb&quot;).read(8)<br>    if head.startswith(b&quot;%PDF&quot;):<br>        return &quot;pdf&quot;<br>    if head.startswith(b&quot;PK\x03\x04&quot;):   # a .docx is really a zip file<br>        return &quot;docx&quot;<br>    return &quot;text&quot;</pre><p><strong>Why:</strong> my own notebook once crashed because a Word file was passed to a PDF reader. Looking at the first bytes of the file is more reliable than trusting the extension. For Word files, the code walks paragraphs <em>and</em> tables in document order, because designed resumes and manuals often hide all their content inside a layout table.</p><h3>2. Chunk with a sliding window</h3><pre>CHUNK_WORDS, CHUNK_OVERLAP = 400, 50</pre><p><strong>Why:</strong> 400 words is enough context for the teacher to write meaningful questions, and small enough to stay focused on one topic. The 50-word overlap means a fact that sits on a chunk boundary still appears whole in at least one chunk.</p><h3>3. A teacher writes the training data, in batches</h3><pre>TEACHER_MODEL = &quot;unsloth/Qwen2.5-1.5B-Instruct&quot;<br>STUDENT_MODEL = &quot;unsloth/Qwen2.5-0.5B-Instruct&quot;<br>QA_PER_CHUNK, N_PARAPHRASES = 4, 2</pre><p><strong>Why two models?</strong> The smallest model is what we want to ship, but it is not reliable at writing structured JSON. A slightly bigger teacher writes better questions, then gets deleted from memory before training starts. Each fact comes with paraphrases (“What does E-102 mean?”, “What is error E-102?”) because a model that has only seen one wording will not recognise the question when a real user phrases it differently. All chunks are sent to the teacher in batches of 8 instead of one at a time, which is the single biggest speed win in the notebook.</p><h3>4. A real hallucination filter</h3><pre>def validate(pair, chunk_text):<br>    src = norm(chunk_text)<br>    if any(n not in src for n in numbers(pair[&quot;answer&quot;])):<br>        return False, &quot;number not in source&quot;<br>    if any(norm(e) not in src for e in entities(pair[&quot;answer&quot;])):<br>        return False, &quot;entity not in source&quot;<br>    ...</pre><p><strong>Why:</strong> teachers hallucinate too. If an answer mentions “24 months” or “Tier 2” and those words are not in the chunk it came from, the pair is thrown away. In my test runs, planted fake answers containing invented numbers were rejected every time. My earlier filter only checked whether <em>any one</em> long word overlapped, which let almost anything through.</p><h3>5. Balanced refusals</h3><pre>REFUSAL_SHARE = 0.12   # refusals as a share of training examples</pre><p><strong>Why:</strong> this is the direct fix for mistake 3. Refusals teach the model to say “not in the document” for off-topic questions, but if they dominate, refusing becomes the default. Around 10 to 15 percent works well. The refusal questions themselves are checked against the document so a question the document <em>can</em> answer never ends up labelled as a refusal.</p><h3>6. Split by fact, so the test is honest</h3><p>One paraphrase of every fact is held back from training. The test then asks the trained fact in words the model has never seen. A separate 15 percent of facts is never trained at all, which shows how the model behaves on things it truly does not know.</p><h3>7. Train only on the answers</h3><pre>labels = [-100] * len(prompt_ids) + full_ids[len(prompt_ids):]</pre><p><strong>Why:</strong> the value -100 tells the trainer to ignore those tokens when computing the loss. So the model is never graded on repeating the system prompt or the question, only on producing the answer and the end-of-answer token. That end token matters: it is how the model learns when to stop talking. I also use the tokenizer’s own chat template instead of hand-typing the special tags, because one typo in a tag (I had &lt;|im_end|u003E in an early version) teaches the model to print garbage.</p><h3>8. Small LoRA, a few epochs</h3><pre>model = FastLanguageModel.get_peft_model(<br>    model, r=16, lora_alpha=32,<br>    target_modules=[&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,<br>                    &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;],<br>    use_gradient_checkpointing=&quot;unsloth&quot;)</pre><p><strong>Why:</strong> rank 16 with alpha 32 is a well-tested default. Targeting both the attention layers and the feed-forward layers gives the adapter enough room to store facts, not just style. Unsloth handles the 4-bit loading and memory tricks, which is what makes a free T4 enough.</p><h3>9. Export to GGUF and ask locally</h3><pre>model.save_pretrained_gguf(&quot;gguf_model&quot;, tokenizer, quantization_method=[&quot;q4_k_m&quot;, &quot;q8_0&quot;])</pre><pre>llm = Llama(model_path=&quot;doc-assistant-q4_k_m.gguf&quot;, n_ctx=4096)<br>llm.create_chat_completion(messages=build_messages(question, context), temperature=0)</pre><p><strong>Why:</strong> q4_k_m is small and fast with a minor quality cost; q8_0 is almost lossless. The notebook also writes an Ollama Modelfile, so ollama create doc-assistant -f Modelfile turns the result into a local chat assistant in one command. Temperature 0 keeps factual answers deterministic.</p><h3>Results, and how to measure them honestly</h3><p>The best setup, the fine-tuned student with relevant excerpts in the prompt, scored a word-overlap F1 of 0.85 on reworded questions, more than double the untouched base model’s 0.40.</p><p>These numbers come from one run on the notebook’s demo document, a short appliance manual, on a free T4. Training itself took 47 seconds. The test set is small, so treat the numbers as directional, not as a benchmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*pzw1hSMPpT7R4Lz343bu6Q.png" /></figure><p>Three things stand out:</p><ol><li><strong>Fine-tuning clearly helped.</strong> On facts it was trained on, the fine-tuned model jumped from 0.40 to 0.61 even with no document in sight.</li><li><strong>Fine-tuning alone is not enough for exact facts.</strong> It recalled only about half the key numbers and names. A 0.5B model holds the gist better than the details.</li><li><strong>The combination wins.</strong> The fine-tuned model already knows the tone, the format and the refusal behaviour; the retrieved excerpts supply the exact facts. Together they beat either approach on its own.</li></ol><p>How do you know your answers are accurate? These are the checks I would insist on before trusting any fine-tuned model:</p><ul><li><strong>Always measure the base model first.</strong> Without a baseline you cannot claim the training did anything.</li><li><strong>Test on paraphrases, never on the training questions.</strong> A model repeating its flashcards proves nothing.</li><li><strong>Track key facts, not just word overlap.</strong> For troubleshooting, getting the error code or the number wrong is what hurts. The notebook checks whether numbers and names from the reference answer appear in the model’s answer.</li><li><strong>Measure refusals in both directions.</strong> Off-topic questions should be refused, and real questions should not be. My refuse-everything model would have looked perfect on one of those metrics and useless on the other.</li><li><strong>Read the worst answers yourself.</strong> Metrics are a proxy. Ten minutes reading wrong answers teaches you more than any score.</li></ul><h3>What this opens up</h3><p>Once you can turn a document into a small, private, local model in an afternoon, a lot of doors open. A few I find genuinely exciting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*AAjo8a3D7TdCywJz7DGDjQ.png" /></figure><p>Beyond single documents, the same pattern scales up. Fine-tuning can teach a model a domain’s vocabulary (telecom, insurance, logistics), a fixed output format (JSON for a downstream system, a ticket template), or a language pair (questions in Spanish, answers in English). The synthetic Q&amp;A step is reusable too: the dataset it produces is a ready-made evaluation set for any future model you try.</p><p>And because the result is a GGUF file, deployment is boring in the best way. It runs in Ollama on a laptop, in llama.cpp on a server, and the notebook’s merged 16-bit export can sit behind vLLM if you need throughput.</p><h3>What I would tell my past self</h3><p>If you take one thing from this story, make it this: the model was never the hard part. The data was.</p><ul><li><strong>Many small facts beat one big document.</strong> Break the source into question and answer pairs, one fact each, several wordings each.</li><li><strong>Watch the proportions.</strong> Whatever answer appears most often in your data becomes the model’s default. Keep refusals around 10 to 15 percent.</li><li><strong>Never trust the teacher blindly.</strong> Filter generated answers against the source text.</li><li><strong>Test the way users will ask.</strong> Paraphrased questions, off-topic questions, and a baseline to compare against.</li><li><strong>Use fine-tuning for behaviour and retrieval for facts.</strong> Together they are much stronger than either alone.</li></ul><p>The whole pipeline lives in a single Colab notebook that runs on a free T4 GPU. Upload a PDF, Word or text file, press <em>Run all</em>, and you get a small model, an evaluation table and a GGUF file you can run with Ollama on your own laptop. The code is on GitHub at <a href="https://github.com/sifayathf/llmfinetuning/blob/claude/llm-finetuning-pdf-c9dvif/Universal_Document_Fine_Tuner_(Unsloth_%2B_QLoRA).ipynb">https://github.com/sifayathf/llmfinetuning/blob/claude/llm-finetuning-pdf-c9dvif/Universal_Document_Fine_Tuner_(Unsloth_%2B_QLoRA).ipynb</a>.</p><p>Start with a document your team actually uses. Ask it the questions people really ask. And when your first model tells you that you are an accountant, smile: you are about to learn something.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4addc017ba1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building Autonomous System Monitoring with MCP: Real-Time OS Health Tracking for Manufacturing…]]></title>
            <link>https://medium.com/@sifayathf/building-autonomous-system-monitoring-with-mcp-real-time-os-health-tracking-for-manufacturing-b5e8f2e95333?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e8f2e95333</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 09:10:18 GMT</pubDate>
            <atom:updated>2026-03-30T09:10:18.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>🏭 Building Autonomous System Monitoring with MCP: Real-Time OS Health Tracking for Manufacturing AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfAVN2iuKM7nIuTM1dI6Ww.png" /></figure><h3>🚀 Introduction</h3><p>In modern manufacturing environments, <strong>factory controller machines (often Windows/Linux-based systems)</strong> are the backbone of operations.</p><p>But here’s the challenge:</p><p>❌ No real-time visibility into system health<br> ❌ Downtime detection is reactive<br> ❌ Manual monitoring leads to delays and failures</p><h3>💡 What if systems could monitor themselves?</h3><p>This is where <strong>Model Context Protocol (MCP) + Autonomous Agents</strong> come into play.</p><p>👉 I recently built a <strong>lightweight MCP-based system monitor</strong> that can:</p><ul><li>Track CPU usage</li><li>Monitor memory consumption</li><li>Analyze disk health</li><li>Expose real-time system state via APIs</li></ul><p>And more importantly:</p><blockquote><em>🔥 This becomes the foundation for </em><strong><em>Autonomous Factory Monitoring Systems</em></strong></blockquote><h3>💡Core Idea</h3><p>Instead of:</p><blockquote><em>Humans checking machines ❌</em></blockquote><p>We move to:</p><blockquote><em>AI agents continuously monitoring and acting ✅</em></blockquote><h3>⚙️ MCP-Based System Monitoring</h3><p>Below is the core implementation using MCP tools:</p><pre>from fastmcp import FastMCP<br>import psutil</pre><pre>mcp = FastMCP(&quot;linux-monitor&quot;)</pre><pre>@mcp.tool()<br>def cpu_usage():<br>    &quot;&quot;&quot;Get current CPU usage percentage&quot;&quot;&quot;<br>    return {&quot;cpu_percent&quot;: psutil.cpu_percent(interval=1)}</pre><pre>@mcp.tool()<br>def memory_usage():<br>    &quot;&quot;&quot;Get RAM usage&quot;&quot;&quot;<br>    mem = psutil.virtual_memory()<br>    return {<br>        &quot;total&quot;: mem.total,<br>        &quot;used&quot;: mem.used,<br>        &quot;percent&quot;: mem.percent<br>    }</pre><pre>@mcp.tool()<br>def disk_usage():<br>    &quot;&quot;&quot;Get disk usage for root&quot;&quot;&quot;<br>    disk = psutil.disk_usage(&#39;/&#39;)<br>    return {<br>        &quot;total&quot;: disk.total,<br>        &quot;used&quot;: disk.used,<br>        &quot;percent&quot;: disk.percent<br>    }</pre><pre>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;http&quot;, port=8000)</pre><p>📌 Source:</p><p>main.py</p><h3>🔍 What this code does</h3><ul><li>Exposes system metrics as <strong>MCP tools</strong></li><li>Makes them callable by:</li><li>AI agents</li><li>Orchestrators (LangGraph)</li><li>External monitoring systems</li></ul><h3>🏗️ Architecture: Autonomous Factory Monitoring</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*r4VaQAJ_8mPar0RE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*4ur-m7XAy9Cq1l5F.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*P74rB2u4WaPzW-mH.png" /></figure><h3>🔄 Flow</h3><pre>Factory Machine (Windows/Linux)<br>        ↓<br>MCP Agent (System Metrics)<br>        ↓<br>LangGraph Orchestrator<br>        ↓<br>AI Decision Engine<br>        ↓<br>Alert / Auto-Remediation</pre><h3>🧠 How this becomes Autonomous</h3><h3>Step 1: Data Collection</h3><ul><li>CPU / Memory / Disk via MCP</li></ul><h3>Step 2: State Management</h3><ul><li>Stored in LangGraph state</li></ul><h3>Step 3: Decision Logic</h3><ul><li>Detect anomalies:</li><li>CPU &gt; 90%</li><li>Memory leak</li><li>Disk nearing full</li></ul><h3>Step 4: Action</h3><ul><li>Send alert</li><li>Restart service</li><li>Trigger workflow</li></ul><h3>🔥 Real Manufacturing Use Case</h3><h3>🏭 Scenario: Factory Controller Machine</h3><ul><li>Runs on Windows/Linux</li><li>Controls production line</li><li>Critical for uptime</li></ul><h3>Problem:</h3><ul><li>System slowdown → production delay</li><li>Disk full → machine crash</li><li>CPU overload → process failure</li></ul><h3>✅ Solution with MCP + AI</h3><ul><li>Continuous monitoring</li><li>AI-based anomaly detection</li><li>Automated remediation</li></ul><p>👉 Result:</p><ul><li>Reduced downtime</li><li>Predictive maintenance</li><li>Increased operational efficiency</li></ul><h3>🤖 Integrating with LangGraph (Agentic Layer)</h3><p>You can plug MCP tools into LangGraph:</p><pre>def monitor_node(state):<br>    cpu = cpu_usage()<br>    <br>    if cpu[&quot;cpu_percent&quot;] &gt; 85:<br>        return {&quot;alert&quot;: &quot;High CPU detected&quot;}<br>    <br>    return {&quot;status&quot;: &quot;healthy&quot;}</pre><p>👉 This enables:</p><ul><li>Autonomous decision-making</li><li>Stateful monitoring</li><li>Continuous loops</li></ul><h3>⚡ Advanced Capabilities</h3><h3>🔹 Multi-Machine Monitoring</h3><ul><li>Deploy MCP agents across factory nodes</li></ul><h3>🔹 Central AI Brain</h3><ul><li>LangGraph orchestrates decisions</li></ul><h3>🔹 Predictive Insights</h3><ul><li>Use historical trends</li></ul><h3>🔹 Auto-Healing Systems</h3><ul><li>Restart processes</li><li>Scale workloads</li></ul><h3>🧪 Beyond Manufacturing</h3><p>This approach applies to:</p><ul><li>🏥 Healthcare systems monitoring</li><li>🏦 Telecom infrastructure</li><li>☁️ Cloud system observability</li><li>🤖 Autonomous IT operations (AIOps)</li></ul><h3>⚠️ Challenges</h3><ul><li>Security (agent access control)</li><li>Network latency</li><li>Data consistency</li><li>Scaling MCP endpoints</li></ul><h3>🏁 Conclusion</h3><p>We are moving from:</p><blockquote><em>Monitoring dashboards ❌<br> ➡️<br> </em><strong><em>Autonomous AI-driven system management</em></strong><em> ✅</em></blockquote><h3>💡 Key Insight</h3><blockquote><em>MCP + LangGraph = Foundation for Autonomous Infrastructure</em></blockquote><h3>📌 TL;DR</h3><ul><li>MCP exposes system metrics as tools</li><li>LangGraph enables decision orchestration</li><li>Together → Autonomous monitoring systems</li><li>Critical for manufacturing environments</li></ul><h3>🚀 Final Thought</h3><p>The future factory won’t just be automated…</p><p>👉 It will be <strong>self-aware and self-healing</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e8f2e95333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering LangGraph: State Management, Data Passing & Image Handling in AI Workflows]]></title>
            <link>https://medium.com/@sifayathf/mastering-langgraph-state-management-data-passing-image-handling-in-ai-workflows-05d7a0f1da41?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/05d7a0f1da41</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 21:02:50 GMT</pubDate>
            <atom:updated>2026-03-28T21:02:50.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ER99pB2E5m1LzAf2VQJSfA.png" /></figure><h3>🚀 Introduction</h3><p>As GenAI systems evolve, orchestrating multi-step reasoning workflows has become critical. Traditional chains fall short when workflows require:</p><ul><li>Stateful execution</li><li>Conditional branching</li><li>Multi-modal data handling (text + images)</li><li>Memory across steps</li></ul><p>This is where <strong>LangGraph</strong> shines.</p><p>In this article, we’ll explore:</p><ul><li>How LangGraph manages <strong>state</strong></li><li>Passing <strong>data across nodes</strong></li><li>Handling <strong>images via state variables</strong></li><li>Building a <strong>real-world orchestrator</strong></li></ul><h3>🧩 What is LangGraph?</h3><p>LangGraph is a <strong>stateful orchestration framework</strong> built on top of LangChain that enables:</p><ul><li>Directed graph-based workflows</li><li>Persistent state across nodes</li><li>Conditional routing</li><li>Multi-step AI pipelines</li></ul><p>Think of it as a <strong>workflow engine for LLM applications</strong>.</p><h3>🔑 Core Concept: State</h3><p>In LangGraph, <strong>state is the backbone</strong>.</p><p>Instead of passing variables manually between functions, LangGraph uses a <strong>central shared state object</strong>.</p><h3>Example State Schema</h3><pre>from typing import TypedDict, Optional</pre><pre>class GraphState(TypedDict):<br>    user_input: str<br>    processed_text: Optional[str]<br>    image_path: Optional[str]<br>    image_description: Optional[str]<br>    final_output: Optional[str]</pre><p>👉 Every node reads from and writes to this shared state.</p><h3>🔄 How State Flows</h3><pre>User Input → Text Processing → Image Processing → Final Response</pre><p>Each node:</p><ul><li>Receives state</li><li>Updates specific fields</li><li>Passes it forward</li></ul><h3>🏗️ Building a LangGraph Orchestrator</h3><p>Let’s implement a real example:</p><h3>🎯 Scenario</h3><p>User provides:</p><ul><li>Text prompt</li><li>Optional image</li></ul><p>System:</p><ol><li>Processes text</li><li>Analyzes image</li><li>Combines both</li></ol><h3>⚙️ Step 1: Install Dependencies</h3><pre>pip install langgraph langchain openai pillow</pre><h3>🎯 Step 2: Define Nodes</h3><h3>📝 Text Processing Node</h3><pre>def process_text(state: dict):<br>    user_input = state[&quot;user_input&quot;]</pre><pre>    processed = f&quot;Processed Text: {user_input.upper()}&quot;</pre><pre>    return {<br>        &quot;processed_text&quot;: processed<br>    }</pre><h3>🖼️ Image Processing Node</h3><pre>from PIL import Image</pre><pre>def process_image(state: dict):<br>    image_path = state.get(&quot;image_path&quot;)</pre><pre>    if not image_path:<br>        return {&quot;image_description&quot;: &quot;No image provided&quot;}</pre><pre>    try:<br>        img = Image.open(image_path)<br>        description = f&quot;Image size: {img.size}, mode: {img.mode}&quot;</pre><pre>        return {<br>            &quot;image_description&quot;: description<br>        }<br>    except Exception as e:<br>        return {<br>            &quot;image_description&quot;: f&quot;Error processing image: {str(e)}&quot;<br>        }</pre><h3>🔗 Final Aggregation Node</h3><pre>def generate_output(state: dict):<br>    text = state.get(&quot;processed_text&quot;, &quot;&quot;)<br>    image_desc = state.get(&quot;image_description&quot;, &quot;&quot;)</pre><pre>    final = f&quot;&quot;&quot;<br>    Final Response:<br>    {text}<br>    {image_desc}<br>    &quot;&quot;&quot;</pre><pre>    return {<br>        &quot;final_output&quot;: final<br>    }</pre><h3>🔀 Step 3: Build the Graph</h3><pre>from langgraph.graph import StateGraph</pre><pre>builder = StateGraph(dict)</pre><pre># Add nodes<br>builder.add_node(&quot;text_node&quot;, process_text)<br>builder.add_node(&quot;image_node&quot;, process_image)<br>builder.add_node(&quot;output_node&quot;, generate_output)</pre><pre># Define flow<br>builder.set_entry_point(&quot;text_node&quot;)</pre><pre>builder.add_edge(&quot;text_node&quot;, &quot;image_node&quot;)<br>builder.add_edge(&quot;image_node&quot;, &quot;output_node&quot;)</pre><pre># Compile graph<br>graph = builder.compile()</pre><h3>▶️ Step 4: Run the Workflow</h3><pre>initial_state = {<br>    &quot;user_input&quot;: &quot;analyze this data&quot;,<br>    &quot;image_path&quot;: &quot;sample.jpg&quot;<br>}</pre><pre>result = graph.invoke(initial_state)</pre><pre>print(result[&quot;final_output&quot;])</pre><h3>🔍 Key Concepts Explained</h3><h3>✅ 1. State Persistence</h3><ul><li>Data is stored once and reused across nodes</li><li>No need for manual parameter passing</li></ul><h3>✅ 2. Partial Updates</h3><p>Each node returns only what it updates:</p><pre>return {&quot;processed_text&quot;: processed}</pre><p>LangGraph merges it into the global state.</p><h3>✅ 3. Multi-Modal Support</h3><p>You can pass:</p><ul><li>Text</li><li>Images (file paths / base64)</li><li>JSON</li><li>Embeddings</li></ul><h3>🖼️ Passing Images via State</h3><h3>Option 1: File Path (used above)</h3><pre>&quot;image_path&quot;: &quot;sample.jpg&quot;</pre><h3>Option 2: Base64 (for APIs)</h3><pre>import base64</pre><pre>with open(&quot;sample.jpg&quot;, &quot;rb&quot;) as f:<br>    encoded = base64.b64encode(f.read()).decode()</pre><pre>state[&quot;image_base64&quot;] = encoded</pre><h3>🔀 Advanced: Conditional Routing</h3><pre>def decide_next(state):<br>    if state.get(&quot;image_path&quot;):<br>        return &quot;image_node&quot;<br>    return &quot;output_node&quot;</pre><pre>builder.add_conditional_edges(<br>    &quot;text_node&quot;,<br>    decide_ne</pre><p>👉 Enables dynamic workflows.</p><h3>🧪 Real-World Scenarios</h3><ul><li>📞 IVR classification pipelines</li><li>🏥 Healthcare document + image analysis</li><li>📊 Business analytics copilots</li><li>🤖 Autonomous AI agents</li><li>📄 PDF + image QA systems</li></ul><h3>⚡ Best Practices</h3><h3>🔹 Keep State Minimal</h3><p>Avoid dumping unnecessary data.</p><h3>🔹 Use TypedDict / Pydantic</h3><p>Ensures schema consistency.</p><h3>🔹 Modular Nodes</h3><p>Each node should do <strong>one job only</strong>.</p><h3>🔹 Handle Failures Gracefully</h3><p>Always return fallback values.</p><h3>🏁 Conclusion</h3><p>LangGraph transforms AI workflows from <strong>linear chains</strong> into <strong>intelligent, stateful systems</strong>.</p><p>With:</p><ul><li>Centralized state</li><li>Multi-modal support</li><li>Conditional execution</li></ul><p>…it becomes the foundation for <strong>production-grade GenAI orchestration</strong>.</p><h3>📌 TL;DR</h3><ul><li>LangGraph = Stateful orchestration engine</li><li>State = Shared memory across nodes</li><li>Supports text + images seamlessly</li><li>Enables complex AI workflows</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05d7a0f1da41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Autonomous AI Agents with LangGraph: Tools, Memory & Orchestration]]></title>
            <link>https://medium.com/@sifayathf/building-autonomous-ai-agents-with-langgraph-tools-memory-orchestration-83eb459c9c76?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/83eb459c9c76</guid>
            <category><![CDATA[langgraph-agents]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-orchestration]]></category>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 20:29:34 GMT</pubDate>
            <atom:updated>2026-03-28T20:29:34.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPd4bz7La4QSndsT52VXiw.png" /></figure><h3>🚀 Introduction</h3><p>Autonomous AI agents are the next evolution of GenAI systems — moving beyond simple Q&amp;A into:</p><ul><li>Goal-driven execution</li><li>Tool usage (APIs, DBs, calculators)</li><li>Multi-step reasoning</li><li>Persistent memory</li></ul><p>While frameworks like LangChain introduced agents, <strong>LangGraph takes it further</strong> by enabling:</p><p>👉 <strong>Stateful, controllable, production-grade agent workflows</strong></p><p>In this article, we’ll build a <strong>fully working autonomous agent</strong> using:</p><ul><li>LangGraph for orchestration</li><li>Tools for real-world actions</li><li>Memory for context persistence</li></ul><h3>🧠 What is an Autonomous Agent?</h3><p>An autonomous agent can:</p><ol><li>Understand a user goal</li><li>Decide what action to take</li><li>Use tools if required</li><li>Store intermediate context</li><li>Iterate until task completion</li></ol><h3>🏗️ Architecture Overview</h3><pre>User Input → Planner → Tool Executor → Memory → Final Response<br>                     ↑         ↓<br>                  Loop until goal achieved</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6iAUN_EU7KpHi1cEz8z3gA.png" /></figure><h3>🔑 Core Components</h3><h3>1. 🧠 State (Memory Backbone)</h3><pre>from typing import TypedDict, List, Optional</pre><pre>class AgentState(TypedDict):<br>    user_input: str<br>    plan: Optional[str]<br>    tool_result: Optional[str]<br>    history: List[str]<br>    final_output: Optional[str]</pre><h3>2. 🛠️ Tools (External Capabilities)</h3><p>Let’s define simple tools:</p><pre>def calculator_tool(query: str) -&gt; str:<br>    try:<br>        return str(eval(query))<br>    except:<br>        return &quot;Invalid calculation&quot;</pre><pre>def search_tool(query: str) -&gt; str:<br>    return f&quot;Search results for &#39;{query}&#39; (mocked)&quot;</pre><h3>⚙️ Step 1: Planner Node</h3><p>The planner decides:<br> 👉 Should we use a tool or answer directly?</p><pre>def planner_node(state: dict):<br>    user_input = state[&quot;user_input&quot;]</pre><pre>    if &quot;calculate&quot; in user_input:<br>        plan = &quot;use_calculator&quot;<br>    elif &quot;search&quot; in user_input:<br>        plan = &quot;use_search&quot;<br>    else:<br>        plan = &quot;respond_directly&quot;</pre><pre>    return {&quot;plan&quot;: plan}</pre><h3>🔧 Step 2: Tool Executor Node</h3><pre>def tool_node(state: dict):<br>    plan = state[&quot;plan&quot;]<br>    user_input = state[&quot;user_input&quot;]</pre><pre>    if plan == &quot;use_calculator&quot;:<br>        result = calculator_tool(user_input.replace(&quot;calculate&quot;, &quot;&quot;).strip())</pre><pre>    elif plan == &quot;use_search&quot;:<br>        result = search_tool(user_input)</pre><pre>    else:<br>        result = &quot;No tool used&quot;</pre><pre>    return {<br>        &quot;tool_result&quot;: result,<br>        &quot;history&quot;: state.get(&quot;history&quot;, []) + [result]<br>    }</pre><h3>🧠 Step 3: Memory Node</h3><p>Maintains conversation context.</p><pre>def memory_node(state: dict):<br>    history = state.get(&quot;history&quot;, [])<br>    history.append(f&quot;User: {state[&#39;user_input&#39;]}&quot;)</pre><pre>    return {&quot;history&quot;: history}</pre><h3>🧾 Step 4: Response Generator</h3><pre>def response_node(state: dict):<br>    plan = state.get(&quot;plan&quot;)<br>    tool_result = state.get(&quot;tool_result&quot;, &quot;&quot;)<br>    history = state.get(&quot;history&quot;, [])</pre><pre>    if plan == &quot;respond_directly&quot;:<br>        final = f&quot;Direct response to: {state[&#39;user_input&#39;]}&quot;<br>    else:<br>        final = f&quot;Tool Result: {tool_result}&quot;</pre><pre>    final += f&quot;\n\nMemory: {history}&quot;</pre><pre>    return {&quot;final_output&quot;: final}</pre><h3>🔀 Step 5: Conditional Routing (Agent Brain)</h3><pre>def should_use_tool(state):<br>    if state[&quot;plan&quot;] in [&quot;use_calculator&quot;, &quot;use_search&quot;]:<br>        return &quot;tool_node&quot;<br>    return &quot;response_node&quot;</pre><h3>🏗️ Step 6: Build LangGraph Agent</h3><pre>from langgraph.graph import StateGraph</pre><pre>builder = StateGraph(dict)</pre><pre>builder.add_node(&quot;planner&quot;, planner_node)<br>builder.add_node(&quot;tool_node&quot;, tool_node)<br>builder.add_node(&quot;memory&quot;, memory_node)<br>builder.add_node(&quot;response&quot;, response_node)</pre><pre>builder.set_entry_point(&quot;planner&quot;)</pre><pre># Conditional edge<br>builder.add_conditional_edges(<br>    &quot;planner&quot;,<br>    should_use_tool<br>)</pre><pre>builder.add_edge(&quot;tool_node&quot;, &quot;memory&quot;)<br>builder.add_edge(&quot;memory&quot;, &quot;response&quot;)</pre><pre># Compile<br>agent = builder.compile()</pre><h3>▶️ Step 7: Run the Agent</h3><pre>input_state = {<br>    &quot;user_input&quot;: &quot;calculate 10 + 20&quot;,<br>    &quot;history&quot;: []<br>}</pre><pre>result = agent.invoke(input_state)</pre><pre>print(result[&quot;final_output&quot;])</pre><h3>🔁 Example Execution</h3><h3>Input:</h3><pre>calculate 10 + 20</pre><h3>Output:</h3><pre>Tool Result: 30</pre><pre>Memory: [&#39;30&#39;, &#39;User: calculate 10 + 20&#39;]</pre><h3>🧠 What Makes This “Autonomous”?</h3><p>✅ Decision making (planner)<br> ✅ Tool usage<br> ✅ Memory persistence<br> ✅ Conditional execution<br> ✅ Extensible architecture</p><h3>🔥 Advanced Enhancements</h3><h3>🔹 1. Replace Planner with LLM</h3><pre>from langchain.chat_models import ChatOpenAI</pre><pre>llm = ChatOpenAI()</pre><pre>def planner_node(state):<br>    prompt = f&quot;Decide action: {state[&#39;user_input&#39;]}&quot;<br>    decision = llm.invoke(prompt)</pre><pre>    return {&quot;plan&quot;: decision.content}</pre><h3>🔹 2. Add Multi-step Looping</h3><p>You can loop until goal achieved:</p><pre>builder.add_edge(&quot;response&quot;, &quot;planner&quot;)</pre><h3>🔹 3. Persistent Memory (Redis / DB)</h3><p>Replace in-memory history with:</p><ul><li>Redis</li><li>Vector DB</li><li>SQL</li></ul><h3>🔹 4. Tool Registry Pattern</h3><pre>TOOLS = {<br>    &quot;calculator&quot;: calculator_tool,<br>    &quot;search&quot;: search_tool<br>}</pre><h3>🧪 Real-World Applications</h3><ul><li>📞 Telecom automation agents</li><li>🏥 Healthcare copilots</li><li>🧾 Document processing agents</li><li>🤖 Autonomous debugging agents</li></ul><h3>⚡ Best Practices</h3><h3>🔹 Keep Tools Atomic</h3><p>Each tool = single responsibility</p><h3>🔹 Use Structured State</h3><p>TypedDict / Pydantic recommended</p><h3>🔹 Add Observability</h3><p>Log each state transition</p><h3>🔹 Fail Gracefully</h3><p>Never break the graph execution</p><h3>🏁 Conclusion</h3><p>LangGraph enables a shift from:</p><p>👉 Prompt-based systems<br> ➡️ To<br> 👉 <strong>Autonomous, stateful AI agents</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83eb459c9c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Websites summarizer using langchain,Ollama, Deepseek]]></title>
            <link>https://medium.com/@sifayathf/websites-summarizer-using-langchain-ollama-deepseek-25d6cbbfab86?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d6cbbfab86</guid>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 07:49:39 GMT</pubDate>
            <atom:updated>2025-03-03T07:56:58.736Z</atom:updated>
            <content:encoded><![CDATA[<p>You have hundreds of websites, you have opened in your browser, while you are coding, writing articles, creating that one impressive ppt and wish to takes notes of the webpages used, but failed to do so, and now you dont know which page you have found that but just have a list of urls now.</p><p>Dont know what to do? Now we can use Langchain, Ollama, Deepseek to do the work for you.</p><p>First install the libraries.</p><pre>!pip install langchain langchain_community langchain_groq langchain_ollama</pre><p>Now lets import the packages.</p><pre>from langchain.prompts import PromptTemplate<br>from langchain_community.document_loaders import WebBaseLoader<br>from langchain_groq import ChatGroq</pre><p>Here you have to do one more thing outside your code, you need to download ollama and install the same.</p><p><a href="https://ollama.com/">https://ollama.com/</a></p><p>Now install the ollama. Once done choose a particular model, which you are going to use.</p><p>I am going to use this deepseek model DeepSeek-R1-Distill-Qwen-1.5B because it is the smallest deepseek model. Easy to download and its around 1.3 gb in size.</p><p>Open a command prompt, and type the following command after you have installed ollama.</p><pre>ollama run deepseek-r1:1.5b</pre><p>This will start downloading the deepseek model, if you are running it for the first time. If you have already downloaded the model by running the command previously, it will automatically connect to the model and you ollama server is running now.</p><p>Now lets initialize the llms in the python code.</p><pre>from langchain_ollama import ChatOllama<br>llm = ChatOllama(<br>    model = &quot;deepseek-r1:1.5b&quot;,<br>    temperature=0,<br>)</pre><p>Give the URLs.</p><pre>urls = &quot;&quot;&quot;https://towardsdatascience.com/getting-started-with-text-analysis-in-python-ca13590eb4f7<br>https://github.com/lisanka93/text_analysis_python_101<br>https://data-flair.training/blogs/machine-learning-text-summarization/<br>https://data-flair.training/<br>https://openai.com/blog/chatgpt<br>https://towardsdatascience.com/3-ways-to-load-csv-files-into-colab-7c14fcbdcb92<br>https://www.nltk.org/api/nltk.tokenize.html<br>https://chat.openai.com/<br>https://www.kaggle.com/code/dansbecker/basic-data-exploration/tutorial<br>https://www.kaggle.com/code/sifayathf/notebook2b94fe8afb/edit<br>https://www.kaggle.com/code/dansbecker/your-first-machine-learning-model/tutorial<br>https://www.google.com/search?q=ml+test_data%3D&amp;rlz=1C1GCEA_enIN1035IN1035&amp;ei=BEK6Y9XdDse83LUP87Ky4Aw&amp;ved=0ahUKEwjV79SOjbf8AhVHHrcAHXOZDMwQ4dUDCA8&amp;uact=5&amp;oq=ml+test_data%3D&amp;gs_lcp=Cgxnd3Mtd2l6LXNlcnAQAzIGCAAQBxAeMgYIABAHEB4yBggAEAgQHjIFCAAQhgMyBQgAEIYDMgUIABCGAzIFCAAQhgM6CggAEEcQ1gQQsAM6CAgAEAgQBxAeOg0IABAIEAcQHhDxBBAKOgYIABAeEA1KBAhBGABKBAhGGABQvAVYuglg5SpoAXABeACAAbgBiAHhA5IBAzAuM5gBAKABAcgBBcABAQ&amp;sclient=gws-wiz-serp<br>https://www.geeksforgeeks.org/splitting-data-for-machine-learning-models/<br>https://medium.com/mlearning-ai/train-and-test-data-split-152bad0afbb2<br>https://www.kaggle.com/discussions/general/104462<br>https://console.cloud.google.com/freetrial/signup/tos?_ga=2.60858604.1365088097.1676040937-72737485.1676040937&amp;facet_utm_source=statics.teams.cdn.office.net&amp;facet_utm_campaign=(referral)&amp;facet_utm_medium=referral&amp;facet_url=https:%2F%2Fcloud.google.com%2Fcertification&amp;facet_id_list=%5B39300012,%2039300022,%2039300118,%2039300196,%2039300241,%2039300317,%2039300320,%2039300327,%2039300333,%2039300345,%2039300354,%2039300364,%2039300373,%2039300411,%2039300422,%2039300437,%2039300471%5D&amp;pli=1<br>https://chat.openai.com/c/2713ed30-8412-4fa9-aea9-4c0d9033d115<br>https://data-flair.training/blogs/machine-learning-text-summarization/<br>https://data-flair.training/blogs/artificial-intelligence-project-ideas/<br>https://medium.com/@lokaregns/preparing-text-data-for-transformers-tokenization-mapping-and-padding-9fbfbce28028<br>https://medium.com/@lokaregns/preparing-text-data-for-transformers-tokenization-mapping-and-padding-9fbfbce28028<br>https://www.google.com/search?q=rdbms+data+prediction+using+machine+learning&amp;rlz=1C1GCEA_enIN1059IN1061&amp;oq=rdbms+data+prediction+using&amp;gs_lcrp=EgZjaHJvbWUqBwgBECEYoAEyBggAEEUYOTIHCAEQIRigATIHCAIQIRigATIHCAMQIRigAdIBCTE1NTc1ajBqN6gCALACAA&amp;sourceid=chrome&amp;ie=UTF-8<br>https://www.freecodecamp.org/news/machine-learning-directly-in-sql/<br>https://blogs.oracle.com/coretec/post/oracle-auto-ml-use-inbuilt-expertise-to-develop-effective-machine-learning-model#:~:text=Oracle%20Auto%20ML%20%28automated%20machine%20learning%29%20is%20a,learning%20algorithm%2C%20appropriate%20feature%20sets%20and%20model%20hyperparameters.<br>https://chrome.google.com/webstore/detail/copy-all-tabs/pnbocjclllbkfkkchadljokjclnpakia/related&quot;&quot;&quot;</pre><p>Convert the urls to list.</p><pre>urls = urls.splitlines()</pre><p>Generate summary</p><pre>def summarygenerator(url,code,language):<br>    data = fetchurldata(url.split(&#39;,&#39;))<br>    template=&quot;&quot;&quot;As a web page reader and summarizer please go through the webpages come up with a simple and short 90 words summary <br>    based on the data: {data} <br>    The output should be in the following format:<br>    Title:<br>    Url: {url}<br>    Summary:<br>    Code:&quot;&quot;&quot;<br>    prompt = PromptTemplate(input_variables =[&quot;url&quot;,&quot;data&quot;],<br>                            template = template<br>                            )<br>    story_chain = LLMChain(llm=llm, prompt=prompt,output_key=&quot;story&quot;)<br>    story = story_chain({&quot;url&quot;:url,&quot;data&quot;: data })<br>    <br>    return story<br></pre><p>Get the webpage responses by sending request and getting response and cleansing them of unnecessary tags.</p><pre>!pip install python-docx &gt;/dev/null<br>!pip install openai &gt;/dev/null<br>import requests<br>from bs4 import BeautifulSoup<br>from docx import Document<br><br># Initialize a new Document<br>doc = Document()<br><br># Iterate through the URLs<br>for url in urls:<br>    try:<br>        # Fetch the HTML content of the webpage<br>        response = requests.get(url)<br>        response.raise_for_status()<br><br>        # Parse the HTML content using BeautifulSoup<br>        soup = BeautifulSoup(response.content, &#39;html.parser&#39;)<br><br>        response = summarygenerator(url=url,code =code, language=language)<br><br>        # Extract readable content (you may need to customize this based on the website structure)<br>        readable_content = &#39;\n&#39;.join([code.get_text() for code in soup.find_all(&#39;code&#39;)])<br><br>        # Add a heading with the URL<br>        doc.add_heading(f&quot;Summary of {url}&quot;, level=1)<br><br>        # Add the summary to the document<br>        doc.add_paragraph(readable_content)<br><br>        # Add a page break between URLs<br>        doc.add_page_break()<br><br>    except requests.exceptions.RequestException as e:<br>        print(f&quot;Error fetching or parsing content from {url}: {e}&quot;)<br><br># Save the document to a DOCX file<br>doc.save(&#39;website_summaries.docx&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d6cbbfab86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a Pandas DataFrame — Pandas DataFrame CRUD Series]]></title>
            <link>https://medium.com/@sifayathf/how-to-create-a-pandas-dataframe-pandas-dataframe-crud-series-ea1f83540a61?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1f83540a61</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-mining]]></category>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 17:55:06 GMT</pubDate>
            <atom:updated>2023-09-24T17:55:06.169Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to create a Pandas DataFrame — Pandas DataFrame CRUD Series</h3><p>There are many ways to create a data frame. For the uninitiated, DataFrame is a dataset in an arrangement of rows and columns similar to rdbms and excel. With this intro, Lets dive deep into this.</p><p>The easiest way to create a Pandas DataFrame is to create a list of list and assign column names with pandas DataFrame command. Without further ado lets import the modules and here is the code for you.</p><pre>import pandas as pd<br><br>data = pd.DataFrame([[&#39;Sifayath&#39;,&#39;Mr&#39;, &#39;Data Scientist and AI ML Expert&#39;],<br>                     [&#39;Khabib&#39;,&#39;Mr&#39;, &#39;MMA Champion&#39;],<br>                     [&#39;Islam&#39;,&#39;Mr&#39;, &#39;MMA Champion&#39;],<br>                     [&#39;Mezut Ozil&#39;,&#39;Mr&#39;,&#39;Footballer&#39;]])<br><br>data.columns =[&#39;Name&#39;,&#39;Title&#39;,&#39;Occupation&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*zuabapruDtrktnYlsbBROg.png" /><figcaption>output</figcaption></figure><p>Well, now see voila your dataframe is created. Ofcourse there are other ways to create a dataframe. One common way prefered by most developers for demo purposes is to give the columns also in a single statement as below.</p><pre>import pandas as pd<br><br>testdata=pd.DataFrame([[&#39;Ahmed&#39;,&#39;Sifayath&#39;,&#39;Mr&#39;,&#39;Data Scientist and AI ML Expert&#39;],<br>[&#39;Abdur Raheem&#39;,&#39;Green&#39;,&#39;Mr&#39;,&#39;Founder of iERA&#39;],<br>[&#39;Khabib&#39;,&#39;Nurmagomedov&#39;,&#39;Mr&#39;,&#39;MMA Champ&#39;],<br>[&#39;Ahmed&#39;,&#39;Sifayath&#39;,&#39;Mr&#39;,&#39;Data Scientist and AI Expert&#39;]],<br>columns=[&#39;firstname&#39;,&#39;lastname&#39;,&#39;title&#39;,&#39;occupation&#39;]<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*YZsJ0FhJVBUrlBFjqh46KQ.png" /></figure><h3>Creating a Dataframe from a dictionary:</h3><p>You can create a dataframe from dictionary too. Lets first see another way to create a dataframe where the input to the data frame method is in the same format as you create a dictionary, and later we will see how to create a df from dictionary directly.</p><p>Lets see the first part…</p><pre>data =pd.DataFrame({&#39;Product&#39;: [&#39;Best Cup Holder&#39;,&#39;Best Coffee Mug&#39;,&#39;Best Coffee Maker&#39;],<br>                    &#39;Buying Price&#39;:[10,20,400],<br>                    &#39;Price&#39;:[60,100,1500],<br>                    &#39;Quantity Sold&#39;:[1000,300,30]})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*qoFL_xQpMzDHt2MaG-bgHw.png" /><figcaption>Output</figcaption></figure><p>Now, for the second part, we create a dictionary first then give it as inpout parameter for <em>pd.DataFrame</em> method to create a pandas dataframe.</p><pre>salesdict={&#39;Product&#39;: [&#39;Best Cup Holder&#39;,&#39;Best Coffee Mug&#39;,&#39;Best Coffee Maker&#39;],<br>                    &#39;Buying Price&#39;:[10,20,400],<br>                    &#39;Price&#39;:[60,100,1500],<br>                    &#39;Quantity Sold&#39;:[1000,300,30]}<br>#  The above code creates a dictionary,  Now using this to create dataframe<br>salesdata = pd.DataFrame(salesdict)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*fH3MRv_9iVTNCXB3m9gCfA.png" /><figcaption>output salesdata dataframe</figcaption></figure><p>There are several other ways to create a dataframe such as from csv, excel, from database. We will see that in the next article…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1f83540a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas — What to do if you forgot your column name and remember only part of it . DataFrame.filter]]></title>
            <link>https://medium.com/@sifayathf/pandas-what-to-do-if-you-forgot-your-column-name-and-remember-only-part-of-it-dataframe-filter-4e1f9c449e14?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e1f9c449e14</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-wrangling]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 02:11:28 GMT</pubDate>
            <atom:updated>2023-09-20T02:11:28.061Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pandas — What to do if you forgot your column name and remember only part of it . DataFrame.filter</h3><p>It often happens for most data scientists like you that you are dealing with a gigaton sized dataframe, where you have to run a marathon scroll to get your column name and data. Hasn’t happened to you? Lucky you…</p><p>Most often we have datasets when loading it for first time we skim through columns to get insights, by skim through i really mean we skim like ninjas…We get an idea about whats the dataset and dataframe is. Then we try to query the column names to deep dive, to our surprise we remember only part of the column names.</p><p>Without further adoo lets go smash some code.</p><p>As usual we go for the amazon mobile price dataset. I can hear you screaming “Hey Sifayath… dont you have any other dataset?”. Still i have started working on this one. Haha.</p><p>Here we go… Loading the dataset using the following code.</p><pre>import pandas as pd<br>data = pd.read_csv(r&quot;C:\\Users\\sifayathahmed.f\\Downloads\\archive (7)\\amazon_mobile.csv&quot;,encoding=&quot;ISO-8859-1&quot;)</pre><p>The dataset looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*vmOWBepvwQCRUj1K5U6BlQ.png" /></figure><p>We normally knows in any price list dataset there is a column which contains word … no prize for guessing… the word ‘Price’. But we dont know the exact column name and also we might not know how many columns with the word price is there.</p><p>Yeah. I can hear you say we can use <em>data.columns</em>. But, what if there are a thousand column in the dataset. This wont be ideal then. We have another method which we can use for this<em> data.filter. </em>The code below uses regex parameter to match column names.</p><pre>data.filter(regex=&#39;Price&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*id25pD1L5oROTWvaFGS5-w.png" /></figure><p>As you can see it displayed the column <em>Price(Dollar) </em>along with the data<em>. </em>Now lets use another line of code to check if any colums contain rice.</p><pre>data.filter(regex=&#39;rice&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*OAJJgugfYXykRqRDENmf1w.png" /></figure><p>Now, you see it pulled out two columns with the partial name <em>rice </em>along with the data<em>.</em></p><p>You can also use the parameter <em>like </em>with <em>filter </em>method.</p><pre>data.filter(like=&#39;Price&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*dNu7ACoIzPqi5KaGWi3QtA.png" /></figure><p>For those guys screaming “Thats all ok, show us the column names. How do i believe you???”.</p><pre>data.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*xsr_QkAx0RP6l-oHhMpj9g.png" /></figure><p>Adios amigos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e1f9c449e14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas Dataframe describe function-Difference between how it behaves for Categorical vs Numerical…]]></title>
            <link>https://medium.com/@sifayathf/pandas-dataframe-describe-function-difference-between-how-it-behaves-for-categorical-vs-numerical-e72a7cfa074c?source=rss-f76f9c8b15ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/e72a7cfa074c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[pandas-tutorial]]></category>
            <dc:creator><![CDATA[Sifayathf]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 23:17:43 GMT</pubDate>
            <atom:updated>2023-09-18T23:17:43.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pandas Dataframe describe function-Difference between how it behaves for Categorical vs Numerical Dataframe</h3><p>Pandas is a powerful tool which is used by majority of data analysts and data scientists. One powerful method pandas provides in Pandas Dataframe is describe() method.</p><p>The describe() method is used to display the information of each and every column values in a dataframe, however, interestingly, the information displayed by the describe() method is different for a Categorical and a Numerical dataframe.</p><p>Enough of jibber jabber, Let us see some code really quick.</p><pre>import pandas as pd<br>data = pd.read_csv(r&quot;C:\\Users\\sifayathahmed.f\\Downloads\\archive (7)\\amazon_mobile.csv&quot;,encoding=&quot;ISO-8859-1&quot;)</pre><p>The above code loads the amazon mobile price dataset. You can download this dataset from Kaggle. No hassles.</p><p>Lets see how the dataset looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*4NJWET-UPl2QNUXRCOHagw.png" /></figure><p>The dataset has the following columns.</p><pre>data.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*k8wUNblYopf7r8RhyDxFZA.png" /></figure><p>Now lets see what kind of dataframe it is. Normally, pd.read_csv creates a categorical dataframe with all the columns as object if no coverters are specified.</p><pre>data.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*fSP4szhde3I2xcsTUU0uww.png" /></figure><p>Clearly, the dataframe columns all are of type object.</p><p>Lets quickly do a describe().</p><pre>data.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*v6eMzbRhP3RjsYVqPrvy7g.png" /></figure><p>We have four columns as output namely count, unique, top, freq.</p><p>So the categorical dataframe has these four columns for describe(). What would be the columns for describe() on a numerical dataframe. Will it be same? or different?. Lets see.</p><pre>datanumeric=pd.DataFrame([[1,100],[2,200],[3,300],[4,400],[5,500],[6,600]])<br>datanumeric.columns = [&#39;Product Count&#39;,&#39;Unit Price&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*UfCxUp0DnM7MpxcY-8yDKg.png" /><figcaption>datanumeric</figcaption></figure><p>We have just created a numerical dataframe. Lets quickly do a describe().</p><pre>datanumeric.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*f8PCRoElUzBlHQ8KFLpPlg.png" /></figure><p>We can clearly see the rows are changed in the output of describe().</p><p>Instead of four, we have eight row labels, count, mean, std, min, 25%, 50%, 75%, max. So for a numerical dataframe, we have 8 rows as output.</p><p>Now an intriguing question is what if we have both numerical and non numerical dtypes in the dataframe. What would the describe() method do now? Lets go and merge these two data frames in differnt ways and see.</p><pre>datanumeric1 = pd.merge(datanumeric, data[&#39;Product Description &#39;][0:6], how =&#39;inner&#39;, left_index=True, right_index=True)<br>datanumeric1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*5pxAv3xWaTpDdW40YZl4Dg.png" /></figure><p>The above code just takes the first six records of the column ‘Product Description’ of the ‘data’ dataframe and merges it with our numerical dataframe. Now lets do a describe().</p><pre>datanumeric1.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*s4b6pujpBSwI6iYxbiPLWg.png" /></figure><p>Its obvious the that the 8 records are printed and the describe() method treats it as a numerical dataframe but skips the Product Description column. Lets do a dtype print here and check if the column is there and whats the type.</p><pre>datanumeric1.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*he4tOQdoKQfUfwi6qWxoxg.png" /></figure><p>So the columns Product Description is there and the dtype is object but still the describe() considers it as a numerical dataframe and prints the numerical columns alone and it stats.</p><p>What if we merge it the other way around, with Product Description first and the other two columns as next. Still we get the same results.</p><p>Look for yourself.</p><pre>datacategory2= pd.merge(data[&#39;Product Description &#39;][0:6], datanumeric,  how =&#39;inner&#39;, left_index=True, right_index=True)</pre><pre>datacategory2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*doy5VcTe5IMUVGDQgHdZ4Q.png" /></figure><pre><br>datacategory2.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*gtPVoMy6Gp1QUM8Tq6TUGA.png" /></figure><pre>datacategory2.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*WueeAm1I6yPcWYzj_LpYEA.png" /></figure><p>So thats it for now. Thanks for staying patient and reading it till here.</p><p>Alas, we can do a describe for subset of a dataframe too.</p><pre>data[&#39;Product Description &#39;][0:6].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*TwqkusZBFhOwYeqShbK0Dg.png" /></figure><p>Thats all for now. Adios amigos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e72a7cfa074c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>