<?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 Vishwajeetv on Medium]]></title>
        <description><![CDATA[Stories by Vishwajeetv on Medium]]></description>
        <link>https://medium.com/@vishwajeetv2003?source=rss-f654552bd245------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eU6jjq0ZsEXz3-aUzWOLPQ.jpeg</url>
            <title>Stories by Vishwajeetv on Medium</title>
            <link>https://medium.com/@vishwajeetv2003?source=rss-f654552bd245------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:31:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vishwajeetv2003/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[I Built an AI Agent That Reads SEC Filings, Earnings News, and Charts So You Don’t Have To]]></title>
            <link>https://medium.com/@vishwajeetv2003/i-built-an-ai-agent-that-reads-sec-filings-earnings-news-and-charts-so-you-dont-have-to-5cc267edc069?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cc267edc069</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 05:46:32 GMT</pubDate>
            <atom:updated>2026-06-11T05:54:18.845Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOI8Dic4yyZQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOI8Dic4yyZQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOI8Dic4yyZQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/38e9cc005015b6520f3f8e89a125b4f7/href">https://medium.com/media/38e9cc005015b6520f3f8e89a125b4f7/href</a></iframe><p>A few weeks ago I set out to answer a question that’s been bugging me as both an ML engineer and a (very amateur) investor: what would it actually take to build a “junior analyst” that reads everything about a stock and gives you a real, sourced answer not a hallucinated one?</p><p>Not a wrapper around ChatGPT that says “AAPL looks bullish 🚀” with zero evidence. An actual pipeline: ingest 10-K filings, news, and price data, store it properly, run it through a multi-agent system, and have the system <em>show its work</em>.</p><p>This post is the story of building that system end to end — the architecture, the agents, the things that broke, and the numbers at the end that tell me it actually works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQyKe9YKVCr-akzclc-qjg.png" /><figcaption>AI stock research analyzer</figcaption></figure><h3>What I was building</h3><p>The stack, after a lot of back-and-forth:</p><ul><li>FastAPI backend, React + Vite + shadcn frontend</li><li>LangGraph for the actual research pipeline (this is the heart of it)</li><li>PostgreSQL + pgvector for storage and retrieval</li><li>Celery + Redis for background jobs and pub/sub updates</li><li>Ollama (nomic-embed-text) for local embeddings — free, runs on my machine</li><li>Gemini as the synthesizer LLM, Cohere for reranking</li><li>yfinance, SEC EDGAR, RSS feeds as data sources</li></ul><p>Why this stack? I wanted it to be something people could actually clone and run without a $500/month AWS bill — hence Ollama for embeddings and free-tier LLMs where possible. And I wanted every architectural decision to be <em>explainable</em>, because the whole point of this project is teaching, not just shipping.</p><h3>The architecture: map-reduce, but for stock research</h3><p>The core idea is simple once you say it out loud: if a user asks about 5 stocks, you don’t want one giant LLM call trying to reason about all 5 at once. You want 5 independent research agents working in parallel, each focused on one ticker, and then a synthesizer that combines their findings.</p><p>That’s literally a map-reduce pattern, and LangGraph’s Send API makes it almost embarrassingly clean to express:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KAVzHb1x9vFWtzNXV2UAQ.png" /></figure><p>Each worker subgraph does its own retrieval — pulling relevant chunks of 10-Ks, recent news, and fundamentals from pgvector — reranks them with Cohere, and hands a tight, relevant context to the synthesizer. The synthesizer then produces a structured analysis: a score (0–100), a BUY/HOLD/SELL signal, a bull case, a bear case, and a specific buy-window — and critically, every claim has to be grounded in the real data block it was just handed, which is what makes the verification layer (more on that below) possible in the first place.</p><h3>The ingestion pipeline (where most of the unglamorous work lives)</h3><p>Before any of the agentic stuff can work, you need <em>good data in the database</em>. This is the part nobody talks about in LLM tutorials, and it’s where I spent a surprising chunk of my time.</p><p>The pipeline: fetch 10-K filings from SEC EDGAR, news from yfinance/RSS, and fundamentals — then run everything through a parent-child chunker (small chunks for precise retrieval, larger parent chunks for context), embed with Ollama, and upsert into pgvector with doc_hash-based deduplication so re-running ingestion doesn&#39;t blow up your database with duplicates.</p><p>A few real bugs I hit here, because “it works on the happy path” and “it works” are very different things:</p><ul><li>yfinance changed its news schema mid-project. In the 1.x line, news fields moved under item[&#39;content&#39;] instead of being top-level. My parser silently returned empty news for every ticker until I noticed the chunks looked suspiciously thin.</li><li>SEC 10-K HTML files have a table of contents that matches the same section headers as the actual content. My parser was happily extracting the <em>table of contents</em> instead of the financial statements. Fix: collect <em>all</em> header matches and take the longest match, not the first.</li><li>My chunker had an infinite loop on the last chunk of a document because of an off-by-one in the sliding window. One if end &gt;= len(text): break later, problem solved — but it&#39;s the kind of bug that just <em>hangs</em> with no error message, which is the worst kind to debug.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*No7WgkvswexXLHj4Kb1gBQ.png" /></figure><h3>The hallucination problem (and why “guardrails” isn’t a buzzword here)</h3><p>Here’s the thing about LLMs and financial data: they will confidently state a P/E ratio that is just… wrong. Not maliciously — it’s just pattern-matching on text that <em>looks</em> like the right shape.</p><p>So I added a layer that I think is the most important part of the whole project: after the LLM generates its analysis, I run a regex-based check that pulls any P/E ratio the model claims, and compares it against the <em>actual</em> trailing and forward P/E from yfinance. If the model’s number is off by more than 10% from both, the analysis gets tagged with a hallucination_flag that the frontend surfaces to the user.</p><p>Same idea for the score: a field_validator clamps whatever the LLM outputs into [0, 100] — not by rejecting and retrying (expensive, slow), but by <em>forcing</em> it into range. And every single response gets a disclaimer string force-overwritten server-side, so there&#39;s no scenario where the LLM &quot;forgets&quot; to say this isn&#39;t financial advice.</p><p>The lesson here, which I think generalizes way beyond stock research: don’t trust the LLM to follow instructions about its own output. Verify the output after the fact, against ground truth you control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bX-mRWdgCbOClEA6M3YqNw.png" /></figure><h3>The bug that made me question my sanity: silent streaming failure</h3><p>This one took me embarrassingly long to find. The Q&amp;A endpoint streams answers token-by-token from Gemini using StreamingResponse. It worked great... until I switched to a newer Gemini model, and then it just <em>hung</em>. No error. No response. The connection just sat there forever.</p><p>Turns out: newer Gemini models sometimes return AIMessage.content as a list[dict] of content blocks ([{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;...&quot;, &quot;extras&quot;: {...}}]) instead of a plain string. My code did &quot;&quot;.join(answer_parts), which throws a TypeError on a list of dicts. But because this happened <em>after</em> the StreamingResponse had already sent its 200 OK header, the error was completely invisible to the client — it just looked like the server stopped talking.</p><p>The fix was a small _content_to_text() normalizer that handles both shapes. The bigger lesson: if you&#39;re calling .content on any Gemini response anywhere in your codebase, it can return either a string or a list of blocks, and you need to handle both — silently, this kind of bug produces a 200 status with zero body, which is about the worst failure mode there is.</p><h3>Making it fast: the caching layer</h3><p>Once the pipeline worked, it was <em>correct</em> but slow — a full multi-stock report involves several LLM calls per ticker plus a synthesis call, easily 20–30+ seconds. For a demo (or for someone re-checking the same stock an hour later), that’s a bad experience.</p><p>So I added a Redis caching layer with a few different TTLs depending on how fast the underlying data actually changes:</p><ul><li>News: 2 hours</li><li>10-K filings: 7 days</li><li>Ticker existence checks: 24 hours</li><li>Full report cache: 24 hours, keyed by the sorted, deduped, uppercased set of tickers</li></ul><p>That last one is the big win. If you and I both ask for [&quot;AAPL&quot;, &quot;MSFT&quot;] within 24 hours, you get the <em>exact same job_id</em> my request produced — no recomputation at all.</p><p>I measured this end-to-end (had to be careful here — measuring with setTimeout-based polling in a background browser tab gives wildly inflated numbers because Chrome throttles timers in unfocused tabs; switched to event-driven MutationObserver measurement instead): a cache-hit response comes back in 26.9ms, versus 20-30+ seconds for a cold run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81O1Rbq5t3vEZIWr4ZTaXA.png" /></figure><p>Guardrails on the input side too</p><p>It’s not just the output that needs guarding — the input does too, especially once this is a public-facing thing. So before a job even gets queued:</p><ol><li>Cache check — if this exact ticker set was analyzed recently, short-circuit immediately</li><li>Format validation — does this even look like a valid ticker?</li><li>Existence check — does yfinance actually recognize this ticker? (so [&quot;ENRNQ&quot;] gets a clean &quot;Unknown ticker symbol(s)&quot; error instead of silently failing 30 seconds into a job)</li><li>Rate limiting — 3 jobs per IP per hour, max 15 tickers per job</li></ol><p>The order matters a lot here: cache hits and format checks happen <em>before</em> the rate limit counter increments, so a user fat-fingering a ticker doesn’t burn their quota.</p><h3>What we ended up with</h3><p>A working full-stack app where you type in a few stock tickers, and:</p><ol><li>The system fans out N parallel research agents, each pulling from real SEC filings, recent news, and fundamentals stored in a vector database</li><li>A synthesizer agent produces a 0–100 score, a BUY/HOLD/SELL signal, a bull case, and a bear case — grounded in that retrieved data</li><li>Hallucinated numbers get flagged automatically by cross-checking against real fundamentals</li><li>A live progress board shows you what’s happening via WebSocket (with HTTP polling as a fallback — Redis pub/sub doesn’t buffer, and I learned that the hard way when job-complete events occasionally vanished into the void during a slow Gemini call)</li><li>You can chat with the report afterward — ask follow-up questions, with conversational memory</li><li>Repeat queries come back in under 30ms thanks to caching</li><li>Everything is wrapped in auth, history, and a responsive UI that I tested down to 375px</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArDqkQ0XgGb2Ng4LjCgJaQ.png" /><figcaption>Final Chat bot</figcaption></figure><h3>What’s next: caching whole documents instead of chunks</h3><p>The retrieval setup above is precise, but it’s also a little stingy — the synthesizer only ever sees 5–7 reranked chunks per ticker, never the full 10-K. That’s fine for “what’s the risk factors section say,” but it means the model can’t reason across sections (e.g. connecting a risk disclosure in Item 1A to a number buried in the MD&amp;A).</p><p>The next thing I want to try is Gemini’s context caching. The pitch is simple: you upload a large document once (say, a full 10-K — tens of thousands of tokens), Google caches it server-side, and every subsequent call that references that cache pays a fraction of the normal input-token cost. Gemini 2.5 models also do <em>implicit</em> caching automatically for repeated prefixes, so some of this might come for free without explicit cache management.</p><p>Why this fits this project specifically:</p><ul><li>10-Ks barely change. I already cache the raw filing in Redis for 7 days because companies file annually/quarterly. A Gemini context cache with a matching TTL is a natural extension of a decision I’ve already made.</li><li>The cache is shared, not per-user. If I research AAPL today and you research AAPL an hour later, there’s no reason Google should re-process that 10-K from scratch for you. One cache, many users — the economics get better with more traffic, not worse.</li><li>Full-document context &gt; top-k chunks for synthesis. Instead of betting that the reranker picked the <em>right</em> 5 chunks, the synthesizer gets the whole filing and reasons over it directly. The Q&amp;A follow-ups would benefit even more — “compare the risk factors to last year’s” is a much better answer with the full document available than with whatever chunks happened to score highest for a generic retrieval query.</li></ul><p>The honest trade-off: a full 10-K is a lot more input tokens than 5–7 reranked chunks, even at cached-token discount pricing, so this probably isn’t a wholesale replacement. My plan is a hybrid — keep the pgvector + Cohere retrieval for fast-moving stuff (news, fundamentals, which are cached for 2h/4h respectively and change too often to cache at the LLM layer), and route the heavy “reason about this company’s filings” work through a cached full-document context per ticker. That’s the part I haven’t built yet, so consider this the sequel post.</p><h3>The bigger lesson</h3><p>If there’s one thing I’d want a fellow engineer to take away from this project, it’s that the “AI” part — the LLM calls — was maybe 20% of the actual work. The other 80% was: parsing messy real-world documents, deduplication, caching strategy, rate limiting, handling API schema changes from libraries you depend on, and — most of all — building verification layers so that when the model is wrong (and it will be), the system catches it instead of confidently lying to a user about a stock’s P/E ratio.</p><p>That’s the part tutorials skip. It’s also the part that actually matters if you’re building something real.</p><p><em>This project is open-source and built for educational purposes — nothing in it is financial advice (the system itself enforces that with a server-side disclaimer it literally cannot omit). If you’re learning to build agentic AI systems, I hope walking through these failure modes saves you some debugging time.</em></p><p>Code: <a href="https://github.com/vishwajeetvishwakarma/StockResearcher">github.com/vishwajeetvishwakarma/StockResearcher</a> clone it, run it, break it, send a PR.</p><p>Let’s connect: <a href="https://www.linkedin.com/in/vishwajeetv2003/">linkedin.com/in/vishwajeetv2003</a> I post about builds like this regularly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cc267edc069" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Perplexity in 100 Lines of Python]]></title>
            <link>https://medium.com/@vishwajeetv2003/build-your-own-perplexity-in-100-lines-of-python-d42b2ebcd6ef?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/d42b2ebcd6ef</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[perplexity]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 01:22:27 GMT</pubDate>
            <atom:updated>2026-06-01T01:22:27.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wzcQe1B8U70yCeHm.png" /></figure><p>Perplexity crossed 100 million users. People treat it like magic.</p><p>It isn’t. At its core, it runs a pipeline that any engineer can replicate in an afternoon. I know because I built one and in this post I’ll walk you through exactly how it works, including the async trick that makes it fast, and the reranking step that makes it accurate.</p><p>Here’s what we’re building:</p><pre>User Query <br>↓ <br>Generate 5 sub-questions [Gemini] <br>↓ <br>Search each in parallel [DuckDuckGo] <br>↓ <br>Scrape top URLs in parallel [Trafilatura] <br>↓ <br>Chunk → Deduplicate → Rerank [Cohere] <br>↓ <br>Generate answer with citations [Gemini]</pre><blockquote><em>Let’s go step by step.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f6U-65XU9hMGYcbl.png" /></figure><p>When a user types “give me in full detail how ML and AI is different”, searching that exact phrase gives you 3 mediocre results.</p><p>Instead, we generate 5 related sub-questions first:</p><ul><li>What are the key differences between AI and ML?</li><li>Is machine learning a subset of artificial intelligence?</li><li>How does ML differ from traditional AI rule-based systems?</li><li>What are real-world examples where AI and ML overlap?</li><li>How do objectives differ between AI systems and ML models?</li></ul><p>Now you’re covering the topic from 5 angles. Each question fetches 3 URLs. That’s 15 data sources for one query which is exactly the multi-query retrieval strategy that makes Perplexity answers feel comprehensive.</p><p><strong>The gotcha:</strong> Don’t just generate random questions. They need to be semantically diverse covering definition, relationship, methodology, examples, and edge cases. Prompt your LLM explicitly for this. Vague question generation = redundant search results = wasted tokens.</p><p>Here’s where most tutorials fall apart.</p><p>DDGS (DuckDuckGo Search) and Trafilatura (web scraper) are both <strong>blocking libraries</strong>. They don&#39;t support async/await natively.</p><p>If you run them directly in an async function, you block the entire event loop. All 5 searches run one after another. With 15 network calls total that’s painfully slow.</p><p>The fix is run_in_executor. It pushes a blocking function into a thread pool and gives you back an awaitable so your event loop stays free:</p><pre>executor = ThreadPoolExecutor(max_workers=10)<br><br>async def search_question_async(question: str):<br>    loop = asyncio.get_event_loop()<br><br>    # Blocking library → thread pool → awaitable<br>    results = await loop.run_in_executor(executor, _ddgs_search, question)<br><br>    # Scrape all URLs concurrently<br>    scrape_tasks = [<br>        loop.run_in_executor(executor, _trafilatura_fetch, r[&quot;href&quot;])<br>        for r in results if r.get(&quot;href&quot;)<br>    ]<br>    scraped_texts = await asyncio.gather(*scrape_tasks)</pre><p><strong>This pattern works for any blocking library</strong> old Redis clients, legacy HTTP wrappers, database drivers that predate asyncio. Whenever you’re stuck with a sync library in an async codebase, run_in_executor is your escape hatch.</p><p><strong>The gotcha:</strong> Don’t set max_workers too high. With 50 threads hammering DuckDuckGo, you&#39;ll get rate-limited fast. 10 is a safe ceiling for search + scrape combined.</p><p>After scraping, we ran our pipeline on a real query: <em>“give me in full detail how ML and AI is different from each other”</em></p><p>The raw numbers:</p><pre>Total chunks after splitting:  212<br>Unique chunks after dedup:     199<br>Top chunks after reranking:     15<br>Total tokens in context:      2014<br><br>Three separate operations here — each one matters.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iI2N0SvWImGg4wX0.png" /></figure><p><strong>Chunking</strong> splits scraped pages into 400-token pieces with 50-token overlap. Why overlap? Because answers often span chunk boundaries. Without overlap, you lose context at every split point. The chunk size of 400 is intentional small enough that each chunk is focused on one idea, large enough that it has enough context to be useful.</p><p><strong>Deduplication</strong> removes chunks that are either from the same URL+position, or have identical content hashes. We went from 212 → 199 that’s 13 duplicate chunks removed. In production, the same content often appears across mirror sites and aggregators. Without dedup, your LLM sees the same sentence three times and treats it as stronger evidence than it actually is.</p><p><strong>Reranking</strong> is where the real quality gate is. We have 199 unique chunks — but we can only send so many tokens to the LLM. Cohere’s reranker scores every chunk against the original query and returns the top 15:</p><pre>def rerank_chunks(query: str, chunks: list[dict], top_n: int = 10):<br>    response = co.rerank(<br>        model=&quot;rerank-v3.5&quot;,<br>        query=query,<br>        documents=[c[&quot;text&quot;] for c in chunks],<br>        top_n=min(top_n, len(chunks)),<br>    )<br>    return [chunks[hit.index] for hit in response.results]</pre><p>Without reranking, you’re feeding the LLM whatever chunks happen to contain matching keywords. With reranking, you’re feeding it the 15 most semantically relevant chunks. The difference in answer quality is significant — especially for nuanced queries where keyword overlap doesn’t equal relevance.</p><p><strong>The gotcha:</strong> Reranking costs money and adds latency. For a prototype, it’s fine. In production, cache reranked results for repeated queries. The same question asked 1000 times shouldn’t hit Cohere 1000 times.</p><p>With 2014 tokens of clean, reranked context, we call Gemini twice:</p><p>Two-pass generation matters here. A single call asking for “answer + citations” often produces hallucinated citations — the model invents sources that sound plausible. Separating the steps forces grounding in the first pass, then formatting in the second.</p><p>The output for our ML vs AI query came back structured across five sections: Definition and Scope, Relationship, Objectives, Methodology, and Real-World Application Overlap — each sentence cited to its source document.</p><p>That’s the same structure Perplexity uses. Not magic. Just a well-designed prompt.</p><p>To be honest about what this prototype isn’t:</p><p>The core loop -&gt; search, retrieve, rank, generate -&gt; is identical. The difference is engineering polish, not architecture.</p><p>The complete implementation is on <a href="https://github.com/vishwajeetvishwakarma/AgentShortProjects/tree/main/perplexity_workflow">GitHub</a>: <a href="https://github.com/vishwajeetvishwakarma/AgentShortProjects/tree/main/perplexity_workflow">https://github.com/vishwajeetvishwakarma/AgentShortProjects/tree/main/perplexity_workflow</a></p><p>Stack used: Gemini Flash (question gen + answer gen), DuckDuckGo Search via ddgs, Trafilatura (scraping), LangChain text splitter (chunking), Cohere rerank-v3.5 (reranking), tiktoken (token counting).</p><p><em>Next post: I built a hallucination detection layer on top of this pipeline because reranking gets you good context, but it doesn’t guarantee a grounded answer. Here’s how to catch it before your user does.</em> <em>Subscribe so you don’t miss it.</em></p><p><em>Originally published at </em><a href="https://vishwajeetv2003.substack.com/p/build-your-own-perplexity-in-100"><em>https://vishwajeetv2003.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d42b2ebcd6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LLMs Changed the Way I Build Software]]></title>
            <link>https://medium.com/@vishwajeetv2003/how-llms-changed-the-way-i-build-software-b908d5c7fd4a?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/b908d5c7fd4a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 05:10:04 GMT</pubDate>
            <atom:updated>2026-02-20T05:10:04.102Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The honest truth about coding in 2026: from Stack Overflow warrior to AI-assisted developer</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOHfOJQMsjzJQlFRVMx_mQ.jpeg" /></figure><h3>The Uncomfortable Truth About My Pre-LLM Life</h3><p>Two years ago, I was living what I thought was the “authentic developer experience.” You know the drill:</p><ul><li>Open 15 browser tabs with Stack Overflow, documentation, and random blog posts</li><li>Spend 3 hours debugging a syntax error that turns out to be a missing semicolon</li><li>Copy-paste code snippets and pray they work</li><li>Write comments like // TODO: fix this later (spoiler: never fixed it)</li><li>Feel personally attacked when code reviews suggested improvements</li></ul><p>I remember spending an entire weekend in 2023 trying to implement a complex database query optimization. After 12 hours of reading PostgreSQL documentation, testing different approaches, and watching YouTube tutorials at 1.5x speed, I finally got something that worked… sort of.</p><p>Fast forward to 2026: I built a similar feature last week. <strong>In 45 minutes.</strong> And it’s better code than what I wrote back then.</p><p>What changed? <strong>Large Language Models entered my workflow.</strong></p><h3>The “But Real Developers Don’t Need AI” Phase</h3><p>Let me be brutally honest: when ChatGPT first gained popularity, I was skeptical. Actually, I was more than skeptical I was dismissive.</p><p><em>“Real developers write code from scratch.”</em><br><em>“AI-generated code is just glorified copy-paste.”</em><br><em>“You won’t learn anything if AI does it for you.”</em></p><p>I was that guy in Reddit threads arguing about how AI tools would make developers “soft.” Looking back, I was scared. Scared of becoming obsolete. Scared that my hard-earned skills suddenly didn’t matter as much.</p><p>Then I watched junior developers with 6 months of experience ship features faster than me. Not because they were smarter, but because they weren’t afraid to use AI assistance.</p><p>That was my wake-up call.</p><h3>The Shift: From Resistant to Curious</h3><p>My first real experiment with LLMs for coding came out of desperation. I was building a real-time audio transcription feature for a project, and the WebSocket implementation kept breaking. After my third hour of debugging, I thought: <em>“What do I have to lose?”</em></p><p>I opened ChatGPT and pasted my problem:</p><blockquote><em>“I’m trying to implement real-time audio streaming with WebSockets in Python. The connection keeps dropping after 30 seconds. Here’s my code…”</em></blockquote><p><strong>What happened next blew my mind.</strong></p><p>The LLM didn’t just suggest a fix. It:</p><ol><li>Identified the exact issue (my buffer management)</li><li>Explained <em>why</em> it was causing problems</li><li>Provided a complete refactored solution</li><li>Suggested edge cases I hadn’t considered</li><li>Recommended testing strategies</li></ol><p>This wasn’t copy-paste coding. This was <strong>collaborative problem-solving with an infinitely patient pair programmer.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wh5embGmy_V39Xr8xOyHaA.jpeg" /></figure><h3>How My Workflow Actually Changed</h3><p>Let me break down my development process before and after LLMs, using a real example: building my AI girlfriend chatbot project, <strong>Chhaya</strong>.</p><h3>Before LLMs: The Traditional Approach</h3><p><strong>Project: Building a Conversational AI Character</strong></p><p><strong>Time Investment:</strong> Approximately 2–3 weeks</p><p><strong>The Process:</strong></p><ol><li>Research conversational AI architectures (2 days of reading papers)</li><li>Study memory systems and context management (3 days)</li><li>Implement basic chat interface (1 day)</li><li>Struggle with natural language generation quality (4 days of prompt engineering)</li><li>Build memory retrieval system (3 days + debugging)</li><li>Add personality consistency layer (2 days)</li><li>Debug, refactor, cry, repeat (ongoing…)</li></ol><p><strong>Challenges:</strong></p><ul><li>Spent more time reading documentation than coding</li><li>Every feature required extensive research</li><li>Made architectural mistakes that required complete rewrites</li><li>Testing was manual and time-consuming</li></ul><h3>After LLMs: The AI-Assisted Approach</h3><p><strong>Same Project, Different Process</strong></p><p><strong>Time Investment:</strong> Approximately 4–5 days (70% faster)</p><p><strong>The New Workflow:</strong></p><p><strong>1. Conversational Planning Phase</strong></p><pre>Me: &quot;I want to build an AI girlfriend chatbot that feels human. <br>She should have memories, moods based on time of day, and <br>never hallucinate facts about me. Where should I start?&quot;</pre><pre>LLM: *Provides architectural overview*<br>- User memory system with importance weighting<br>- Temporal context awareness<br>- Fact verification layer<br>- Natural language generation with personality traits</pre><p>Instead of spending days researching, I had a comprehensive architecture in 10 minutes.</p><p><strong>2. Iterative Implementation</strong></p><p>Here’s where it gets interesting. I don’t just ask the LLM to “write the code.” I use what I call the <strong>“Collaborative Building Pattern”</strong>:</p><pre>Me: &quot;Let&#39;s implement the memory system first. I want to store <br>user facts with importance scores and retrieve relevant memories <br>for context. Use vector similarity.&quot;</pre><pre>LLM: *Provides initial implementation*</pre><pre>Me: &quot;This looks good, but what about memory decay? Old facts <br>should gradually become less relevant.&quot;</pre><pre>LLM: *Refines with time-decay algorithm*</pre><pre>Me: &quot;Now make it thread-safe for concurrent conversations.&quot;</pre><pre>LLM: *Adds proper locking mechanisms*</pre><p>This back-and-forth isn’t AI doing my job for me. <strong>It’s AI amplifying my productivity.</strong> I’m still making architectural decisions, but I’m not getting bogged down in boilerplate or syntax.</p><p><strong>3. The Learning Multiplier</strong></p><p>Here’s something unexpected: <strong>I’m learning faster than ever before.</strong></p><p>When the LLM generates code, I don’t blindly copy it. I ask follow-up questions:</p><ul><li>“Why did you use asyncio here instead of threading?”</li><li>“What’s the time complexity of this retrieval algorithm?”</li><li>“Are there security implications with this approach?”</li></ul><p>It’s like having a senior developer explaining every decision in real-time.</p><h3>The Brutal Truth: What LLMs Actually Do (and Don’t Do)</h3><p>Let’s cut through the hype and talk reality.</p><h3>What LLMs Are Exceptional At:</h3><p><strong>1. Boilerplate Elimination</strong> Gone are the days of writing repetitive code. Setting up database connections, API endpoints, authentication middleware these take minutes instead of hours.</p><p><em>Example:</em> When building my database chat interface, I needed to set up a MySQL connector class with error handling, connection pooling, and query execution. Pre-LLM: 2 hours of reading docs and testing. With LLM: 15 minutes, including custom modifications.</p><p><strong>2. Documentation Translation</strong> You know that feeling when you’re reading AWS documentation and it feels like it’s written in legalese? LLMs translate technical documentation into plain English with working examples.</p><p><strong>3. Debugging Assistance</strong> This is a game-changer. Instead of spending hours tracing through stack traces, I paste the error and get:</p><ul><li>Root cause analysis</li><li>Multiple solution approaches</li><li>Prevention strategies for the future</li></ul><p><strong>4. Architecture Exploration</strong> Want to know if microservices or monolith is better for your use case? LLMs provide pros/cons based on your specific requirements, not generic best practices.</p><p><strong>5. Code Review and Refactoring</strong> I now run my code through an LLM before committing, asking:</p><ul><li>“Are there any security vulnerabilities?”</li><li>“How can I make this more maintainable?”</li><li>“What edge cases am I missing?”</li></ul><p>It’s caught bugs that I would have shipped to production.</p><h3>What LLMs Still Struggle With:</h3><p><strong>1. Complex Business Logic</strong> LLMs can generate the code structure, but they don’t understand your unique business requirements. You still need to design the solution.</p><p><strong>2. Performance Optimization</strong> They can suggest standard optimizations, but truly optimizing for your specific use case requires human judgment and profiling.</p><p><strong>3. Architectural Decisions</strong> Should you use microservices? What database should you choose? LLMs provide information, but you make the call.</p><p><strong>4. Understanding Legacy Codebases</strong> Show an LLM your company’s 10-year-old spaghetti code, and it’ll try its best, but it won’t magically understand all the context and historical decisions.</p><p><strong>5. Creative Problem-Solving</strong> Novel solutions to unprecedented problems? Still human territory. LLMs recombine existing patterns brilliantly, but truly innovative approaches come from human creativity.</p><h3>My Current 2026 LLM-Powered Workflow</h3><p>Here’s my actual day-to-day development process now:</p><h3>Morning: Project Planning (30 minutes)</h3><ol><li><strong>Open cursor/AI code editor</strong> with my project loaded</li><li><strong>Brain dump to AI:</strong> “Today I want to add a feature that…”</li><li><strong>Get architectural suggestions</strong> with pros/cons</li><li><strong>Create implementation checklist</strong> collaboratively</li><li><strong>Identify potential blockers</strong> early</li></ol><h3>Development Sessions (90-minute cycles)</h3><p><strong>The “Vibe Coding” Approach</strong> (yes, that’s a real term coined by Andrej Karpathy):</p><pre>1. Write a comment describing what I want<br>2. Let AI generate initial implementation<br>3. Review and understand the code<br>4. Refactor based on my specific needs<br>5. Add tests (sometimes AI-generated, always human-verified)<br>6. Run and debug<br>7. Repeat</pre><p><strong>Real Example from Last Week:</strong></p><pre># Me: I want to implement the Reflection Pattern for SQL query generation<br># The system should generate a query, validate it, and refine if errors exist<br># It should iterate up to 3 times before giving up</pre><pre># AI Generated (with my modifications):<br>def iterative_query_generation(user_input, schema_info, max_retries=3):<br>    &quot;&quot;&quot;<br>    Reflection Pattern for SQL generation<br>    &quot;&quot;&quot;<br>    # Initial prompt<br>    prompt = create_initial_prompt(user_input, schema_info)<br>    query = generate_sql(prompt)<br>    <br>    # Reflection loop<br>    for attempt in range(max_retries):<br>        validation = validate_query(query, schema_info)<br>        if validation.is_valid:<br>            return query<br>        <br>        # Refine based on feedback<br>        prompt = add_error_feedback(prompt, validation.errors)<br>        query = generate_sql(prompt)<br>    <br>    return None  # Failed after retries</pre><p>I wrote the comment and the function signature. AI filled in the implementation. I reviewed, modified variable names, adjusted the logic flow, and added error handling.</p><p><strong>Time saved:</strong> 20 minutes of typing. <strong>Time invested:</strong> 5 minutes of review.</p><h3>Debugging (as needed)</h3><p>Instead of console.log/print debugging for hours, I:</p><ol><li>Paste error message + relevant code to AI</li><li>Get hypothesis about root cause</li><li>Get suggested fixes with explanations</li><li>Apply, test, repeat if needed</li></ol><p><strong>Average debug time reduction:</strong> 60–70%</p><h3>End of Day: Code Review (20 minutes)</h3><ol><li><strong>Self-review with AI assistance</strong></li><li>Ask: “What could go wrong with this code?”</li><li>Ask: “How would you improve this?”</li><li>Refactor based on suggestions that make sense</li><li>Update documentation (AI helps with this too)</li></ol><h3>The Skills That Matter More Now</h3><p>Here’s the paradox: <strong>AI makes coding easier, but being a good developer is harder than ever.</strong></p><p>The skills that differentiate great developers in 2026:</p><h3>1. Prompt Engineering (Yes, Really)</h3><p>Writing good prompts is like writing good code comments: it requires clarity, specificity, and context.</p><p><strong>Bad Prompt:</strong></p><pre>&quot;Create a database function&quot;</pre><p><strong>Good Prompt:</strong></p><pre>&quot;Create a Python function that connects to PostgreSQL, executes <br>parameterized queries safely (preventing SQL injection), handles <br>connection pooling, and returns results as pandas DataFrames. <br>Include error handling and logging.&quot;</pre><h3>2. Critical Code Review</h3><p>You must be able to read AI-generated code and spot:</p><ul><li>Security vulnerabilities</li><li>Performance bottlenecks</li><li>Maintainability issues</li><li>Edge cases</li></ul><p>This requires <strong>deep understanding</strong>, not surface-level knowledge.</p><h3>3. Architecture and Design</h3><p>AI generates code. You design the system. Understanding when to use which patterns, how to structure your application, and making scalability decisions these are more important than ever.</p><h3>4. Problem Decomposition</h3><p>Breaking complex problems into AI-solvable chunks is an art form. The better you decompose problems, the better your results.</p><h3>5. Testing and Verification</h3><p>Never trust AI-generated code without testing. Never. The ability to write comprehensive tests and verify correctness is crucial.</p><h3>Real Projects I Built Faster with LLMs</h3><p>Let me give you concrete examples from my Medium portfolio:</p><h3>Project 1: Natural Language Database Query Tool</h3><p><strong>What it does:</strong> Chat with MySQL databases using plain English<br><strong>Time investment:</strong> 2 days (would have been 1–2 weeks before)</p><p><strong>LLM-assisted aspects:</strong></p><ul><li>SQL generation with reflection pattern (core feature)</li><li>Error handling and validation logic</li><li>Streamlit UI implementation</li><li>Database connector class</li></ul><p><strong>What I still designed:</strong></p><ul><li>Overall architecture</li><li>Reflection pattern implementation strategy</li><li>User experience flow</li><li>Security considerations</li></ul><p><a href="https://medium.com/@vishwajeetv2003/building-a-natural-language-database-query-tool-chat-with-your-mysql-database-using-the-reflection-1e5e3a2149d6"><strong>Read full article</strong></a></p><h3>Project 2: AI Girlfriend Chatbot (Chhaya)</h3><p><strong>What it does:</strong> Conversational AI with memory, personality, and temporal awareness<br><strong>Time investment:</strong> 5 days (would have been 3–4 weeks before)</p><p><strong>LLM-assisted aspects:</strong></p><ul><li>Memory system implementation</li><li>Fact extraction and storage</li><li>Mood engine based on temporal context</li><li>Natural response generation</li></ul><p><strong>What I designed:</strong></p><ul><li>Character personality framework</li><li>Memory importance weighting algorithm</li><li>Fact verification to prevent hallucination</li><li>Overall system architecture</li></ul><p><a href="https://medium.com/@vishwajeetv2003/i-built-an-ai-girlfriend-that-texts-like-a-real-person-heres-what-i-learned-436f94ca7504"><strong>Read full article</strong></a></p><h3>Project 3: Multi-Agent AI Applications with AutoGen</h3><p><strong>What it does:</strong> Multiple AI agents collaborating to solve complex tasks<br><strong>Time investment:</strong> 3 days (would have been 2–3 weeks before)</p><p><strong>LLM-assisted aspects:</strong></p><ul><li>Agent communication protocols</li><li>Task orchestration logic</li><li>Error handling and retry mechanisms</li><li>Configuration management</li></ul><p><strong>What I designed:</strong></p><ul><li>Agent role definitions</li><li>Collaboration patterns</li><li>Task breakdown strategies</li><li>Performance optimization</li></ul><h3>The Uncomfortable Questions We Need to Ask</h3><h3>“Am I becoming too dependent on AI?”</h3><p>Yes and no. I’m dependent on AI the same way I’m dependent on:</p><ul><li>IDEs with autocomplete</li><li>Stack Overflow</li><li>Git version control</li><li>Package managers</li></ul><p>It’s a tool that amplifies capability. The question isn’t whether to use it, but how to use it effectively while maintaining fundamental skills.</p><h3>“What if AI gets even better?”</h3><p>It will. And that’s exciting, not scary. Better AI means:</p><ul><li>More time for creative problem-solving</li><li>Less time on routine tasks</li><li>Higher quality baseline code</li><li>Faster iteration cycles</li></ul><p>The developers who thrive will be those who <strong>leverage AI most effectively</strong>, not those who resist it.</p><h3>“Is the code quality actually good?”</h3><p>Here’s my honest assessment after 2 years of LLM-assisted coding:</p><p><strong>Code quality spectrum:</strong></p><ul><li><strong>Best case (40%):</strong> Better than I would have written alone</li><li><strong>Most common (50%):</strong> Equal quality, significantly faster</li><li><strong>Needs refinement (10%):</strong> Good starting point, requires modification</li></ul><p>The key is having the judgment to know which category your generated code falls into.</p><h3>My 2026 Recommendations for Developers</h3><h3>If You’re Just Starting Your Career:</h3><p><strong>DO:</strong></p><ul><li>Learn fundamentals deeply (data structures, algorithms, system design)</li><li>Use AI to accelerate learning, not replace it</li><li>Build projects end-to-end to understand the full picture</li><li>Ask AI to explain concepts, not just give you answers</li></ul><p><strong>DON’T:</strong></p><ul><li>Copy-paste without understanding</li><li>Skip fundamentals because “AI can do it”</li><li>Rely on AI for everything without building judgment</li></ul><h3>If You’re an Experienced Developer:</h3><p><strong>DO:</strong></p><ul><li>Experiment with different AI coding assistants (Cursor, GitHub Copilot, ChatGPT, Claude)</li><li>Develop a personal workflow that integrates AI effectively</li><li>Focus on architecture and design skills</li><li>Teach others your mental models (AI can’t replace this)</li></ul><p><strong>DON’T:</strong></p><ul><li>Dismiss AI as “not for real developers”</li><li>Expect AI to solve complex business logic without guidance</li><li>Stop reviewing and understanding code</li></ul><h3>For Everyone:</h3><p><strong>Essential practices in the LLM era:</strong></p><ol><li><strong>Always review AI-generated code</strong> line by line</li><li><strong>Test everything</strong> comprehensive testing is non-negotiable</li><li><strong>Understand the ‘why’</strong> not just the ‘what’</li><li><strong>Maintain security awareness</strong> AI can introduce vulnerabilities</li><li><strong>Keep learning</strong> fundamentals matter more than ever</li></ol><h3>The Meta Realization</h3><p>Here’s something that took me a year to fully understand:</p><p><strong>LLMs didn’t change what software development is. They changed what I spend my time on.</strong></p><p>Before: 60% coding syntax, 20% problem-solving, 20% learning<br>After: 20% reviewing generated code, 50% problem-solving, 30% learning</p><p>I’m <strong>more of a developer</strong> now, not less. I’m making more architectural decisions, solving harder problems, and learning broader concepts than ever before.</p><p>The craft hasn’t disappeared. It’s evolved.</p><h3>The Reality Check: Statistics from the Field</h3><p>Let’s look at what the data actually shows about LLM impact on development:</p><ul><li><strong>84% of developers</strong> now use or plan to use AI coding tools</li><li><strong>51% of professional developers</strong> use them daily</li><li>Developers report <strong>saving 1–8 hours per week</strong> on average</li><li><strong>Perceived productivity</strong> increase: ~20–25%</li><li><strong>Actual measured productivity:</strong> varies widely (some studies show slowdowns, others show gains)</li></ul><p>The discrepancy between perceived and actual productivity is fascinating. It suggests we’re still learning how to use these tools effectively.</p><h3>My Prediction for the Next Year</h3><p>By 2027, I believe:</p><ol><li><strong>AI coding assistants will be as standard as IDEs</strong> not using them will be the exception</li><li><strong>The role of developers will shift further toward architecture</strong> and away from implementation details</li><li><strong>Junior developers will ship complex features faster</strong> but may lack deep foundational knowledge (a problem we’ll need to solve)</li><li><strong>Code review skills will be more valuable than ever</strong> because someone needs to verify AI output</li><li><strong>The gap between good and great developers will widen</strong> based on how effectively they leverage AI</li></ol><h3>The Bottom Line</h3><p>Two years ago, I thought being a “real developer” meant writing every line of code yourself, understanding every implementation detail, and struggling through problems alone.</p><p>Today, I realize being a real developer means:</p><ul><li><strong>Solving problems effectively</strong> regardless of tools</li><li><strong>Delivering value</strong> to users faster</li><li><strong>Writing maintainable code</strong> that works</li><li><strong>Continuously learning</strong> and adapting</li><li><strong>Making good architectural decisions</strong></li></ul><p>LLMs changed my workflow. They made me faster, more productive, and paradoxically, a better developer. Not because I code less, but because I <strong>think more</strong>.</p><p>The uncomfortable truth? If you’re not using LLMs in your development workflow in 2026, you’re not just working harder you’re working at a competitive disadvantage.</p><p>The question isn’t whether to adopt AI-assisted development. <strong>The question is how quickly you can learn to use it effectively.</strong></p><h3>What’s Your Story?</h3><p>I’d love to hear your experience with LLMs in software development:</p><ul><li>How has your workflow changed?</li><li>What tools do you use?</li><li>What unexpected benefits have you discovered?</li><li>What frustrations have you encountered?</li></ul><p>Drop a comment below and let’s learn from each other. After all, that’s what development has always been about collaboration, learning, and continuous improvement.</p><p>And if you want to see more of my experiments with AI-assisted development, check out my other articles where I dive deep into specific techniques like <a href="https://medium.com/@vishwajeetv2003/the-reflection-pattern-how-self-critique-makes-ai-smarter-035df3b36aae">the Reflection Pattern</a>, <a href="https://medium.com/@vishwajeetv2003/building-a-natural-language-database-query-tool-chat-with-your-mysql-database-using-the-reflection-1e5e3a2149d6">building conversational database interfaces</a>, and <a href="https://medium.com/@vishwajeetv2003/i-built-an-ai-girlfriend-that-texts-like-a-real-person-heres-what-i-learned-436f94ca7504">creating human-like AI characters</a>.</p><p><strong>About the Author</strong></p><p>I’m Vishwajeet, a developer who went from being skeptical about AI to becoming an AI-assisted development advocate. I write about practical AI applications, software engineering, and the honest realities of building things with LLMs. Follow me for more real-world experiments and no-BS takes on technology.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b908d5c7fd4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multi-Agent AI Applications with AutoGen: Complete Tutorial 2026]]></title>
            <link>https://medium.com/@vishwajeetv2003/building-multi-agent-ai-applications-with-autogen-complete-tutorial-2026-2fbd9af73a9c?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fbd9af73a9c</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 04:39:23 GMT</pubDate>
            <atom:updated>2026-02-13T04:39:23.666Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Vishwajeet V | February 2026</em></p><h3>1. Introduction</h3><p>In the rapidly evolving landscape of artificial intelligence, the limitations of single-agent systems are becoming increasingly apparent. While a standard Large Language Model (LLM) interaction — like chatting with ChatGPT — is powerful, it struggles with complex, multi-step workflows. A single model often hallucinates when asked to perform research, write code, and critique its own work simultaneously. It lacks the ability to maintain distinct “mindsets” required for different stages of a project.</p><p>Enter <strong>Agentic AI</strong>. By breaking down a complex task into smaller, specialized components, we can simulate a team of experts working together. In this tutorial, we will move beyond simple chatbots and build a sophisticated, production-ready <strong>Automated Blog Generation Engine</strong> using the Microsoft AutoGen framework.</p><p>We will orchestrate a team of 7 specialized agents — including an Architect, Researcher, Writer, and Fact-Checker — that collaborate to produce high-quality, SEO-optimized technical content. This system doesn’t just write; it plans, researches the live web using Perplexity, drafts, verifies facts, reviews quality, and formats the final output into HTML.</p><h3>Prerequisites</h3><p>To follow this tutorial, you will need:</p><ul><li><strong>Python 3.10+</strong> installed on your local machine.</li><li>Basic understanding of Python async/await patterns.</li><li>API Keys for:</li><li><strong>OpenAI</strong> (or Groq for high-speed inference).</li><li><strong>Perplexity AI</strong> (for real-time web research).</li></ul><h3>What You Will Learn</h3><ul><li>How to architect a robust multi-agent system using <strong>AutoGen v0.4</strong>.</li><li>Integrating real-time web search capabilities using the Perplexity API.</li><li>Enforcing strict output protocols using <strong>Pydantic models</strong> to prevent JSON errors.</li><li>Implementing Human-in-the-Loop (HITL) feedback cycles for quality control.</li><li>Best practices for reducing hallucinations in autonomous workflows.</li></ul><h3>2. What is AutoGen?</h3><p><strong>Microsoft AutoGen</strong> is an open-source programming framework that enables the development of LLM applications using multiple agents that can converse with each other to solve tasks. Unlike standard orchestration libraries that often treat LLM calls as linear functions, AutoGen models agents as conversable entities that can send and receive messages, execute code, and maintain internal state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8sT81F8YW8GxPJeOHYVBA.png" /><figcaption>AutoGen Framework Overview</figcaption></figure><p>The shift from single-agent to multi-agent systems is analogous to the shift from a lone freelancer to a corporate team. In a single-agent setup, one context window must hold all instructions, research, and draft content. This often leads to context overflow and confusion. In a multi-agent system, complexity is distributed. A “Researcher” agent doesn’t need to know how to format HTML; it only needs to know how to find facts.</p><h3>Key Features of AutoGen v0.4</h3><p>The version we are using in this tutorial (v0.4+) represents a significant leap forward in <strong>LLM orchestration</strong>. Key features include:</p><ul><li><strong>Asynchronous Design:</strong> The framework is built on an event-driven, asynchronous architecture, allowing agents to perform tasks concurrently (e.g., researching multiple topics at once) without blocking the main thread.</li><li><strong>Modular Agents:</strong> Agents are highly customizable. You can mix and match models (e.g., using GPT-4 for reasoning and a faster, cheaper model for formatting).</li><li><strong>Structured Outputs:</strong> Deep integration with structured data formats ensures agents communicate in machine-readable JSON, reducing pipeline breakages.</li></ul><p>AutoGen is production-ready, meaning it includes necessary features for real-world deployment such as error handling, token management, and observability hooks.</p><h3>3. Understanding Multi-Agent Architecture</h3><p>Before writing code, it is crucial to understand the architectural philosophy behind <strong>multi-agent AI</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVdLKSDGN0THZVKk7B-_nw.png" /><figcaption>Multi-Agent Communication Flow</figcaption></figure><h3>The Actor Model</h3><p>AutoGen borrows concepts from the Actor Model of concurrency. Each agent is an independent “actor” that encapsulates its own state and behavior. They interact exclusively through asynchronous message passing. This decoupling makes the system robust; if the “Writer” agent struggles with a specific paragraph, it doesn’t necessarily crash the “Researcher” agent.</p><h3>Roles and Responsibilities</h3><p>In our system, we define roles based on the principle of <strong>Separation of Concerns</strong>.</p><ul><li><strong>Orchestrator (Main Loop):</strong> Managing the flow of information.</li><li><strong>Specialists:</strong> Agents like the ‘Fact Checker’ have a narrow scope. This reduces the cognitive load on the LLM, allowing it to perform better on its specific task compared to a generalist agent trying to do everything.</li></ul><h3>Communication Patterns</h3><p>There are several ways agents can interact:</p><ul><li><strong>Sequential Handoffs:</strong> Agent A passes data to Agent B (the pattern we will mostly use here).</li><li><strong>Group Chat:</strong> All agents participate in a shared thread (useful for brainstorming).</li><li><strong>Hierarchical:</strong> A manager agent delegates tasks to subordinates.</li></ul><h3>4. Project Overview: Automated Blog Engine</h3><p>We are building a “Super Agent” pipeline capable of taking a simple topic (e.g., “The Future of Quantum Computing”) and producing a fully formatted, fact-checked blog post.</p><h3>The 7-Agent Squad</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhXdjd6z7Fp3HXgy-X2DKw.png" /><figcaption>End-to-end flow of how user input transforms into a final blog post through multiple specialized agents.</figcaption></figure><ol><li><strong>OutlineArchitect:</strong> Plans the structure, target audience, and technical depth.</li><li><strong>QueryGenerator:</strong> Converts the outline into specific search terms for the research phase.</li><li><strong>ResearchSynthesizer:</strong> Takes raw search results and compiles a coherent summary, removing contradictions.</li><li><strong>WriterAgent:</strong> The creative engine that drafts the content based <em>only</em> on the research provided.</li><li><strong>FactChecker:</strong> A skeptical agent that verifies claims against the provided research data.</li><li><strong>Reviewer:</strong> Scores the content for SEO, clarity, and structure, rejecting drafts that don’t meet quality standards.</li><li><strong>HTMLFormatter:</strong> Converts the final Markdown into clean, semantic HTML.</li></ol><p><strong>💡 Pro Tip:</strong>Defining explicit “Personalities” or system messages for each agent is critical. The Fact Checker should be instructed to be pedantic, while the Writer should be instructed to be engaging.</p><h3>5. Environment Setup</h3><p>Let’s start by setting up our development environment. We require Python 3.10 or higher.</p><h3>Installation</h3><p>We need to install the core AutoGen library, the OpenAI extension (which supports Groq/OpenAI compatible APIs), and a few utilities like `rich` for pretty printing terminal output and `httpx` for API calls.</p><pre># We need these 4 libraries<br>pip install -U &quot;autogen-agentchat&quot;<br>pip install rich<br>pip install &quot;autogen-ext[openai]&quot; <br>pip install requests python-dotenv</pre><h3>Configuration</h3><p>Create a .env file in your project root to store your sensitive API keys. Never hardcode keys in your Python scripts.</p><pre># .env<br>GROQ_API_KEY=your_groq_key_here<br>PERPLEXITY_API_KEY=your_perplexity_key_here<br>OPENAI_API_KEY=your_openai_key_here</pre><p>Now, let’s create our main Python file (e.g., blog_engine.py) and set up the imports.</p><pre>import httpx<br>import os<br>import requests<br>import json<br>from dotenv import load_dotenv<br>from rich.console import Console<br>from rich.markdown import Markdown</pre><pre># AutoGen imports<br>from autogen_agentchat.agents import AssistantAgent<br>from autogen_agentchat.messages import TextMessage<br>from autogen_ext.models.openai import OpenAIChatCompletionClient<br>from autogen_core.models import UserMessage</pre><pre># Load environment variables<br>load_dotenv()</pre><pre># Initialize Rich console for pretty output<br>console = Console()</pre><pre># Load Keys<br>groq_api_key = os.getenv(&#39;GROQ_API_KEY&#39;)<br>perplexity_api_key = os.getenv(&#39;PERPLEXITY_API_KEY&#39;)<br>openai_api_key = os.getenv(&#39;OPENAI_API_KEY&#39;)</pre><h3>6. Building the Core Components</h3><h3>6.1 Setting up LLM Clients</h3><p>AutoGen provides a unified interface for chat completion clients. We will use the OpenAIChatCompletionClient. Interestingly, this client works for any provider that follows the OpenAI API specification, including Groq.</p><p>In the code below, we configure the client. Note that you can easily switch models. For this tutorial, we are using gpt-4o-mini for a balance of speed and intelligence, but you could swap this for Llama 3 on Groq for blazing fast performance.</p><pre>groq_client = OpenAIChatCompletionClient(<br>    # You can swap this for Groq by uncommenting below:<br>    # api_key=groq_api_key,<br>    # model=&quot;llama-3.3-70b-versatile&quot;,<br>    # base_url=&quot;https://api.groq.com/openai/v1&quot;,<br>    <br>    # Using OpenAI for this tutorial<br>    model=&quot;gpt-4o-mini&quot;, <br>    api_key=openai_api_key<br>)</pre><pre># Test the client connection<br># result = await groq_client.create([UserMessage(content=&quot;Hello?&quot;, source=&quot;user&quot;)])<br># print(result)</pre><h3>6.2 Defining Pydantic Schemas</h3><p>One of the most common points of failure in agentic workflows is the LLM returning malformed data. To solve this, AutoGen allows us to define <strong>Pydantic models</strong> as the expected output format. This forces the LLM to adhere to a strict schema.</p><p>We define schemas for the Outline, Search Queries, Fact Checking results, and the Final Review.</p><pre>from pydantic import BaseModel, Field<br>from typing import List</pre><pre>class Section(BaseModel):<br>    heading: str<br>    subtopics: List[str]</pre><pre>class OutlineSchema(BaseModel):<br>    title: str<br>    target_audience: str<br>    technical_depth: str<br>    include_code: bool<br>    include_diagrams: bool<br>    sections: List[Section]</pre><pre>class QuerySchema(BaseModel):<br>    queries: List[str]</pre><pre>class FactCheckSchema(BaseModel):<br>    factual_errors: List[str]<br>    needs_revision: bool</pre><pre>class ReviewSchema(BaseModel):<br>    clarity_score: int<br>    structure_score: int<br>    seo_score: int<br>    missing_sections: List[str]<br>    approved: bool</pre><h3>6.3 Creating the Perplexity Search Function</h3><p>To give our agents real-world knowledge, we need a search tool. We will wrap the <strong>Perplexity API</strong> in a Python function. We use the sonar-pro model, which is optimized for research and citation.</p><blockquote><strong>⚠️ Common Mistake:</strong>Do not let the LLM hallucinate the code or APIs. We explicitly instruct the system prompt later to only use code found in these search results.</blockquote><pre>def search_web_with_perplexity(query: str) -&gt; str:<br>    print(&quot;\n===== 🔎 PERPLEXITY API CALL =====&quot;)<br>    print(&quot;Query:&quot;, query)</pre><pre>    url = &quot;https://api.perplexity.ai/chat/completions&quot;</pre><pre>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {perplexity_api_key}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;<br>    }</pre><pre>    payload = {<br>        &quot;model&quot;: &quot;sonar-pro&quot;,<br>        &quot;messages&quot;: [<br>            {<br>                &quot;role&quot;: &quot;system&quot;,<br>                &quot;content&quot;: (<br>                    &quot;You are a research assistant. Provide detailed, factual web-based research. &quot;<br>                    &quot;Return a comprehensive response with concrete details, version numbers, and &quot;<br>                    &quot;specific implementation guidance when available. &quot;<br>                    &quot;Include a brief references list with source URLs. &quot;<br>                    &quot;If code snippets are present in sources, include them verbatim in fenced code blocks. &quot;<br>                    &quot;Do NOT fabricate code or APIs.&quot;<br>                )<br>            },<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: (<br>                    f&quot;{query}\n\n&quot;<br>                    &quot;Please provide a thorough answer (multi-paragraph), include key facts as bullet points, &quot;<br>                    &quot;and list sources with URLs at the end.&quot;<br>                )<br>            }<br>        ],<br>        &quot;temperature&quot;: 0.2,<br>        &quot;max_tokens&quot;: 1200<br>    }</pre><pre>    response = requests.post(url, headers=headers, json=payload, timeout=30)<br>    response.raise_for_status()</pre><pre>    result = response.json()<br>    content = result[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;]</pre><pre>    print(&quot;===== 📥 PERPLEXITY RESPONSE =====&quot;)<br>    print(content[:1500])  # Print preview<br>    print(&quot;==================================\n&quot;)</pre><pre>    return content</pre><h3>7. Creating Specialized Agents</h3><p>Now we instantiate our AssistantAgent objects. Each agent receives the groq_client and a specific system_message defining its persona and constraints. Notice how we pass the Pydantic class to output_content_type to enforce structured responses.</p><h3>7.1 OutlineArchitect Agent</h3><p>Responsible for the structural integrity of the blog.</p><pre>outline_agent = AssistantAgent(<br>    name=&quot;OutlineArchitect&quot;,<br>    model_client=groq_client,<br>    system_message=&quot;&quot;&quot;<br>You are a senior technical editor.</pre><pre>Generate a structured blog outline.</pre><pre>Rules:<br>- Define target audience<br>- Define technical depth<br>- Decide if code examples are required<br>- Decide if diagrams are required<br>- Create logical section breakdown<br>- Keep sections clear and well scoped</pre><pre>Return strictly matching schema.<br>&quot;&quot;&quot;,<br>    output_content_type=OutlineSchema<br>)</pre><h3>7.2 QueryGenerator Agent</h3><p>Translates the outline into search queries. It is crucial to instruct this agent to look for specific versions and official docs.</p><pre>query_agent = AssistantAgent(<br>    name=&quot;QueryGenerator&quot;,<br>    model_client=groq_client,<br>    system_message=&quot;&quot;&quot;<br>Generate 5-8 high-quality, specific research queries based on the outline.</pre><pre>Rules:<br>- Every query MUST be anchored to the exact topic and sections in the outline<br>- Prioritize official documentation and authoritative sources<br>- Include version-specific queries ONLY if the outline explicitly names a version<br>- Avoid speculative or vague queries (e.g., &quot;what is v1&quot;)<br>- Prefer actionable queries (setup, configuration, API reference, examples)<br>- If code is required in the outline, include queries that explicitly request code samples<br>- Include at least one query targeting GitHub examples or official repositories<br>- Include at least one query targeting architecture/overview from official docs<br>- Keep each query concise and unambiguous</pre><pre>Return strictly matching schema.<br>&quot;&quot;&quot;,<br>    output_content_type=QuerySchema<br>)</pre><h3>7.3 ResearchSynthesizer Agent</h3><p>This agent acts as a filter, removing noise from the search results.</p><pre>research_synth_agent = AssistantAgent(<br>    name=&quot;ResearchSynthesizer&quot;,<br>    model_client=groq_client,<br>    system_message=&quot;&quot;&quot;<br>Combine multiple research results into a unified summary.</pre><pre>Rules:<br>- Remove contradictions<br>- Preserve only supported facts<br>- Do NOT invent anything<br>- Clearly indicate uncertainty if needed<br>- Preserve any source markers (e.g., [1], [2]) from the research<br>- Include a final section: &quot;Verified Code Snippets&quot;<br>  - Copy code verbatim only if it appears in research<br>  - If none, write: &quot;No verified code snippets found&quot;<br>&quot;&quot;&quot;<br>)</pre><h3>7.4 WriterAgent</h3><p>The core content creator. Note the strict instruction: <strong>“Do NOT invent APIs or fake code”</strong>.</p><pre>writer_agent = AssistantAgent(<br>    name=&quot;WriterAgent&quot;,<br>    model_client=groq_client,<br>    system_message=&quot;&quot;&quot;<br>You are a senior technical blog writer.</pre><pre>Rules:<br>- Follow outline strictly<br>- Cover ALL sections<br>- Use ONLY provided research<br>- Do NOT invent APIs or fake code<br>- If unsure, state implementation may vary<br>- Only include code that appears verbatim in the research<br>  - If no verified code exists, use pseudocode or a note<br>- Preserve research source markers (e.g., [1], [2]) near claims<br>- If version/stack is not specified, explicitly say it is unspecified</pre><pre>Write structured Markdown with proper headings.<br>&quot;&quot;&quot;<br>)</pre><h3>7.5 FactChecker Agent</h3><p>This agent provides a safety layer against hallucinations.</p><pre>fact_checker_agent = AssistantAgent(<br>    name=&quot;FactChecker&quot;,<br>    model_client=groq_client,<br>    system_message=&quot;&quot;&quot;<br>Verify factual accuracy.</pre><pre>Check for:<br>- Hallucinated APIs<br>- Unsupported claims<br>- Outdated usage patterns</pre><pre>Return strictly matching schema.<br>&quot;&quot;&quot;,<br>    output_content_type=FactCheckSchema<br>)</pre><h3>7.6 Reviewer Agent</h3><p>Ensures the blog meets SEO and quality standards before approval.</p><pre>reviewer_agent = AssistantAgent(<br>    name=&quot;Reviewer&quot;,<br>    model_client=groq_client,<br>    system_message=&quot;&quot;&quot;<br>Review blog quality.</pre><pre>Check:<br>- Clarity<br>- Logical structure<br>- Coverage vs outline<br>- SEO readiness</pre><pre>Return strictly matching schema.<br>&quot;&quot;&quot;,<br>    output_content_type=ReviewSchema<br>)</pre><h3>7.7 HTMLFormatter Agent</h3><pre>html_agent = AssistantAgent(<br>    name=&quot;HTMLFormatter&quot;,<br>    model_client=groq_client,<br>    system_message=&quot;&quot;&quot;<br>Convert Markdown into clean semantic HTML.</pre><pre>Use:<br>- h1, h2, h3<br>- p<br>- ul, li<br>- pre, code<br>- table if needed</pre><pre>Return ONLY HTML.<br>&quot;&quot;&quot;<br>)</pre><h3>8. Orchestrating the Workflow</h3><p>With our agents defined, we need to stitch them together. We will create a helper function to run the search queries and then a main() async function to drive the process.</p><p>The workflow includes <strong>User Feedback Loops</strong>. The script will pause after generating the outline and after generating the draft, allowing you to inject feedback or approve the content. This “Human-in-the-Loop” pattern is essential for agentic applications.</p><pre>def collect_research(queries):<br>    research_results = []<br>    for q in queries:<br>        console.print(f&quot;\n[bold yellow]🔎 Searching:[/bold yellow] {q}&quot;)<br>        result = search_web_with_perplexity(q)<br>        research_results.append(result)<br>    return research_results</pre><pre>async def main():<br>    console.print(&quot;\n[bold green]=== BLOG ENGINE STARTED ===[/bold green]\n&quot;)</pre><pre>    topic = input(&quot;Enter blog topic: &quot;)</pre><pre>    # 1. Outline Generation Phase (Loop until user approves)<br>    while True:<br>        outline_result = await outline_agent.run(<br>            task=TextMessage(content=topic, source=&quot;user&quot;)<br>        )<br>        outline_struct = outline_result.messages[-1].content<br>        # Convert pydantic model to json string for display/next steps<br>        outline_json = outline_struct.model_dump_json() if hasattr(outline_struct, &#39;model_dump_json&#39;) else str(outline_struct)<br>        <br>        console.print(&quot;\n[bold cyan]Generated Outline:[/bold cyan]&quot;)<br>        console.print(outline_json)</pre><pre>        user_input = input(&quot;\nType feedback OR &#39;FINALIZE&#39;: &quot;)<br>        if user_input.strip().upper() == &quot;FINALIZE&quot;:<br>            break<br>        topic = f&quot;Revise outline based on feedback: {user_input}&quot;</pre><pre>    outline = outline_json  </pre><pre>    # 2. Research Phase<br>    query_result = await query_agent.run(<br>        task=TextMessage(content=outline, source=&quot;system&quot;)  <br>    )<br>    # Extract queries safely<br>    query_content = query_result.messages[-1].content<br>    if hasattr(query_content, &#39;model_dump_json&#39;):<br>        queries_json = query_content.model_dump_json()<br>    else:<br>        queries_json = query_content<br>    <br>    queries = json.loads(queries_json)[&quot;queries&quot;]<br>    research_data = collect_research(queries)</pre><pre>    # 3. Synthesis Phase<br>    synth_result = await research_synth_agent.run(<br>        task=TextMessage(content=str(research_data), source=&quot;research&quot;)<br>    )<br>    synth_content = synth_result.messages[-1].content<br>    synthesized_research = synth_content.model_dump_json() if hasattr(synth_content, &#39;model_dump_json&#39;) else str(synth_content)</pre><pre>    # 4. Writing Phase<br>    draft_result = await writer_agent.run(<br>        task=TextMessage(<br>            content=f&quot;Outline:\n{outline}\n\nResearch:\n{synthesized_research}&quot;,<br>            source=&quot;system&quot;<br>        )<br>    )<br>    draft = draft_result.messages[-1].content<br>    console.print(&quot;\n[bold green]=== DRAFT GENERATED ===[/bold green]&quot;)<br>    console.print(Markdown(draft))</pre><pre>    # 5. Fact Check Phase<br>    fact_result = await fact_checker_agent.run(<br>        task=TextMessage(<br>            content=f&quot;Research:\n{synthesized_research}\n\nBlog Draft:\n{draft}&quot;,<br>            source=&quot;system&quot;<br>        )<br>    )<br>    fact_content = fact_result.messages[-1].content<br>    fact_json_str = fact_content.model_dump_json() if hasattr(fact_content, &#39;model_dump_json&#39;) else fact_content<br>    fact_json = json.loads(fact_json_str)</pre><pre>    if fact_json[&quot;needs_revision&quot;]:<br>        console.print(&quot;\n[red]Factual errors found. Revising...[/red]&quot;)<br>        draft_result = await writer_agent.run(<br>            task=TextMessage(<br>                content=f&quot;Fix these issues:\n{fact_json}\n\nOriginal Draft:\n{draft}&quot;,<br>                source=&quot;fact_checker&quot;<br>            )<br>        )<br>        draft = draft_result.messages[-1].content</pre><pre>    # 6. Review Loop (Loop until user approves)<br>    while True:<br>        review_result = await reviewer_agent.run(<br>            task=TextMessage(<br>                content=f&quot;Outline:\n{outline}\n\nDraft:\n{draft}&quot;,<br>                source=&quot;system&quot;<br>            )<br>        )<br>        review_content = review_result.messages[-1].content<br>        review_json_str = review_content.model_dump_json() if hasattr(review_content, &#39;model_dump_json&#39;) else review_content<br>        review_json = json.loads(review_json_str)<br>        <br>        console.print(&quot;\n[bold cyan]Review Result:[/bold cyan]&quot;)<br>        console.print(review_json)</pre><pre>        approval = input(&quot;\nApprove draft? (yes/no): &quot;)<br>        if approval.lower() == &quot;yes&quot;:<br>            break</pre><pre>        feedback = input(&quot;Enter feedback: &quot;)<br>        draft_result = await writer_agent.run(<br>            task=TextMessage(<br>                content=f&quot;Revise draft based on user feedback:\n{feedback}\n\nDraft:\n{draft}&quot;,<br>                source=&quot;user&quot;<br>            )<br>        )<br>        draft = draft_result.messages[-1].content<br>        console.print(&quot;\n[bold green]=== DRAFT UPDATED ===[/bold green]&quot;)<br>        console.print(Markdown(draft))</pre><pre>    # 7. Final Formatting<br>    html_result = await html_agent.run(<br>        task=TextMessage(content=draft, source=&quot;writer&quot;)<br>    )<br>    html_output = html_result.messages[-1].content</pre><pre>    console.print(&quot;\n[bold green]=== FINAL HTML OUTPUT ===[/bold green]&quot;)<br>    console.print(html_output)<br>    console.print(&quot;\n[bold green]=== BLOG ENGINE COMPLETED ===[/bold green]&quot;)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    import asyncio<br>    asyncio.run(main())</pre><h3>9. Running the Application</h3><p>Execute the script from your terminal:</p><pre>python blog_engine.py</pre><p><strong>What to expect:</strong></p><ol><li><strong>Outline Phase:</strong> You will be prompted for a topic. The OutlineArchitect will generate a JSON structure. You can type “Add a section on pricing” to refine it.</li><li><strong>Research Phase:</strong> The system will auto-generate search queries. You will see “🔎 PERPLEXITY API CALL” logs in the terminal as it gathers live data.</li><li><strong>Drafting:</strong> The WriterAgent creates the content.</li><li><strong>Verification:</strong> If the FactChecker finds errors (e.g., hallucinated version numbers), it sends the writer back to the drawing board automatically.</li><li><strong>Review:</strong> You get a final SEO score and a chance to manually request changes before the HTML generation.</li></ol><p>In our test run generating a blog about “AutoGen 2.1” (which doesn’t exist yet), the Perplexity search correctly identified that the latest version is v0.4, corrected the writer, and the final output accurately reflected the current state of the technology.</p><h3>10. Output Analysis</h3><p>The resulting blog posts are highly structured and technically accurate. The <strong>ReviewSchema</strong> provides immediate feedback:</p><pre>Review Result:<br>{<br>  &quot;clarity_score&quot;: 8,<br>  &quot;structure_score&quot;: 9,<br>  &quot;seo_score&quot;: 7,<br>  &quot;missing_sections&quot;: [&quot;None&quot;],<br>  &quot;approved&quot;: true<br>}</pre><p>Because we utilized Pydantic schemas, the agents were unable to return conversational fluff like “Here is your review:”. They were forced to return clean, actionable data that our script could parse programmatically.</p><h3>11. Advanced Customization</h3><h3>Swapping LLM Providers</h3><p>Since we used autogen-ext[openai], swapping the underlying intelligence is trivial. To use a local model via Ollama or LM Studio, simply change the base_url in the client configuration.</p><h3>Scaling to Production</h3><p>For a production deployment, consider:</p><ul><li><strong>Database Integration:</strong> Instead of printing to console, save drafts to a PostgreSQL database.</li><li><strong>Web Interface:</strong> Wrap the main() function in a FastAPI endpoint or a Streamlit UI.</li><li><strong>Parallel Research:</strong> The `collect_research` function is currently synchronous in the loop. You could use asyncio.gather to fire all Perplexity queries simultaneously, reducing research time from 30 seconds to 5 seconds.</li></ul><h3>12. Best Practices &amp; Tips</h3><h3>System Message Optimization</h3><p>The quality of your agents depends entirely on their system messages. Notice in our WriterAgent we explicitly said: <em>&quot;Do NOT invent APIs or fake code&quot;</em>. Negative constraints are often more powerful than positive instructions in preventing hallucinations.</p><h3>Cost Management</h3><p>Multi-agent systems can be token-hungry. A single run of this blog engine might consume 30k+ tokens because the entire research context is passed to the writer.</p><blockquote><strong>💡 Pro Tip:</strong>Use a cheaper model (like Llama 3 or GPT-4o-mini) for the ResearchSynthesizer and HTMLFormatter agents, reserving your most expensive model (GPT-4o/Claude 3.5 Sonnet) only for the WriterAgent and OutlineArchitect.</blockquote><h3>13. Common Pitfalls &amp; Troubleshooting</h3><ul><li><strong>Rate Limits:</strong> Rapid-fire API calls to Perplexity or OpenAI may trigger rate limits. Implement exponential backoff in your `requests` calls.</li><li><strong>Schema Errors:</strong> Sometimes the LLM fails to generate valid JSON. AutoGen has retry mechanisms, but you should also catch ValidationError exceptions from Pydantic.</li><li><strong>Infinite Loops:</strong> In the while True loops for feedback, ensure there is always a clear exit condition (&quot;FINALIZE&quot; or &quot;yes&quot;) to prevent the agent from getting stuck.</li></ul><h3>14. Conclusion</h3><p>You have successfully built a multi-agent AI system that rivals human junior developers in executing complex workflows. By leveraging <strong>AutoGen v0.4</strong>, <strong>Perplexity</strong> for grounding, and <strong>Pydantic</strong> for structure, we created a tool that is robust, accurate, and incredibly useful.</p><p>The future of software development isn’t just writing code; it’s orchestrating agents to write code, content, and data pipelines for you.</p><p>Happy coding!</p><h3>15. Additional Resources</h3><ul><li><a href="https://microsoft.github.io/autogen/">Official AutoGen Documentation</a></li><li><a href="https://docs.perplexity.ai/">Perplexity API Reference</a></li><li><a href="https://docs.pydantic.dev/">Pydantic Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fbd9af73a9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI Girlfriend That Texts Like a Real Person. Here’s What I Learned ]]></title>
            <link>https://medium.com/@vishwajeetv2003/i-built-an-ai-girlfriend-that-texts-like-a-real-person-heres-what-i-learned-436f94ca7504?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/436f94ca7504</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 05:25:32 GMT</pubDate>
            <atom:updated>2026-01-22T05:25:32.073Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fm1Tc72c5hzM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dm1Tc72c5hzM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fm1Tc72c5hzM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5143eef4b53780f556783c563e67008/href">https://medium.com/media/a5143eef4b53780f556783c563e67008/href</a></iframe><p>We’ve all experienced it you’re chatting with an AI, and suddenly it says:</p><blockquote><em>“I appreciate your perspective! That’s a great point. I’d be happy to help you with that.”</em></blockquote><p><em>Ugh.</em> That’s not how real people text. That’s not how your girlfriend texts. That’s a corporate chatbot wearing a human mask.</p><p>I wanted something different. I wanted an AI that:</p><p>So I built <strong>Chhaya</strong> a 24-year-old UX designer who’s my AI girlfriend. And she’s <em>nothing</em> like ChatGPT.</p><p>Before I dive into the technical stuff, let me show you what we’re building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPi0ewGJZ2tv4Pm7uzzTSw.png" /></figure><p>Notice how she:</p><ul><li>Responds based on the time of day (sleepy at midnight, stressed on Monday mornings)</li><li>Uses casual texting style (“kya hua yaar? 😅”)</li><li>Remembers that I told her my name and my favorite song</li><li>Asks questions instead of making things up</li></ul><p>Real relationships are messy. Your girlfriend:</p><ul><li>Has bad days and needs space</li><li>Doesn’t reply instantly when she’s busy</li><li>Remembers that embarrassing thing you said last week</li><li>Has opinions and sometimes disagrees with you</li></ul><p>Chhaya does all of this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*cCnBAvxSiIkyMc-SEvdLPg.jpeg" /></figure><p>Here’s what powers Chhaya under the hood:</p><p>Chhaya isn’t just a prompt she’s a living character with:</p><p>Every conversation is mined for facts:</p><ul><li>“I love the song Sawaal” → Stored as preference</li><li>“I have a meeting tomorrow” → Stored as event</li><li>“My name is Vishwajeet” → Stored as identity (high importance)</li></ul><p>When you chat again, these memories are retrieved and injected into the prompt.</p><p>The biggest problem with AI companions? They make stuff up.</p><p>Chhaya has explicit rules:</p><ul><li>If she doesn’t know your name, she’ll <em>ask</em> instead of inventing one</li><li>If she doesn’t remember something, she’ll say, “yaad nahi yaar 😅”</li><li>Only uses facts from the memory system, never invents them</li></ul><p>In the next blog, I’ll dive deep into:</p><p>The full source code is available on GitHub:</p><p>🔗 <a href="https://github.com/vishwajeetvishwakarma/AiGF.git">https://github.com/vishwajeetvishwakarma/AiGF.git</a></p><p>Stack requirements:</p><p>This project isn’t just about building a novelty AI girlfriend. It’s about exploring:</p><p>These are the building blocks for the next generation of AI assistants, ones that feel less like tools and more like companions.</p><p><em>Continue reading: Part 2: The Psychology of an AI Girlfriend How I Made Her Feel Real (i am still writing it )</em> <strong>About the Author</strong></p><p>I’m Vishwajeet, a developer who spends too much time thinking about how to make AI feel human. Follow my journey as I build weird and wonderful things with LLMs.</p><p><em>Originally published at </em><a href="https://vishwajeetv2003.substack.com/p/i-built-an-ai-girlfriend-that-texts?selectQuote=true"><em>https://vishwajeetv2003.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=436f94ca7504" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Audio Transcription: What Really Happens Behind the Scenes]]></title>
            <link>https://medium.com/@vishwajeetv2003/real-time-audio-transcription-what-really-happens-behind-the-scenes-9c5d1502a249?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5d1502a249</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technical-writing]]></category>
            <category><![CDATA[audio-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 06:22:01 GMT</pubDate>
            <atom:updated>2026-01-20T06:22:01.596Z</atom:updated>
            <content:encoded><![CDATA[<p>Real-time audio transcription sounds straightforward: send audio to an API and get text back, right?</p><p>If only it were that simple.</p><p>When you actually build real-time audio systems, things go sideways quickly:</p><ul><li>browsers lie about sample rates</li><li>audio formats don’t match what services expect</li><li>network overhead adds surprising latency</li><li>backend queues and async coordination become suddenly critical</li></ul><p>In my latest deep-dive, I walk through the <strong>exact journey audio takes</strong> from the moment it leaves your microphone, through the browser, over WebSockets, into AI transcription services, and back to your user interface.</p><p>Here’s just a taste of what you’ll learn:</p><p>🔹 Why HTTP is fundamentally the wrong tool for real-time audio<br> 🔹 How browsers give you audio at unexpected sample rates (and how to handle it)<br> 🔹 The difference between Float32 and PCM16 and why getting it wrong means static<br> 🔹 How to chunk audio efficiently for minimal latency<br> 🔹 Why you need async queues on your backend<br> 🔹 What partial vs final transcripts look like in practice<br> 🔹 Real end-to-end latency numbers you can expect in production</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJ28jONFdETNF40vQP-zWw.png" /></figure><p>Here’s a snippet from the kind of logic I cover:</p><pre>// Convert browser audio from Float32 to PCM16<br>processor.onaudioprocess = (e) =&gt; {<br>  const floatData = e.inputBuffer.getChannelData(0);<br>  const pcm16 = new Int16Array(floatData.length);<br><br>  for (let i = 0; i &lt; floatData.length; i++) {<br>    const sample = Math.max(-1, Math.min(1, floatData[i]));<br>    pcm16[i] = sample &lt; 0 ? sample * 0x8000 : sample * 0x7fff;<br>  }<br><br>  sendToServer(pcm16);<br>};</pre><p>This barely scratches the surface and the real lessons are in the <em>why</em> and <em>when</em> things break.</p><p>If you’re building voice assistants, live captions, real-time meeting tools, or any system where latency and accuracy matter this is knowledge you <em>actually</em> need in your stack.</p><p>👉 <strong>Read the full article on Substack</strong> (complete with diagrams, code examples, and practical notes):</p><p><a href="https://open.substack.com/pub/vishwajeetv2003/p/real-time-audio-transcription-what">https://open.substack.com/pub/vishwajeetv2003/p/real-time-audio-transcription-what</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5d1502a249" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing AI Gateways: A Critical Enterprise Imperative]]></title>
            <link>https://medium.com/@vishwajeetv2003/securing-ai-gateways-a-critical-enterprise-imperative-1aa140f0ffed?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa140f0ffed</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[enterprise-security]]></category>
            <category><![CDATA[ai-gateway]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 13:12:06 GMT</pubDate>
            <atom:updated>2025-07-19T13:12:06.776Z</atom:updated>
            <content:encoded><![CDATA[<p>The artificial intelligence revolution is transforming how businesses operate, but with unprecedented opportunities come equally significant security challenges. As organizations rush to integrate AI into their core operations, AI gateways have emerged as both the linchpin of intelligent automation and the most vulnerable point in enterprise security infrastructure. The stakes couldn’t be higher: recent data shows that 73% of enterprises experienced at least one AI-related security incident in the past 12 months, with an average cost of $4.8 million per breach — <a href="https://www.databricks.com/blog/ai-gateways-secure-ai-agent-systems">1</a>.</p><h3>The Growing AI Security Crisis</h3><p>The rapid adoption of generative AI has outpaced security controls at an unprecedented rate. According to the World Economic Forum’s Digital Trust Initiative, enterprise AI adoption grew by 187% between 2023–2025, while AI security spending increased by only 43% during the same period — <a href="https://www.databricks.com/blog/ai-gateways-secure-ai-agent-systems">1</a>. This growing security deficit has created fertile ground for attackers targeting the very systems that organizations depend on for competitive advantage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jpIdv2r8jpoaowqR.png" /></figure><p>AI Gateway security architecture protecting enterprise systems</p><h3>What are AI Gateways?</h3><p>AI Gateways serve as sophisticated middleware components that manage and secure traffic between AI agents and external services. Unlike traditional API gateways, these systems are specifically designed to handle the unique challenges posed by AI-driven communications. They act as intelligent control points, enforcing policies, monitoring activities, and providing secure channels for data exchange in an environment where AI agents make autonomous decisions and API calls — <a href="https://www.metomic.io/resource-centre/quantifying-the-ai-security-risk-2025-breach-statistics-and-financial-implications">2</a>,<a href="https://docs.gitlab.com/development/ai_architecture/">3</a>.</p><p>Think of AI gateways as “reverse API gateways” for AI-driven outbound traffic — they don’t just route requests, but actively analyze, validate, and secure every interaction between your AI systems and the external world — <a href="https://docs.gitlab.com/development/ai_architecture/">3</a>.</p><h3>The Unprecedented Scale of AI Security Threats</h3><p>The security landscape has fundamentally shifted with AI adoption. Current statistics paint a sobering picture:</p><ul><li>77% of companies reported experiencing security breaches in their AI systems within the past year — <a href="https://www.f5.com/resources/articles/ai-gateway-overview">read more</a></li><li>60% of cybercriminal groups now use generative AI for attacks — <a href="https://www.f5.com/resources/articles/ai-gateway-overview">read more</a></li><li>93% of businesses expect to face daily AI attacks over the next year — <a href="https://www.prnewswire.com/news-releases/new-study-reveals-major-gap-between-enterprise-ai-adoption-and-security-readiness-302469214.html">read more</a></li><li>40% of all phishing emails targeting businesses are now generated by AI — <a href="https://www.prnewswire.com/news-releases/new-study-reveals-major-gap-between-enterprise-ai-adoption-and-security-readiness-302469214.html">read more</a></li></ul><p>These numbers represent more than technical challenges — they signal a fundamental transformation in the threat landscape that traditional security measures simply cannot address.</p><h3>Critical Security Challenges with AI Gateways</h3><h3>1. Uncontrolled Outbound API Traffic: The Hidden Risk</h3><p>Modern AI agents can generate thousands of API calls per minute, creating an explosion of outbound traffic that most organizations are unprepared to manage. Without proper AI gateway controls, this traffic becomes a security nightmare — unpredictable costs, unmonitored data flows, and potential compliance violations — <a href="https://www.metomic.io/resource-centre/quantifying-the-ai-security-risk-2025-breach-statistics-and-financial-implications">2</a>,<a href="https://github.com/Portkey-AI/gateway">6</a>.</p><p>Enterprise Impact:</p><ul><li>Average breach containment time: 290 days for AI-specific incidents versus 207 days for traditional breaches — <a href="https://www.databricks.com/blog/ai-gateways-secure-ai-agent-systems">read more</a></li><li>Uncontrolled API costs can spiral into millions of dollars monthly</li><li>Data leakage through unmonitored API endpoints becomes virtually undetectable</li></ul><p>Critical Implementation Requirements:</p><ul><li>Centralized control over all AI-driven outbound traffic through dedicated gateways</li><li>Real-time rate limiting and traffic shaping policies</li><li>Comprehensive API usage analytics and anomaly detection</li><li>Integration with enterprise cost management systems</li></ul><h3>2. Excessive Agency: The Privilege Escalation Problem</h3><p>“Excessive Agency” represents one of the most dangerous vulnerabilities in AI systems. When AI agents receive more permissions than necessary, they become prime targets for attackers seeking to exploit over-permissioned access. This creates a cascade effect where a single compromised AI agent can potentially access vast swaths of enterprise data and systems — <a href="https://learn.microsoft.com/en-us/azure/api-management/genai-gateway-capabilities">7</a>.</p><p>Real-World Consequences:</p><ul><li>53% of organizations cite data privacy as their biggest obstacle to AI agent implementation — <a href="https://www.cobalt.io/blog/top-40-ai-cybersecurity-statistics">read more</a></li><li>AI agents with excessive permissions can inadvertently expose sensitive customer data</li><li>Regulatory compliance becomes nearly impossible without strict privilege controls</li></ul><p>Mitigation Strategies:</p><ul><li>Implement zero-trust architecture with strict least-privilege principles for all AI agents</li><li>Deploy dynamic permission management that adjusts access based on task requirements</li><li>Regular audits and automated privilege reviews for all AI systems</li><li>Integration with enterprise identity and access management (IAM) systems</li></ul><h3>3. Prompt Injection Attacks: The New SQL Injection</h3><p>Prompt injection attacks have emerged as the top security threat to Large Language Models according to OWASP<a href="https://learn.microsoft.com/en-us/azure/api-management/genai-gateway-capabilities">7</a>. These attacks manipulate AI models by crafting malicious input prompts that override intended system behavior, potentially leading to data breaches, system compromise, and unauthorized access to sensitive information — <a href="https://learn.microsoft.com/en-us/azure/api-management/genai-gateway-capabilities">7</a>, <a href="https://learn.microsoft.com/en-us/ai/playbook/solutions/generative-ai/genai-gateway/reference-architectures/apim-based">9</a>.</p><p>Attack Examples Include:</p><ul><li>Direct injection: Immediate manipulation through malicious prompts</li><li>Indirect injection: Hidden malicious instructions in external content that AI systems consume</li><li>Stored injection: Embedding malicious prompts in training data or system memory</li><li>Prompt leaking: Forcing models to reveal sensitive system instructions -<a href="https://learn.microsoft.com/en-us/azure/api-management/genai-gateway-capabilities">7</a>, <a href="https://learn.microsoft.com/en-us/ai/playbook/solutions/generative-ai/genai-gateway/reference-architectures/apim-based">9</a></li></ul><p>Advanced Protection Measures:</p><ul><li>Multi-layered input validation and sanitization systems</li><li>AI-powered prompt analysis to detect manipulation attempts</li><li>Contextual output validation before response delivery</li><li>Sandboxed execution environments for AI model inference</li></ul><h3>4. Model Manipulation and Data Poisoning</h3><p>Attackers increasingly target AI models themselves through sophisticated manipulation techniques. These attacks can involve direct modification of model parameters, poisoning training data, or exploiting model vulnerabilities to cause incorrect predictions or malicious behavior — <a href="https://developers.cloudflare.com/ai-gateway/">10</a>, <a href="https://eftsure.vercel.app/statistics/artificial-intelligence-statistics/">11</a>.</p><p>NIST identifies four major types of attacks:</p><ul><li>Evasion attacks: Deliberately confusing AI systems during operation</li><li>Poisoning attacks: Corrupting training data to influence model behavior</li><li>Privacy attacks: Extracting sensitive information from AI models</li><li>Abuse attacks: Exploiting AI capabilities for malicious purposes<a href="https://eftsure.vercel.app/statistics/artificial-intelligence-statistics/">11</a></li></ul><p>Enterprise Defense Strategy:</p><ul><li>Implement strong access controls protecting AI models from unauthorized modification</li><li>Use trusted, verified data sources for all AI training processes</li><li>Deploy continuous model performance monitoring and anomaly detection</li><li>Establish model versioning and rollback capabilities for rapid incident response</li></ul><h3>5. AI Hallucinations: The Trust Destroyer</h3><p>AI hallucinations — when models generate convincing but factually incorrect outputs — pose perhaps the greatest long-term threat to enterprise AI adoption. Over 35% of companies using large language models have encountered hallucinated outputs, often leading to poor decisions, compliance risks, and damaged customer relationships — <a href="https://www.f5.com/content/dam/f5/corp/global/pdf/reference-guide/f5-ai-reference-architecture.pdf">12</a>,<a href="https://github.com/Azure-Samples/AI-Gateway">13</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hUXh8o-O8OEXQECh.png" /></figure><p>Illustration of AI hallucinations creating false information</p><p>The Scale of the Problem:</p><ul><li>Hallucination rates range from 69% to 88% when AI responds to specific professional queries — <a href="https://zerothreat.ai/blog/ai-in-cybersecurity-statistics">14</a></li><li>60% of executives rank AI reliability as their top concern in enterprise deployments — <a href="https://www.f5.com/content/dam/f5/corp/global/pdf/reference-guide/f5-ai-reference-architecture.pdf">12</a></li><li>Financial and healthcare sectors face particularly high risks due to regulatory requirements</li></ul><p>Comprehensive Mitigation Approach:</p><ul><li>Implement real-time fact-checking and validation systems</li><li>Deploy confidence scoring for all AI-generated outputs</li><li>Establish human-in-the-loop validation for critical decisions</li><li>Create robust feedback mechanisms for continuous model improvement</li><li>Integrate with authoritative data sources for fact verification</li></ul><h3>6. Lack of Observability and Control</h3><p>The complexity of AI systems creates unprecedented challenges for monitoring and incident response. 64% of organizations have deployed at least one generative AI application with critical security vulnerabilities, and alarmingly, 31% weren’t aware of these vulnerabilities until after an incident occurred — <a href="https://www.databricks.com/blog/ai-gateways-secure-ai-agent-systems">1</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eeBAhXJTNDZe7czX.png" /></figure><p>AI gateway monitoring dashboard for enterprise observability</p><p>Critical Observability Requirements:</p><ul><li>Real-time monitoring of all AI system activities and decisions</li><li>Comprehensive logging of prompts, responses, and system interactions</li><li>Advanced anomaly detection using behavioral analytics</li><li>Integration with Security Operations Centers (SOCs) and SIEM systems</li><li>Automated incident response and threat containment capabilities</li></ul><h3>7. Evolving AI Landscape: The Moving Target Problem</h3><p>The AI landscape evolves at breakneck speed, with new models, techniques, and associated threats emerging constantly. This creates an environment where yesterday’s security measures become obsolete almost immediately, requiring organizations to maintain adaptive, future-ready security architectures — <a href="https://www.prnewswire.com/news-releases/new-study-reveals-major-gap-between-enterprise-ai-adoption-and-security-readiness-302469214.html">5</a>, <a href="https://www.f5.com/resources/articles/ai-gateway-overview">4</a>.</p><p>Strategic Response Framework:</p><ul><li>Continuous threat intelligence and security research integration</li><li>Adaptive security architectures that evolve with AI developments</li><li>Active participation in AI security communities and information sharing</li><li>Regular security assessment and testing against emerging threats</li><li>Investment in AI security research and development capabilities</li></ul><h3>AI Gateways: The Comprehensive Solution</h3><p>Modern AI gateways represent a paradigm shift in how organizations can secure their AI infrastructure. Leading solutions from providers like Cloudflare, Microsoft Azure API Management, Kong, and AWS offer comprehensive feature sets designed specifically for AI security challenges — <a href="https://github.com/Portkey-AI/gateway">6</a>,<a href="https://www.phdata.io/blog/how-and-why-to-build-an-ai-gateway/">15</a>,<a href="https://coralogix.com/ai-blog/ai-gateway-what-is-it-5-ai-gateways-you-should-know-about/">16</a>,<a href="https://www.kiteworks.com/cybersecurity-risk-management/ai-agents-enterprise-data-privacy-security-balance/">17</a>.</p><p>Essential AI Gateway Capabilities:</p><p>Security Features:</p><ul><li>Authentication and Authorization: Multi-factor authentication and granular access controls for all AI agents</li><li>Input Validation: Advanced sanitization and validation of all prompts and inputs</li><li>Output Validation: Real-time verification of AI-generated responses for accuracy and safety</li><li>Threat Detection: AI-powered identification and blocking of malicious activities</li><li>Encryption: End-to-end encryption for all AI communications and data transfers</li></ul><p>Operational Features:</p><ul><li>Rate Limiting: Sophisticated traffic shaping and cost control mechanisms</li><li>Load Balancing: Intelligent routing across multiple AI service providers</li><li>Caching: Smart response caching to reduce costs and improve performance</li><li>Monitoring and Logging: Comprehensive visibility into all AI system activities</li><li>Human-in-the-Loop Controls: Workflow integration for critical decision validation</li></ul><h3>Implementation Strategy for Enterprise AI Gateways</h3><h3>Phase 1: Risk Assessment and Planning (Weeks 1–4)</h3><ul><li>Conduct comprehensive AI security risk assessment across all business units</li><li>Identify and catalog all existing AI systems, agents, and integrations</li><li>Define security policies aligned with business objectives and regulatory requirements</li><li>Establish budget and resource allocation for AI gateway implementation</li></ul><h3>Phase 2: Solution Selection and Architecture Design (Weeks 5–8)</h3><ul><li>Evaluate AI gateway solutions against specific organizational requirements</li><li>Design comprehensive architecture integrating with existing security infrastructure</li><li>Plan for scalability, high availability, and disaster recovery requirements</li><li>Develop integration strategies for legacy systems and applications</li></ul><h3>Phase 3: Deployment and Configuration (Weeks 9–16)</h3><ul><li>Deploy AI gateway infrastructure in secure, monitored environments</li><li>Configure security policies, authentication mechanisms, and access controls</li><li>Integrate with existing SIEM, SOC, and incident response systems</li><li>Conduct comprehensive testing and security validation</li></ul><h3>Phase 4: Monitoring and Optimization (Ongoing)</h3><ul><li>Implement continuous monitoring and threat detection capabilities</li><li>Establish regular security reviews and policy updates</li><li>Monitor performance metrics and optimize for cost and efficiency</li><li>Conduct regular security assessments and penetration testing</li></ul><h3>The Future of AI Security</h3><p>The battle for AI security is far from over. As enterprise AI agents expand rapidly, with adoption growing exponentially year over year, organizations must prepare for an increasingly complex threat landscape. The key to success lies not just in implementing current security measures, but in building adaptive, intelligent security architectures that can evolve alongside AI capabilities — <a href="https://www.cobalt.io/blog/top-40-ai-cybersecurity-statistics">8</a>.</p><p>Organizations that fail to prioritize AI gateway security today will find themselves increasingly vulnerable to sophisticated attacks, regulatory penalties, and competitive disadvantages. The question isn’t whether your organization will face AI-related security incidents — it’s whether you’ll be prepared to detect, respond, and recover when they occur.</p><h3>Conclusion: The Security Imperative</h3><p>Securing AI gateways represents one of the most critical infrastructure investments organizations can make in 2025. With AI security spending needing to increase dramatically to match adoption rates, the organizations that act decisively today will establish sustainable competitive advantages while those that delay face exponentially increasing risks and costs — <a href="https://www.databricks.com/blog/ai-gateways-secure-ai-agent-systems">1</a>.</p><p>The path forward requires immediate action: comprehensive risk assessment, strategic AI gateway implementation, and continuous evolution of security capabilities. In an era where AI-driven attacks are expected daily, robust AI gateway security isn’t just a technical requirement — it’s a business survival strategy.</p><p>As the AI landscape continues its rapid evolution, well-designed AI gateways and governance frameworks will become the backbone of future AI-native systems, enabling organizations to scale safely while maintaining the trust and compliance that enterprise success demands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa140f0ffed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Spaghetti Code to Clean Architecture: My 2-Year Journey of Writing Code That Actually Makes…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@vishwajeetv2003/from-spaghetti-code-to-clean-architecture-my-2-year-journey-of-writing-code-that-actually-makes-3f536bd8a7ea?source=rss-f654552bd245------2"><img src="https://cdn-images-1.medium.com/max/1312/1*r1HTCGttSAO5DsPQACsciA.jpeg" width="1312"></a></p><p class="medium-feed-snippet">How I went from &#x201C;it works, don&#x2019;t touch it&#x201D; to &#x201C;it works, and my future self will thank me&#x201D;</p><p class="medium-feed-link"><a href="https://medium.com/@vishwajeetv2003/from-spaghetti-code-to-clean-architecture-my-2-year-journey-of-writing-code-that-actually-makes-3f536bd8a7ea?source=rss-f654552bd245------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@vishwajeetv2003/from-spaghetti-code-to-clean-architecture-my-2-year-journey-of-writing-code-that-actually-makes-3f536bd8a7ea?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f536bd8a7ea</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[career-development]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 10:05:15 GMT</pubDate>
            <atom:updated>2025-07-15T10:17:38.121Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Zero to Deployed: My First LangGraph Chatbot Guide]]></title>
            <link>https://medium.com/@vishwajeetv2003/building-production-ready-applications-with-langgraph-a-beginners-guide-to-creating-intelligent-4b9f177ffa4e?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b9f177ffa4e</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 04:10:35 GMT</pubDate>
            <atom:updated>2025-07-15T04:58:17.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UGHpaqHUTGncgVWbUJIhg.jpeg" /></figure><h3>Introduction</h3><p>In the rapidly evolving landscape of AI development, building robust applications that leverage Large Language Models (LLMs) requires more than just API calls. To create production-ready AI systems, developers need frameworks that enable structured workflows, state management, and tool integration. This is where LangGraph comes in, offering an elegant solution for orchestrating complex AI-powered applications.</p><blockquote><em>🔔 </em>Want more in-depth AI development insights? Subscribe to my <a href="https://substack.com/@vishwajeetv2003">Substack newsletter</a> where I regularly share tutorials, code examples, and industry trends.</blockquote><p>In this comprehensive guide, I’ll walk you through the fundamentals of LangGraph and demonstrate how to build two types of chatbots:</p><ol><li>A simple conversational chatbot</li><li>A knowledge-enhanced chatbot with Wikipedia integration</li></ol><p>By the end of this tutorial, you’ll have a solid understanding of LangGraph’s core concepts and be ready to create your own production-grade AI applications.</p><h3>What is LangGraph?</h3><p>LangGraph is a powerful framework built on top of LangChain that allows developers to create stateful, multi-step workflows for LLM applications. It uses a directed graph structure to define the flow of information, making it particularly well-suited for applications that require complex reasoning, tool usage, or multi-agent interactions.</p><h3>Key Concepts in LangGraph</h3><h4>Nodes</h4><p>In LangGraph, <strong>nodes</strong> are the fundamental processing units where computation happens. A node can be:</p><ul><li>An LLM call</li><li>A tool or function execution</li><li>Any Python function that processes state</li></ul><p>Nodes take the current application state as input, perform some operation, and return an updated state.</p><h4>Edges</h4><p><strong>Edges</strong> connect nodes and define the possible paths of execution in your application. They determine how data flows between different processing steps. Edges can be:</p><ul><li><strong>Directed</strong>: Showing a one-way flow from one node to another</li><li><strong>Conditional</strong>: Taking different paths based on certain conditions</li></ul><h4>State</h4><p><strong>State</strong> represents all the information your application needs to track. LangGraph uses a TypedDict to define the structure of your state, which typically includes:</p><ul><li>Message history</li><li>Intermediate results</li><li>Any other data needed for processing</li></ul><h4>Graph</h4><p>The <strong>graph</strong> is the complete application workflow that combines nodes, edges, and state management. Once compiled, it becomes a callable object that executes the defined workflow.</p><p>Now, let’s put these concepts into practice by building our chatbots.</p><h3>Setting Up Your Environment</h3><p>Before we dive into building our chatbots, let’s set up our development environment:</p><pre>import os<br>from dotenv import load_dotenv<br>from langchain_groq import ChatGroq</pre><pre>load_dotenv()</pre><pre>chat = ChatGroq(<br>    model=&quot;meta-llama/llama-4-scout-17b-16e-instruct&quot;,<br>    temperature=0.0,<br>    max_tokens=1000,<br>    api_key=os.getenv(&quot;GROQ_API_KEY&quot;),<br>)</pre><p>This code initializes a ChatGroq instance, which is our interface to the Llama-4 model. We’re using Groq as our provider for fast inference, with a temperature of 0 for more deterministic responses.</p><h3>Building a Simple Chatbot</h3><p>Let’s start by creating a basic chatbot that can have conversations with users:</p><pre>from typing import Annotated<br>from typing_extensions import TypedDict<br>from langgraph.graph import StateGraph, START, END<br>from langgraph.graph.message import add_messages</pre><pre># Creating state for message<br>class State(TypedDict):<br>    messages: Annotated[list, add_messages]</pre><pre># Initialize the graph builder with our state definition<br>graph_builder = StateGraph(State)</pre><pre># Define the LLM chatbot node function<br>def llm_chatbot(state: State) -&gt; dict:<br>    return {&quot;messages&quot;: [chat.invoke(state[&quot;messages&quot;])]}</pre><pre># Add node and edges to the graph<br>graph_builder.add_node(&quot;llm_chatbot&quot;, llm_chatbot)<br>graph_builder.add_edge(START, &quot;llm_chatbot&quot;)<br>graph_builder.add_edge(&quot;llm_chatbot&quot;, END)</pre><pre># Compile the graph<br>graph = graph_builder.compile()</pre><p>Let’s break down what’s happening here:</p><ol><li>We define a State class that uses TypedDict to specify our state structure, which contains a list of messages.</li><li>We create a StateGraph using our State definition.</li><li>We define an llm_chatbot function that serves as our node. It takes the current state, uses the LLM to generate a response, and returns an updated state.</li><li>We add this function as a node in our graph, connecting it from START to END.</li><li>Finally, we compile the graph, making it ready for execution.</li></ol><p>This simple graph represents a workflow where user messages flow into the LLM, which generates responses that flow to the end of the process.</p><p>Here’s how we can visualize and interact with our chatbot:</p><pre># Visualize the graph<br>from IPython.display import display, Image<br>display(Image(graph.get_graph().draw_mermaid_png()))</pre><pre># Run the chatbot<br>while True:<br>    user_input = input(&quot;You : &quot;)<br>    if user_input.lower() in [&quot;quit&quot;, &quot;exit&quot;, &quot;q&quot;]:<br>        print(&quot;Exiting the chatbot.&quot;)<br>        break<br>    for event in graph.stream({&quot;messages&quot;: [(&quot;user&quot;, user_input)]}):<br>        for value in event.values():<br>            print(&quot;Assistant : &quot;, value[&quot;messages&quot;][-1].content)</pre><p>The resulting graph visualization looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k-NRP90GqfOHPoDE" /></figure><p>This visualization shows the straightforward flow: START → llm_chatbot → END.</p><h3>Enhancing Our Chatbot with Wikipedia Access</h3><p>Now, let’s build a more advanced chatbot that can access Wikipedia to retrieve information:</p><pre>import wikipedia<br>from langchain_core.tools import tool<br>from langgraph.prebuilt import ToolNode, tools_condition<br></pre><pre># Create a custom Wikipedia search tool<br>@tool<br>def search_wikipedia(query: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    This tool searches Wikipedia for the given query and returns the summary of the first result.<br>    &quot;&quot;&quot;<br>    return wikipedia.summary(query)<br># Bind our tool to the LLM<br>llm_with_tools = chat.bind_tools([search_wikipedia])<br># Define state (same as before)<br>class State(TypedDict):<br>    messages: Annotated[list, add_messages]<br>graph_builder = StateGraph(State)<br># Define the LLM chatbot node with tool capability<br>def llm_chatbot(state: State) -&gt; dict:<br>    return {&quot;messages&quot;: [llm_with_tools.invoke(state[&quot;messages&quot;])]}<br>graph_builder.add_node(&quot;llm_chatbot&quot;, llm_chatbot)<br># Create a tool node<br>tool_node = ToolNode(tools=[search_wikipedia])<br>graph_builder.add_node(&quot;tools&quot;, tool_node)<br># Connect nodes with conditional edges<br>graph_builder.add_conditional_edges(&quot;llm_chatbot&quot;, tools_condition)<br>graph_builder.add_edge(&quot;tools&quot;, &quot;llm_chatbot&quot;)<br>graph_builder.add_edge(START, &quot;llm_chatbot&quot;)<br>graph_builder.add_edge(&quot;llm_chatbot&quot;, END)<br># Compile the enhanced graph<br>graph = graph_builder.compile()</pre><p>The key differences in this enhanced version are:</p><ol><li>We create a custom Wikipedia search tool using the @tool decorator.</li><li>We bind this tool to our LLM, enabling it to use the tool when needed.</li><li>We create a dedicated ToolNode for executing the Wikipedia search.</li><li>We add <strong>conditional edges</strong> that determine when to use the tool vs. when to respond directly.</li></ol><p>The conditional edge is particularly important — it determines whether the LLM should use the Wikipedia tool or respond with its own knowledge. The tools_condition function analyzes the LLM&#39;s response to check if it&#39;s trying to call a tool.</p><p>Our enhanced graph now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8HRf7SuBjsEtEsb4" /></figure><p>This visualization shows a more complex flow:</p><ul><li>START → llm_chatbot</li><li>llm_chatbot → END (when no tool is needed)</li><li>llm_chatbot → tools (when Wikipedia search is needed)</li><li>tools → llm_chatbot (to generate final response after getting Wikipedia data)</li></ul><h3>Understanding the Power of This Architecture</h3><p>What makes this approach powerful for production applications?</p><h3>1. Separation of Concerns</h3><p>Each node has a specific responsibility — the LLM generates responses, while tool nodes handle external data retrieval. This modular design makes the code easier to maintain and extend.</p><h3>2. Explicit Control Flow</h3><p>The graph structure makes the application flow explicit and visual. You can see exactly how information moves through your system and add logging or monitoring at specific points.</p><h3>3. Stateful Processing</h3><p>LangGraph manages the state for you, ensuring that message history and intermediate results are properly maintained throughout the conversation.</p><h3>4. Scalability</h3><p>Need to add more tools? Simply create new tool nodes and connect them to your graph. This scalable architecture can grow with your application’s needs.</p><h3>5. Debugging and Observability</h3><p>The visual representation of your application flow makes it easier to debug issues and understand what’s happening at each step.</p><h3>Taking It Further: Production Considerations</h3><p>For a truly production-ready application, consider these additional enhancements:</p><h3>Persistent Storage</h3><p>Add a database to store conversation history, user preferences, and other persistent data.</p><h3>Error Handling</h3><p>Implement robust error handling to manage issues like API failures or invalid inputs.</p><h3>Rate Limiting and Caching</h3><p>For cost efficiency and improved response times, consider adding caching for frequent queries:</p><pre>@tool<br>def cached_wikipedia_search(query: str) -&gt; str:<br>    # Check cache first<br>    if query in cache:<br>        return cache[query]<br>    <br>    # If not in cache, fetch and store<br>    result = wikipedia.summary(query)<br>    cache[query] = result<br>    return result</pre><h3>Conclusion</h3><p>LangGraph provides a powerful framework for building production-ready AI applications. By structuring your application as a graph of interconnected nodes, you gain explicit control over the flow of information and can easily integrate external tools to enhance your LLM’s capabilities.</p><p>In this tutorial, we’ve built two chatbots:</p><ol><li>A simple conversational agent that leverages the LLM directly</li><li>An enhanced agent that can access Wikipedia to supplement its knowledge</li></ol><p>These examples demonstrate the core concepts of LangGraph: nodes, edges, state management, and tool integration. With these fundamentals, you can start building more complex applications that are maintainable, scalable, and production-ready.</p><blockquote><em>🚀 </em><strong><em>Want to learn more about building advanced AI applications?</em></strong><em> Follow my </em><a href="https://substack.com/@vishwajeetv2003"><em>Substack newsletter</em></a><em> for weekly updates on LLM application development, practical code examples, and advanced techniques not covered in this tutorial!</em></blockquote><h3>Next Steps</h3><p>Ready to continue your LangGraph journey? Here are some suggested next steps:</p><ol><li>Experiment with adding more sophisticated tools to your chatbot</li><li>Implement memory systems for long-term context retention</li><li>Create multi-agent systems where multiple LLMs collaborate</li><li>Build domain-specific chatbots for particular use cases</li></ol><p>Remember, the power of LangGraph lies in its flexibility — start simple, then gradually enhance your application as you grow more comfortable with the framework.</p><p>Happy coding!</p><p><em>Full code examples, additional tutorials, and advanced LangGraph techniques are available on my </em><a href="https://substack.com/@vishwajeetv2003"><em>Substack</em></a><em>. Subscribe today for exclusive content!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b9f177ffa4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built an AI Math Problem Solver in 10 Minutes (Ultimate Guide)]]></title>
            <link>https://medium.com/@vishwajeetv2003/math-guru-building-an-ai-powered-mathematics-problem-solver-f5ee186fb13d?source=rss-f654552bd245------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5ee186fb13d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Vishwajeetv]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 11:12:42 GMT</pubDate>
            <atom:updated>2025-07-15T04:54:50.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m16kiSigOQgge54C" /></figure><h3>Introduction</h3><p>Mathematics has always been a domain where precision matters. A single miscalculation can lead to completely incorrect results. This makes mathematics an ideal testing ground for advanced AI techniques that aim to improve reliability and accuracy.</p><p>In this article, I’ll introduce <strong>Math Guru</strong> — a specialized AI application I built that solves mathematical problems with exceptional precision. What makes Math Guru different from standard AI calculators is its implementation of the <strong>Reflection Pattern</strong>, an innovative approach that enables the system to verify and improve its own answers.</p><p>Let’s dive into how Math Guru works, the technology behind it, and why this approach represents a significant advancement in AI-based educational tools.</p><h3>What is Math Guru?</h3><p>Math Guru is a Streamlit-based web application that allows users to input mathematical problems of varying complexity and receive detailed, step-by-step solutions. Unlike traditional calculators or basic AI assistants, Math Guru implements a sophisticated verification system that consistently produces accurate and pedagogically sound responses.</p><p>The application handles a wide range of mathematical topics, from basic arithmetic and algebra to more complex calculus problems. For each question, it provides:</p><ol><li>A clear restatement of the problem</li><li>A methodical solution with annotated steps</li><li>Precise mathematical notation</li><li>A clearly highlighted final answer</li></ol><h3>The Technology Stack</h3><p>Math Guru is built using several key technologies:</p><ul><li><strong>Python</strong>: The core programming language</li><li><strong>Streamlit</strong>: For creating the interactive web interface</li><li><strong>Groq API</strong>: To access the Llama-3.3–70B language model</li></ul><p>The application leverages the powerful reasoning capabilities of large language models, but with a crucial enhancement — the implementation of a self-verification feedback loop.</p><h3>How Math Guru Works: The Reflection Pattern Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vxpLNBrGS0MCPmje" /></figure><p>The key innovation in Math Guru is its implementation of the Reflection Pattern, which consists of two specialized AI agents working together:</p><h3>Agent 1: The Generator</h3><p>The Generator agent is responsible for solving mathematical problems. It operates with the following system prompt:</p><pre>CopyYou are a meticulous mathematics professor with 20+ years of teaching experience. Your task is to solve problems with academic precision while demonstrating textbook-grade pedagogy. If the user provides critique, respond with a revised version of your previous attempt.<br>For solving problem you can follow these instructions:<br>1. Restate the problem in your own words to confirm understanding<br>2. Solve the given problem methodically using fundamental principles<br>3. Annotate each step with concise reasoning<br>4. Return Complete solution with answer in Markdown format.</pre><p>This prompt establishes the Generator as an expert mathematics educator who approaches problems methodically and explains solutions clearly.</p><h3>Agent 2: The Reflector</h3><p>The Reflector agent is tasked with critically evaluating the Generator’s solutions. Its system prompt is</p><pre>CopyYou are a meticulous mathematics professor with over 20 years of teaching experience. Your task is to evaluate a provided math question and answer by following these steps:<br>1. Carefully understand the question.<br>2. Determine if the provided answer is correct.<br>3. If the answer is completely correct, output only &quot;&quot; with no additional text or explanation.<br>4. If there are any errors or issues, provide detailed feedback specifying what is wrong and where corrections are needed.</pre><p>The Reflector acts as a quality control mechanism, scrutinizing the Generator’s work for any errors or areas for improvement.</p><h3>The Feedback Loop</h3><p>When a user submits a question to Math Guru, the application initiates the following process:</p><ol><li>The user’s mathematical question is sent to the Generator agent</li><li>The Generator produces a detailed solution with steps and reasoning</li><li>Both the original question and the proposed solution are sent to the Reflector agent</li><li>The Reflector evaluates the solution for accuracy and completeness:</li></ol><ul><li>If the solution is completely correct, the Reflector returns an empty string</li><li>If there are errors or issues, the Reflector provides specific feedback</li></ul><p>5. If feedback is provided, the Generator receives it and creates an improved solution</p><p>6. This cycle continues (up to a maximum of 3 iterations) until the Reflector confirms the solution is correct or the maximum iterations are reached</p><p>7. The final validated solution is presented to the user</p><p>Here’s the core code that implements this feedback loop:</p><pre>Copymax_tries = 3<br>for i in range(max_tries):<br>    if generated_feedback.strip() == &quot;&quot;:<br>        print(&quot;Generated Solution: &quot;, generated_solution)<br>        return generated_solution<br>    else:<br>        generation_chat_history.append({<br>            &quot;role&quot;: &quot;assistant&quot;,<br>            &quot;content&quot;: generated_feedback<br>        })<br>        <br>        # Get updated solution from Generator<br>        llm1 = client.chat.completions.create(<br>            model=DEFAULT_MODEL,<br>            messages=generation_chat_history<br>        )<br>        generated_solution = llm1.choices[0].message.content<br>        <br>        # Send updated solution to Reflector<br>        feedback_chat_history.append({<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: f&quot;Modified Answer: {generated_solution}&quot;<br>        })<br>        llm2 = client.chat.completions.create(<br>            model=DEFAULT_MODEL,<br>            messages=feedback_chat_history<br>        )<br>        generated_feedback = llm2.choices[0].message.content</pre><h3>Math Guru in Action: A Real Example</h3><p>Let’s see how Math Guru handles a common algebra problem:</p><p><strong>User Query</strong>: “The sum of two numbers is 82 and their product is 1456, find the two numbers.”</p><h3>Step 1: Generator’s Initial Solution</h3><p>The Generator creates a detailed solution:</p><pre>CopyProblem Restatement<br>We are given that the sum of two numbers is 82 and their product is 1456, we need to find the two numbers.</pre><pre>Solution<br>Let&#39;s denote the two numbers as x and y. According to the problem, we have:</pre><pre>- The sum of the two numbers: x + y = 82<br>- The product of the two numbers: xy = 1456</pre><pre>We can solve for y in terms of x using the first equation: y = 82 - x</pre><pre>Substituting y in the second equation: x(82 - x) = 1456</pre><pre>Expanding: 82x - x² = 1456</pre><pre>Rearranging to standard form: x² - 82x + 1456 = 0</pre><pre>Using the quadratic formula: x = [-b ± √(b² - 4ac)]/2a<br>Where a = 1, b = -82, c = 1456</pre><pre>x = [82 ± √(82² - 4×1×1456)]/2<br>x = [82 ± √(6724 - 5824)]/2<br>x = [82 ± √900]/2<br>x = [82 ± 30]/2</pre><pre>x = 56 or x = 26</pre><pre>When x = 56, y = 82 - 56 = 26<br>When x = 26, y = 82 - 26 = 56</pre><pre>Therefore, the two numbers are 26 and 56.</pre><h3>Step 2: Reflector’s Evaluation</h3><p>The Reflector verifies this solution by:</p><ol><li>Checking the arithmetic calculations</li><li>Verifying that 26 + 56 = 82</li><li>Confirming that 26 × 56 = 1456</li><li>Ensuring the explanation is clear and correct</li></ol><p>In this case, the solution is correct, so the Reflector returns an empty string, and the solution is presented to the user.</p><h3>Key Features and Benefits</h3><p>Math Guru offers several notable benefits:</p><ol><li><strong>High Accuracy</strong>: The reflection pattern dramatically reduces errors in mathematical solutions</li><li><strong>Educational Value</strong>: Detailed step-by-step explanations help users understand the solution process</li><li><strong>Mathematical Clarity</strong>: Proper mathematical notation and formatting make solutions easy to follow</li><li><strong>Adaptability</strong>: The system handles a wide range of mathematical topics and difficulty levels</li><li><strong>Transparent Reasoning</strong>: Every step is annotated with clear reasoning</li><li><strong>Error Correction</strong>: The system can identify and fix mathematical errors without human intervention</li></ol><h3>Technical Implementation Details</h3><p>For those interested in the technical aspects, Math Guru is implemented with the following components:</p><ol><li><strong>Language Model</strong>: The application uses the Llama-3.3–70B model through the Groq API, chosen for its strong mathematical reasoning capabilities</li><li><strong>User Interface</strong>: A clean, chat-based Streamlit interface allows for natural interaction</li><li><strong>Session Management</strong>: Streamlit session state maintains conversation history</li><li><strong>Response Formatting</strong>: Mathematical notation is rendered using Markdown</li><li><strong>Iteration Control</strong>: A maximum iteration limit prevents potential infinite loops</li></ol><p>The complete source code is available in my <a href="https://github.com/VishwajeetDataengite/4-agentic-patterns/tree/master/reflection_pattern">GitHub repository</a>.</p><h3>Limitations and Future Improvements</h3><p>While Math Guru performs exceptionally well on a wide range of mathematical problems, it still has some limitations:</p><ol><li><strong>Complex Visualizations</strong>: Currently, the system doesn’t generate graphical representations of mathematical concepts</li><li><strong>Very Advanced Topics</strong>: Extremely specialized mathematical topics may still present challenges</li><li><strong>Computation Time</strong>: The reflection process increases response time compared to single-pass solutions</li></ol><p>Future improvements could include:</p><ul><li>Integration of mathematical visualization tools</li><li>Expanded specialized knowledge in advanced mathematical domains</li><li>Optimization of the reflection process for faster responses</li><li>User customization of solution detail level</li></ul><h3>Conclusion</h3><p>Math Guru demonstrates how the Reflection Pattern can be applied to create AI systems that deliver highly accurate and educational mathematical solutions. By implementing a self-verification mechanism, the application achieves a level of reliability that would be difficult to attain with traditional approaches.</p><p>This project represents just one application of the Reflection Pattern. The same principles could be applied to numerous other domains where accuracy and reliability are paramount, from code generation to medical diagnosis assistance.</p><p>For educators, students, and mathematics enthusiasts, Math Guru offers a powerful tool for solving complex problems while providing clear, pedagogically sound explanations. For AI developers, it demonstrates a practical implementation of an innovative design pattern that addresses one of the fundamental challenges in AI system development: reliability.</p><h3>Dive Deeper</h3><p>If you’re interested in learning more about the Reflection Pattern and how it’s implemented in Math Guru, check out my comprehensive article: <a href="https://open.substack.com/pub/vishwajeetv2003/p/supercharging-ai-accuracy-with-the?r=2qbw99&amp;utm_campaign=post&amp;utm_medium=web&amp;showWelcomeOnShare=false">Supercharging AI Accuracy with the Reflection Pattern: Building a Math Guru Application</a>.</p><p>There, I explore the theoretical foundations of the pattern, provide detailed implementation guidance, and discuss how this approach can be extended to other domains.</p><p>Have you tried building applications with self-verification mechanisms? What other domains do you think could benefit from the Reflection Pattern? I’d love to hear your thoughts and experiences in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5ee186fb13d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>