<?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 Biresh Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Biresh Kumar Singh on Medium]]></description>
        <link>https://medium.com/@bireshkumar1964?source=rss-12f5c0e98e39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C8BFoetjG2ZdUhqoYLyzXQ.jpeg</url>
            <title>Stories by Biresh Kumar Singh on Medium</title>
            <link>https://medium.com/@bireshkumar1964?source=rss-12f5c0e98e39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:29:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bireshkumar1964/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[Stinking Backend Notes (Part 1)]]></title>
            <link>https://medium.com/@bireshkumar1964/stinking-backend-notes-part-1-a874d0349c33?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/a874d0349c33</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 05:45:20 GMT</pubDate>
            <atom:updated>2026-08-20T05:49:21.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*R8b9qe8a0Y2Oz6Yb.png" /><figcaption>Image — Repository Design Pattern (Source : <a href="https://dev.to/manukanne/a-python-implementation-of-the-unit-of-work-and-repository-design-pattern-using-sqlmodel-3mb5">https://dev.to/manukanne/a-python-implementation-of-the-unit-of-work-and-repository-design-pattern-using-sqlmodel-3mb5</a>)</figcaption></figure><p><em>Not an exhaustive list — just patterns and gotchas that kept showing up while building real-time, async backend systems. I was working on a voice-based interview platform (FastAPI + a streaming AI model + Firestore) when most of these clicked for me, so a few examples below come from that context. But none of this is specific to interview apps — the same problems show up in chat apps, live collaboration tools, video calls, trading systems, anything that streams data between two parties in real time.</em></p><h3>Why You Almost Never Let Two Clients Talk Directly</h3><p>Say you’re building anything where a browser needs to talk to a third-party AI service, payment provider, or any external API in real time. The tempting shortcut is to let the browser connect straight to that service.</p><p>Don’t. Here’s an example of what that back-and-forth might look like once you put your backend in the middle:</p><pre>{<br>  &quot;type&quot;: &quot;audio_output&quot;,<br>  &quot;data&quot;: &quot;&lt;ai voice&gt;&quot;<br>}</pre><p>Your server forwards it back:</p><pre>await candidate_ws.send(ai_audio)</pre><p>Trivial code. But the reason it exists is the whole point.</p><h3>Why the client can’t talk to the third party directly</h3><p>Because you need:</p><ul><li>✔ Authentication</li><li>✔ Control over the session (pause, stop, redirect)</li><li>✔ Abuse/cheating prevention</li><li>✔ A saved record of what happened (transcript, logs)</li><li>✔ Progress tracking</li><li>✔ The ability to inject context or instructions mid-session</li><li>✔ Scoring or post-processing after the fact</li></ul><p>Your backend isn’t just relaying bytes — it becomes a controlled proxy, not a dumb pipe. This is true whether you’re proxying an AI model, a payment gateway, or a third-party chat API. Anytime the client-side connection would otherwise bypass your business logic, put a server in the middle.</p><h3>Real-time sessions need state, even though HTTP taught you to avoid it</h3><p>A live session is not stateless in the way a typical REST request is. You have to track things like:</p><ul><li><strong>Current step/question</strong> — to know what’s being asked or expected right now</li><li><strong>Is the other party currently speaking/acting</strong> — avoid interrupt collisions</li><li><strong>Transcript / history so far</strong> — needed for evaluation, auditing, or resuming</li><li><strong>Is the session still active?</strong> — stop processing if it’s already closed</li><li><strong>Time elapsed</strong> — enforce timeouts or limits</li><li><strong>Is your own side still “talking”?</strong> — prevent double-sends</li><li><strong>Current stage</strong> — e.g., Intro → Main flow → Closing</li></ul><p>None of this is unique to interviews — any stateful, long-lived connection (a game session, a live support chat, a collaborative document) needs some version of this list.</p><h3>asyncio.Event — A Signal, Not a Value</h3><p>asyncio.Event is an async synchronization primitive — a way for different async tasks to wait for a signal without blocking the event loop. Think of it like a traffic light shared between coroutines:</p><ul><li>Initially → RED (not set)</li><li>When something important becomes ready → you call .set() → it turns GREEN</li><li>Anyone blocked on .wait() is instantly allowed to continue</li></ul><p>This pattern is useful anywhere one part of your system needs to say “don’t proceed until I’m ready,” without polling in a loop.</p><p><strong>Defining it:</strong></p><pre>self.ready = asyncio.Event()</pre><p>At this point, self.ready.is_set() == False — meaning &quot;the system is NOT ready yet.&quot;</p><p><strong>Triggering the signal</strong>, typically after some setup/handshake step succeeds:</p><pre>if &quot;setupComplete&quot; not in response:<br>    ...</pre><pre>self.session_id = setup_complete.get(&quot;sessionId&quot;)<br>self.ready.set()</pre><p>This is the exact moment you’re saying: “the downstream connection is established — it’s safe to start streaming.”</p><p><strong>Waiting for it</strong>, usually somewhere in your request-handling code:</p><pre>await interview_manager.ready.wait()</pre><p>That line means: “do not send anything yet — wait until the backend has confirmed the connection is live.” Any two-phase startup (connect, then confirm readiness) benefits from this instead of sleeping-and-checking in a loop.</p><h3>asyncio.Queue as a Buffer Between Independent Tasks</h3><p>asyncio.Queue acts as a buffer and handshake layer between independent async tasks, so they don&#39;t block on or depend on each other&#39;s timing. This shows up constantly in any system with two separate data flows moving in opposite directions.</p><h3>Two queues, two directions</h3><pre>self.client_message_queue: asyncio.Queue = asyncio.Queue()<br>self.server_message_queue: asyncio.Queue[str] = asyncio.Queue()</pre><ul><li><strong>client_message_queue</strong> — Client → Upstream service — input waiting to be forwarded</li><li><strong>server_message_queue</strong> — Upstream service → Client — responses waiting to be delivered</li></ul><h3>Queue 1: client → upstream</h3><p><strong>Producer</strong> — whatever handles incoming client messages just enqueues them:</p><pre>await self.client_message_queue.put(message)</pre><p>It doesn’t send anything itself. It just says: “here’s new data, whoever’s responsible for sending it can take it from here.”</p><p><strong>Consumer</strong> — a background task pulls from the queue and does the actual send:</p><pre>message = await self.client_message_queue.get()<br>await self._server_ws.send(message)</pre><p><strong>Why the separation matters:</strong> the code that receives client input usually runs inside your web framework’s request/connection handler, which needs to stay fast and non-blocking. If you sent directly from there:</p><pre>await self._server_ws.send(message)</pre><p>You’d risk:</p><ul><li>blocking request handling</li><li>race conditions if the upstream connection reconnects</li><li>losing messages during a reconnect/resume</li><li>tight coupling between layers that should be independent</li></ul><p>The queue decouples <em>receiving</em> input from <em>transmitting</em> it.</p><h3>Queue 2: upstream → client</h3><p><strong>Producer</strong> — when the upstream service sends a response, it’s dropped into a queue rather than sent straight to the client:</p><pre>await self._queue_message_for_client(response)</pre><p>Which internally does:</p><pre>await self.server_message_queue.put(message_str)</pre><p>So the code handling the upstream connection doesn’t need to care whether the client is slow, disconnected, or mid-reconnect. It just keeps listening and queuing.</p><p><strong>Consumer</strong> — a separate loop delivers to the client:</p><pre>current_message = await self.server_message_queue.get()<br>await self._client_ws.send_text(current_message)</pre><p>This task is the one responsible for handling retries and reconnects.</p><h3>This is the producer–consumer pattern</h3><p>Instead of the fragile version:</p><pre>Upstream handler → send to client immediately → crash if client is gone</pre><p>You get:</p><pre>Producer → Queue → Consumer</pre><p>Which buys you:</p><ul><li>✔ Backpressure handling</li><li>✔ Retry ability</li><li>✔ Disconnection tolerance</li><li>✔ Ordering guarantees</li><li>✔ No cross-task blocking</li></ul><p>This pattern generalizes well beyond WebSocket proxies — it’s the same shape you’d use for a job queue between an API and a worker, or between any producer and consumer that shouldn’t be tightly coupled in time.</p><h3>Why Your Two Data Flows Don’t Need to Look Symmetric</h3><p>If you have a proxy sitting between two connections, you might expect four symmetric pieces:</p><ul><li>forward-from-client</li><li>forward-to-upstream ❓</li><li>forward-from-upstream</li><li>forward-to-client</li></ul><p>But often only three exist, and that’s not a bug — it’s because your web framework is already doing the fourth job for you.</p><h3>The key insight</h3><p>There are two different ingestion models happening at once:</p><ul><li><strong>Client → Backend</strong> — driven by the web framework (framework-driven) — needs its own loop? ❌ No</li><li><strong>Upstream service → Backend</strong> — driven by you (socket-driven) — needs its own loop? ✅ Yes</li></ul><p>The asymmetry exists because one side is already managed by your framework’s event loop, and the other isn’t.</p><h3>Why you don’t need a separate forward-to-upstream task</h3><p>Trace the client → upstream path. Your framework already runs a receive loop for you, something like:</p><pre>while True:<br>    msg = await websocket.receive_text()<br>    await interview_manager.handle_client_message(msg)</pre><p>That loop <em>is</em> your forward-to-upstream stage — just implemented by the framework and your route handler, not written by hand inside your service class.</p><p>The handler that receives client input is intentionally tiny, because it’s called synchronously from that framework loop:</p><pre>await self.client_message_queue.put(message)</pre><p>If you added another forwarding task on top of this, you’d end up with:</p><pre>Framework receive loop<br>    ↓<br>your extra forwarding loop<br>    ↓<br>queue</pre><p>That’s double buffering for no benefit.</p><h3>Why the upstream side does need both directions</h3><p>The upstream connection (to the AI service, payment provider, whatever it is) isn’t managed by your framework — you opened it yourself:</p><pre>async with websockets.connect(...) as server_ws:</pre><p>So now <em>you</em> own both:</p><ul><li>✔ reading from it (forward-from-upstream)</li><li>✔ writing back to the client safely (forward-to-client)</li></ul><p>No framework does that part for you.</p><h3>Side by side</h3><p><strong>Client side (framework owns the receive loop):</strong></p><pre>Framework websocket loop   ← already exists<br>        │<br>        ▼<br>handle_client_message()<br>        │<br>        ▼<br>client_message_queue<br>        │<br>        ▼<br>forward_from_client()   ← sends to upstream</pre><p><strong>Upstream side (you own everything):</strong></p><pre>forward_from_server()   ← must listen manually<br>        │<br>        ▼<br>server_message_queue<br>        │<br>        ▼<br>forward_to_client()     ← must deliver manually</pre><p>The “missing” forward-to-upstream task is really: your framework’s receive loop plus your own message handler.</p><h3>Why this asymmetry is actually good design</h3><p>Trying to force symmetry here would cost you:</p><ul><li>backpressure awareness that the framework already gives you for free</li><li>a simpler connection lifecycle (the framework owns the client connection)</li><li>validation happening before you even enqueue anything</li><li>clean shutdown behavior when the client disconnects</li></ul><p>The framework handles client IO, your code handles the external service’s IO. That’s a clean separation of concerns — not a gap you need to fill in.</p><h3>asyncio.wait with FIRST_COMPLETED — Tasks That Live or Die Together</h3><pre>done, pending = await asyncio.wait(<br>    [client_task, server_task, queue_to_client_task, silence_monitor_task],<br>    return_when=asyncio.FIRST_COMPLETED,<br>)<br>for task in pending:<br>    task.cancel()</pre><p>What this actually means: “run all of these concurrently, and as soon as <em>any one</em> of them exits — successfully or with an error — wake me up.”</p><p>It does not mean “whichever finishes first wins.” It means these tasks are meant to live together as a unit. If any one of them dies, the whole group (the session, the connection, the job) is considered over, and everything else gets cleaned up. This pattern is handy anywhere you’re running several cooperating background tasks that only make sense as long as all of them are alive.</p><h3>Callback Type Hints — Callable[[], Awaitable[None]]</h3><pre>on_finish: Callable[[], Awaitable[None]]</pre><p>Breaking the type down:</p><ul><li><strong>Callable</strong> — it&#39;s a function</li><li><strong>[]</strong> — takes no arguments</li><li><strong>Awaitable</strong> — it&#39;s async (must be awaited)</li><li><strong>None</strong> — returns nothing</li></ul><p>In plain English: “an async function I want you to run when this thing fully finishes.” Typing callback hooks like this is a small habit that pays off — it documents the contract instead of leaving it to a docstring or, worse, tribal knowledge.</p><h3>Parsing LLM Output Safely — ast.literal_eval vs json.loads</h3><p>If you’re working with any LLM in your backend, at some point it’ll hand you back something that looks like a Python list but isn’t valid JSON:</p><pre>parsed = ast.literal_eval(cleaned_response)</pre><p>An LLM might return [0, 3, 7] or [&quot;Time Tracking&quot;, &quot;Absence&quot;] — valid Python syntax, but not valid JSON, since JSON requires double-quoted strings. json.loads will fail on single-quoted output like this.</p><p>ast.literal_eval safely evaluates Python literals without executing arbitrary code. The word &quot;safely&quot; matters here: plain eval() would happily run eval(&quot;os.system(&#39;rm -rf /&#39;)&quot;). ast.literal_eval only allows literal values — strings, numbers, lists, dicts, booleans — nothing executable. If you&#39;re parsing untrusted or semi-trusted text (and LLM output should be treated as such), this distinction is the whole point.</p><p>If you want to go deeper on treating LLM output as untrusted input, the <a href="https://genai.owasp.org/resource/owasp-top-10-for-llm-applications-2025/">OWASP Top 10 for LLM Applications</a> is worth a read.</p><h3>Normalization Maps — Bridging Fuzzy Output and Strict Keys</h3><p>Any time you’re matching free-form text (from a user, or from an LLM) against a fixed set of known values, you’ll hit this problem.</p><h3>The problem</h3><p>Say your system has a fixed list of valid categories:</p><pre>topics_list = [<br>    &quot;Time Tracking &amp; Absence&quot;,<br>    &quot;Payroll Integration&quot;,<br>    &quot;Benefits Setup&quot;<br>]</pre><p>But the source of that text — an LLM, a form field, a search box — might give you variants like:</p><ul><li>&quot;time tracking and absence&quot;</li><li>&quot;Time-Tracking &amp; Absence&quot;</li><li>&quot;TIME TRACKING AND ABSENCE&quot;</li></ul><p>Semantically identical to a human. But a plain string comparison fails:</p><pre>if item in topics_list:   # ❌ False</pre><p>And you silently discard a perfectly valid answer.</p><h3>The fix: precompute a lookup table</h3><pre>normalized_map = {self._normalize_topic(t): t for t in topics_list}</pre><p>Which produces something like:</p><pre>{<br>  &quot;time tracking and absence&quot;: &quot;Time Tracking &amp; Absence&quot;,<br>  &quot;payroll integration&quot;: &quot;Payroll Integration&quot;,<br>  &quot;benefits setup&quot;: &quot;Benefits Setup&quot;<br>}</pre><p>Now, whatever messy variant comes in:</p><pre>normalized = self._normalize_topic(item)<br>selected.append(normalized_map[normalized])</pre><p>You always recover and store the exact canonical string your downstream systems expect.</p><h3>Why it matters downstream</h3><p>Databases and query engines usually require exact matches:</p><pre>query = pdf_sections_ref.where(&quot;section_title&quot;, &quot;==&quot;, title)</pre><p>Without normalization, a mismatched casing or punctuation variant means your query silently returns nothing, and you end up thinking data is missing when it isn’t. Normalization prevents these false negatives before they ever reach your data layer.</p><h3>What normalization should handle — and what it shouldn’t</h3><p>Normalization is for <strong>surface-level noise</strong>, not meaning. All of these should collapse to the same key:</p><ul><li>Time Tracking &amp; Absence → time tracking and absence</li><li>time tracking and absence → time tracking and absence</li><li>Time-Tracking &amp; Absence → time tracking and absence</li><li>TIME TRACKING AND ABSENCE → time tracking and absence</li></ul><p>But these are <em>different meanings</em>, not formatting variants, and should be rejected rather than force-matched:</p><ul><li>&quot;time tracker&quot;</li><li>&quot;time management&quot;</li><li>&quot;absence configuration&quot;</li><li>&quot;tracking employee time&quot;</li></ul><h3>Why not just use fuzzy matching?</h3><p>It’s tempting to reach for Levenshtein distance, cosine similarity, or a fuzzy-matching library here instead. Don’t — at least not for this kind of exact-category matching. Fuzzy matching introduces dangerous ambiguity. Imagine an input of &quot;time management&quot; scoring:</p><pre>Similarity(Time Tracking &amp; Absence, time management) = 0.72 → &quot;close enough&quot;</pre><p>Now your system silently maps to the wrong category. Depending on what’s downstream, that can mean pulling the wrong documentation, generating irrelevant content, or corrupting evaluation logic — and it’s a genuinely painful class of bug to debug, because nothing throws an error. It just quietly does the wrong thing.</p><p>Normalization is a safety boundary, not a convenience feature — it’s meant to tolerate formatting, not meaning.</p><h3>Separation of Concerns and the Repository Pattern</h3><p>This one shows up in nearly every backend codebase eventually, usually as technical debt before it shows up as a lesson.</p><h3>The principle</h3><p>This is <strong>Separation of Concerns (SoC)</strong>, and more specifically in backend architecture, the <strong>Repository Pattern</strong> (or Data Access Layer isolation). You’ll also hear it called Persistence Ignorance, a Clean Architecture boundary, Layered Architecture, or Hexagonal Architecture (Ports &amp; Adapters). All of these are the same idea stated differently: <strong>business logic should not know how data is stored.</strong></p><p>Your service should think in terms of “give me the sections for this document” — not “go to this specific database, this collection, this document, this subcollection, filtered by this field.” The <em>how</em> is infrastructure. The <em>what</em> is business logic.</p><h3>What tight coupling looks like</h3><pre>self.db.collection(&quot;pdfs&quot;).document(...).collection(...)</pre><p>When your service talks directly to a specific database’s query API like this:</p><ul><li>Your business logic now depends on that specific database existing</li><li>You can’t swap databases without rewriting logic</li><li>You can’t unit test without spinning up that database</li><li>Security and access rules have to be duplicated everywhere this pattern appears</li></ul><p>This is infrastructure leaking into your domain layer.</p><h3>What the clean version looks like</h3><p>Introduce a boundary:</p><pre>Service (business logic)<br>        ↓<br>Repository (data contract)<br>        ↓<br>Database adapter (implementation)</pre><p>Now your service just says:</p><pre>sections = section_repository.get_sections(pdf_name, titles)</pre><p>It has zero knowledge of what’s underneath — Firestore, Postgres, Redis, doesn’t matter.</p><p>The repository acts as a translator:</p><ul><li><strong>“Get sections”</strong> → a Firestore query</li><li><strong>“Save transcript”</strong> → a SQL insert</li><li><strong>“Find session”</strong> → a Redis lookup</li></ul><p>The service only knows <em>intent</em>, never storage details.</p><h3>It’s also a security boundary</h3><p>When database access is centralized behind a repository, you get one place to enforce authorization checks, tenant isolation, query limits, input validation, logging, and schema enforcement. Without that central point, every service has to remember to do all of this independently — and that’s exactly how data leaks happen.</p><h3>The Decorator Pattern — A Retry Wrapper</h3><pre>def _retry_on_transient_error(max_attempts: int = MAX_RETRY_ATTEMPTS):<br>    def decorator(func):<br>        async def async_wrapper(*args, **kwargs):<br>            for attempt in range(max_attempts):<br>                try:<br>                    return await func(*args, **kwargs)<br>                except (ServiceUnavailable, DeadlineExceeded) as e:<br>                    await asyncio.sleep(RETRY_DELAY_SECONDS * (attempt + 1))<br>                    ...<br>        return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper<br>    return decorator</pre><p>A decorator wraps a function to add behavior without modifying the function itself. There are three layers here:</p><ol><li><strong>Outer function</strong> _retry_on_transient_error(max_attempts) — takes configuration, returns a decorator</li><li><strong>Middle function</strong> decorator(func) — receives the actual function being wrapped</li><li><strong>Inner function</strong> async_wrapper(*args, **kwargs) — the replacement that adds retry logic around the original call</li></ol><p>Any external call that can fail transiently — a network request, a database call, a third-party API — is a candidate for this pattern instead of scattering try/except retry loops throughout your codebase.</p><p><strong>The backoff itself</strong> — RETRY_DELAY_SECONDS * (attempt + 1) — is a simple exponential-ish backoff: wait 2s, then 4s, then 6s. It gives the failing service time to recover instead of hammering it with immediate retries.</p><h3>Semaphores — Capping Concurrency on Purpose</h3><pre>embedding_semaphore = asyncio.Semaphore(MAX_CONCURRENT_EMBEDDINGS)  # 10<br>llm_semaphore = asyncio.Semaphore(MAX_CONCURRENT_LLM_CALLS)  # 5</pre><pre>async with embedding_semaphore:<br>    result = await _get_embedding(text)</pre><p>A semaphore is a counter that caps concurrency. Setting it to 10 means “at most 10 tasks can be inside this block at once” — an 11th task simply waits until one of the 10 finishes.</p><p>This matters anywhere you’re calling a rate-limited external service. Without a cap like this, firing off 100 concurrent calls to an embedding API, an LLM, or any third-party service will blow through your rate limit and start failing requests wholesale. A semaphore acts like a bouncer, controlling how many requests get let in at once, regardless of how many your code is trying to fire off.</p><h3>asyncio.gather — Running Independent Work in Parallel</h3><pre>jd_emb, mod_emb = await asyncio.gather(<br>    _get_embedding(jd_text),<br>    _get_embedding(modules_text),<br>)</pre><p>This runs both calls concurrently and waits for both to finish before unpacking the results. Without gather, you&#39;d run them one after another — twice as slow for no reason, since neither call depends on the other.</p><p>This is where async pays off the most: IO-bound work (network calls, in particular) can run in parallel on a single thread, because the thread isn’t actually blocked while waiting on the network — it’s free to work on the other call in the meantime.</p><p>One detail worth knowing: passing return_exceptions=True to gather means exceptions come back as values inside the results list instead of being raised immediately. That lets you handle failures per item instead of having one failure kill the entire batch.</p><h3>Cache Invalidation, in Practice</h3><pre>metadata_changed = not cached_metadata or not metadata_equal(cached_metadata, meta)<br>new_items = [iv for iv in items if iv[&quot;sessionId&quot;] not in cached_considered | cached_not_considered]<br>recalc_needed = metadata_changed or bool(new_items) or not cached</pre><p>Cache invalidation is famously one of the two hard problems in computer science, and this snippet handles it through three simple triggers:</p><ol><li>The underlying metadata changed → recalculate</li><li>New items showed up since the cache was built → recalculate</li><li>No cache exists yet → calculate fresh</li></ol><p>The | operator here is a set union — cached_considered | cached_not_considered combines both sets into one, and checking not in against that combined set is how you find genuinely new items that haven&#39;t been seen in either bucket before. It&#39;s a small pattern, but it comes up constantly anywhere you&#39;re caching the output of an expensive computation over a growing dataset.</p><h3>ThreadPoolExecutor — When Async Isn’t Enough</h3><pre>executor = ThreadPoolExecutor(max_workers=4)</pre><p>asyncio is great for IO-bound work, but not everything you call is async-friendly — some libraries are blocking by nature. A ThreadPoolExecutor gives you a pool of real OS threads to hand blocking work off to, so your event loop can keep handling other requests while that work runs in the background.</p><p>Setting max_workers=4 means at most 4 pieces of blocking work run simultaneously — a 5th request waits for a thread to free up. That&#39;s not a limitation to work around; it&#39;s intentional. You generally don&#39;t want an unbounded number of expensive operations (heavy CPU work, blocking library calls, or in this case parallel LLM pipelines) all competing for memory and quota at once.</p><p><em>More of these in Part 2 — this is just what came up often enough to be worth writing down.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a874d0349c33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yes, Building your first AI agent is that easy…]]></title>
            <link>https://medium.com/@bireshkumar1964/yes-building-your-first-ai-agent-is-that-easy-2f265d77b8f2?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f265d77b8f2</guid>
            <category><![CDATA[smolagents]]></category>
            <category><![CDATA[build-ai-agents]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 05:15:53 GMT</pubDate>
            <atom:updated>2026-08-20T05:15:53.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MQLh1j6ZNWF_STo8.png" /><figcaption>Source : <a href="https://techblog.haldata.net/entry/2025/02/15/222950">https://techblog.haldata.net/entry/2025/02/15/222950</a></figcaption></figure><p>Let’s build our own first AI agent with the smolagents library. Some prerequisites:</p><ol><li>Watch the previous part of AI Agents from absolute scratch series.</li><li>You must have VS Code installed.</li><li>You must have an internet connection.</li></ol><p>Let’s understand the conceptual part first before building.</p><p>Remember we discussed the Thought → Action → Observation cycle in the previous part of our AI Agents series. Now that you understand the TAO cycle, let’s go deeper into the “Thought” part. This is where the magic happens, and it’s powered by something called the ReAct framework.</p><h3>The ReAct Framework: Teaching Agents to Reason</h3><h3>What Is ReAct?</h3><p>ReAct stands for Reasoning + Acting, and it’s based on a simple idea: before an AI takes an action, it should explain its reasoning in plain language.</p><p>This was a breakthrough in AI research because it solved a critical problem: models that act without reasoning make poor decisions.</p><h3>The Problem ReAct Solves</h3><p>Early AI agents would just chain tool calls together:</p><p><strong>❌ Without reasoning:</strong></p><pre>User: &quot;What&#39;s the weather in Tokyo and should I bring an umbrella?&quot;<br>Agent: web_search(&quot;Tokyo weather&quot;)<br>Agent: final_answer(&quot;Here are some weather websites...&quot;)</pre><p>The agent searched but didn’t think about what it was doing. It became a glorified API caller.</p><p><strong>✅ With ReAct, the agent must articulate its reasoning:</strong></p><pre>User: &quot;What&#39;s the weather in Tokyo and should I bring an umbrella?&quot;</pre><pre>Thought: &quot;I need to find current weather data for Tokyo, specifically <br>         looking for precipitation forecast to determine if an umbrella <br>         is needed.&quot;<br>Action: web_search(&quot;Tokyo weather forecast today&quot;)<br>Observation: &quot;Partly cloudy, 20°C, 70% chance of rain this afternoon...&quot;</pre><pre>Thought: &quot;There&#39;s a 70% chance of rain, which is significant. I should <br>         recommend bringing an umbrella.&quot;<br>Action: final_answer(&quot;Yes, you should bring an umbrella. There&#39;s a 70% <br>        chance of rain in Tokyo this afternoon...&quot;)</pre><h3>What We’re Building</h3><ul><li>An AI agent that can search the web, generate images, and solve multi-step problems</li><li>A system that streams its thinking process in real-time to users</li><li>A modular architecture where tools can be easily added or modified</li></ul><p><strong>Project structure:</strong></p><pre>├── tools/<br>│   ├── final_answer.py      # Termination tool<br>│   ├── web_search.py        # DuckDuckGo search<br>├── prompts.yaml              # System prompt configuration<br>├── app.py                    # Main application &amp; agent setup<br>└── Gradio_UI.py               # UI streaming &amp; visualization</pre><p>Let’s dive in.</p><h3>Part 1: Building the Tools</h3><p>Tools are the agent’s capabilities. Each tool is a Python class that inherits from smolagents’ Tool base class.</p><h3>1.1 The Final Answer Tool (tools/final_answer.py)</h3><p>This is the most critical tool — it’s how the agent signals “I’m done, here’s the answer.”</p><p><strong>Key components:</strong></p><pre>from smolagents.tools import Tool<br>from smolagents.agent_types import AgentImage<br>from PIL import Image</pre><pre>class FinalAnswerTool(Tool):<br>    name = &quot;final_answer&quot;<br>    description = &quot;Provides a final answer to the given problem. Can handle text, images, and other data types.&quot;<br>    inputs = {&#39;answer&#39;: {&#39;type&#39;: &#39;any&#39;, &#39;description&#39;: &#39;The final answer to the problem&#39;}}<br>    output_type = &quot;any&quot;</pre><p>What’s happening here:</p><ul><li><strong>name</strong>: the function name the agent will call in Python code (final_answer(...))</li><li><strong>description</strong>: how the agent learns <em>when</em> to use this tool. The agent reads this description and decides if it’s appropriate</li><li><strong>inputs</strong>: defines what arguments the tool accepts. Type &#39;any&#39; means it can handle anything</li><li><strong>output_type</strong>: what this tool returns. &quot;any&quot; allows flexibility</li></ul><p><strong>The core logic:</strong></p><pre>def forward(self, answer: Any) -&gt; Any:<br>    # If it&#39;s already an AgentImage, return it<br>    if isinstance(answer, AgentImage):<br>        return answer<br>    <br>    # If it&#39;s a PIL Image, wrap it in AgentImage<br>    if isinstance(answer, Image.Image):<br>        return AgentImage(answer)<br>    <br>    # For other types, return as-is<br>    return answer</pre><p>Why this design? The forward() method handles three scenarios:</p><ol><li><strong>Already wrapped</strong>: if the answer is already an AgentImage object, just return it</li><li><strong>PIL Image</strong>: if it’s a raw PIL Image, wrap it in AgentImage for proper UI display</li><li><strong>Everything else</strong>: text, numbers, etc. — return unchanged</li></ol><p>This flexibility means the agent can return any type of data without crashing.</p><h3>1.2 The Web Search Tool (tools/web_search.py)</h3><p>This tool lets the agent search the internet using DuckDuckGo.</p><p><strong>The tool definition:</strong></p><pre>from smolagents.tools import Tool<br>import duckduckgo_search</pre><pre>class DuckDuckGoSearchTool(Tool):<br>    name = &quot;web_search&quot;<br>    description = &quot;Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results.&quot;<br>    inputs = {&#39;query&#39;: {&#39;type&#39;: &#39;string&#39;, &#39;description&#39;: &#39;The search query to perform.&#39;}}<br>    output_type = &quot;string&quot;</pre><p>Notice:</p><ul><li>output_type = &quot;string&quot;: the results come back as formatted text</li><li>The description explicitly says “think a Google search” — helping the agent understand when to use it</li></ul><p>Key design decisions:</p><ul><li><strong>Configurable results</strong>: max_results=10 can be changed when instantiating</li><li><strong>Lazy import check</strong>: only imports duckduckgo_search when the tool is created, with a helpful error if missing</li><li><strong>Stores DDGS instance</strong>: self.ddgs is reused across searches for efficiency</li></ul><p><strong>The search logic:</strong></p><pre>def forward(self, query: str) -&gt; str:<br>    results = self.ddgs.text(query, max_results=self.max_results)<br>    if len(results) == 0:<br>        raise Exception(&quot;No results found! Try a less restrictive/shorter query.&quot;)<br>    <br>    postprocessed_results = [<br>        f&quot;[{result[&#39;title&#39;]}]({result[&#39;href&#39;]})\n{result[&#39;body&#39;]}&quot; <br>        for result in results<br>    ]<br>    return &quot;## Search Results\n\n&quot; + &quot;\n\n&quot;.join(postprocessed_results)</pre><p>What’s happening:</p><ol><li>Call the DuckDuckGo API: self.ddgs.text(query, max_results=10)</li><li>Check for empty results: if no results, raise an exception that the agent will see</li><li>Format as Markdown: each result becomes [Title](URL)\nDescription</li><li>Return the formatted string: all results joined with line breaks</li></ol><p>Why Markdown formatting? Language models understand Markdown better than JSON or raw text. The agent can easily parse:</p><ul><li>Clickable links [Title](URL)</li><li>Readable descriptions</li><li>Clear structure with headers</li></ul><h3>Part 2: The System Prompt Configuration (prompts.yaml)</h3><p>This YAML file contains the entire “instruction manual” for the agent. It’s structured as a template that gets filled in with tool information at runtime.</p><h3>2.1 The Main System Prompt</h3><p><strong>The opening:</strong></p><pre>&quot;system_prompt&quot;: |-<br>  You are an expert assistant who can solve any task using code blobs. <br>  You will be given a task to solve as best you can.<br>  To do so, you have been given access to a list of tools: these tools <br>  are basically Python functions which you can call with code.</pre><p>Why this wording matters:</p><ul><li><strong>“expert assistant”</strong>: sets a confident, capable tone</li><li><strong>“using code blobs”</strong>: signals that actions are taken via Python code</li><li><strong>“tools are basically Python functions”</strong>: makes it clear how to use tools</li></ul><p><strong>The TAO cycle instructions:</strong></p><pre>To solve the task, you must plan forward to proceed in a series of steps, <br>in a cycle of &#39;Thought:&#39;, &#39;Code:&#39;, and &#39;Observation:&#39; sequences.</pre><pre>At each step, in the &#39;Thought:&#39; sequence, you should first explain your <br>reasoning towards solving the task and the tools that you want to use.</pre><pre>Then in the &#39;Code:&#39; sequence, you should write the code in simple Python. <br>The code sequence must end with &#39;&lt;end_code&gt;&#39; sequence.</pre><pre>During each intermediate step, you can use &#39;print()&#39; to save whatever <br>important information you will then need.</pre><pre>These print outputs will then appear in the &#39;Observation:&#39; field, which <br>will be available as input for the next step.</pre><p>This is the core behavior pattern. The agent learns to:</p><ol><li><strong>Think first</strong>: explain reasoning in Thought:</li><li><strong>Act in code</strong>: write Python in Code: blocks</li><li><strong>Print important info</strong>: use print() to save data</li><li><strong>Observe results</strong>: see printed output in Observation:</li><li><strong>Repeat</strong>: continue until solved</li></ol><h3>2.2 The Examples Section</h3><p>The system prompt contains 6+ complete examples.</p><h3>2.3 The Rules Section</h3><p>These are explicit constraints on agent behavior. For example, Rule 1:</p><pre>Here are the rules you should always follow to solve your task:<br>1. Always provide a &#39;Thought:&#39; sequence, and a &#39;Code:\n```py&#39; sequence <br>   ending with &#39;```&lt;end_code&gt;&#39; sequence, else you will fail.</pre><p>Why “else you will fail”? Strong language creates obligation — the agent treats these rules seriously.</p><h3>2.4 The Planning Section</h3><p>The planning subsection enables advanced reasoning. Before the agent starts working, it can optionally:</p><ul><li>Analyze what information it has</li><li>Identify what it needs to find</li><li>Plan what computations are required</li></ul><p>This is metacognition — thinking about the problem before solving it.</p><h3>Part 3: The Main Application (app.py)</h3><p>This is where everything comes together.</p><h3>3.1 Imports and Setup</h3><pre>import os<br>from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool<br>import datetime<br>import pytz<br>import yaml<br>from tools.final_answer import FinalAnswerTool<br>from Gradio_UI import GradioUI</pre><p>Key imports:</p><ul><li><strong>CodeAgent</strong>: the agent class that orchestrates the TAO cycle</li><li><strong>HfApiModel</strong>: wrapper for the Hugging Face inference API</li><li><strong>load_tool</strong>: loads tools from the Hugging Face Hub</li><li><strong>tool decorator</strong>: for creating custom tools with @tool</li><li><strong>yaml</strong>: to load prompts.yaml</li></ul><h3>Setting the API Token</h3><pre>HF_TOKEN = &quot;&quot;  # Replace with your actual token<br>os.environ[&#39;HF_TOKEN&#39;] = HF_TOKEN</pre><p>Why use environment variables? Many libraries (including Hugging Face) check os.environ for credentials. Setting it here ensures all components have access.</p><h3>3.2 Creating a Custom Tool with the Decorator</h3><pre>@tool<br>def get_current_time_in_timezone(timezone: str) -&gt; str:<br>    &quot;&quot;&quot;A tool that fetches the current local time in a specified timezone.<br>    <br>    Args:<br>        timezone: A string representing a valid timezone (e.g., &#39;America/New_York&#39;).<br>    &quot;&quot;&quot;<br>    try:<br>        tz = pytz.timezone(timezone)<br>        local_time = datetime.datetime.now(tz).strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>        return f&quot;The current local time in {timezone} is: {local_time}&quot;<br>    except Exception as e:<br>        return f&quot;Error fetching time for timezone &#39;{timezone}&#39;: {str(e)}&quot;</pre><p>The @tool decorator magic:</p><ul><li>Reads the docstring as the tool description</li><li>Parses the Args section for input types</li><li>Infers the output type from -&gt; str</li><li>Automatically creates a Tool instance</li></ul><p>This replaces manually writing a Tool subclass.</p><p>Why include error handling?</p><pre>except Exception as e:<br>    return f&quot;Error fetching time for timezone &#39;{timezone}&#39;: {str(e)}&quot;</pre><p>This prevents crashes when users request invalid timezones.</p><h3>3.3 Model Configuration</h3><pre>model = HfApiModel(<br>    max_tokens=2096,<br>    temperature=0.5,<br>    model_id=&#39;Qwen/Qwen2.5-Coder-32B-Instruct&#39;,<br>    token=HF_TOKEN,<br>    custom_role_conversions=None,<br>)</pre><p>Parameter breakdown:</p><ul><li><strong>max_tokens=2096</strong>: enough for reasoning + tool calls</li><li><strong>temperature=0.5</strong>: balanced creativity and determinism</li><li><strong>model_id</strong>: Coder → optimized for code, 32B → strong reasoning, Instruct → follows rules well</li><li><strong>custom_role_conversions=None</strong>: default role handling</li></ul><h3>3.4 Loading External Tools</h3><pre>image_generation_tool = load_tool(<br>    &quot;agents-course/text-to-image&quot;,<br>    trust_remote_code=True<br>)<br>search_tool = DuckDuckGoSearchTool()</pre><p>Why trust_remote_code=True? You are executing external code — only enable this for trusted repositories.</p><h3>3.5 Loading the Prompt Templates</h3><pre>with open(&quot;prompts.yaml&quot;, &quot;r&quot;) as stream:<br>    prompt_templates = yaml.safe_load(stream)</pre><p>Loaded structure:</p><pre>{<br>    &quot;system_prompt&quot;: &quot;...&quot;,<br>    &quot;planning&quot;: {<br>        &quot;initial_facts&quot;: &quot;...&quot;,<br>        &quot;initial_plan&quot;: &quot;...&quot;<br>    },<br>    &quot;managed_agent&quot;: {...}<br>}</pre><h3>3.6 Agent Initialization</h3><pre>agent = CodeAgent(<br>    model=model,<br>    tools=[<br>        final_answer,<br>        image_generation_tool,<br>        search_tool,<br>        get_current_time_in_timezone,<br>    ],<br>    max_steps=6,<br>    verbosity_level=1,<br>    grammar=None,<br>    planning_interval=None,<br>    name=None,<br>    description=None,<br>    prompt_templates=prompt_templates<br>)</pre><p>Key parameters explained:</p><ul><li><strong>tools</strong>: automatically injected into the system prompt</li><li><strong>max_steps=6</strong>: prevents infinite loops</li><li><strong>verbosity_level=1</strong>: basic logging</li><li><strong>planning_interval=None</strong>: planning only once</li><li><strong>prompt_templates</strong>: full behavioral control</li></ul><h3>Part 4: The Gradio UI (Gradio_UI.py)</h3><p>This file handles visualization and streaming.</p><h3>Part 5: How It All Connects — Complete Execution Trace</h3><p>Let’s trace a complete execution from user input to final output, following every single function call and data transformation.</p><p><strong>🎯 The scenario:</strong> user types “Search for Tokyo population and create an illustration.”</p><h3>Step 1: Gradio Captures User Input</h3><pre># In Gradio_UI.py - launch() method<br>text_input = gr.Textbox(lines=1, label=&quot;Chat Message&quot;)<br>text_input.submit(<br>    self.log_user_message,<br>    [text_input, file_uploads_log],<br>    [stored_messages, text_input],<br>).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])</pre><p>The chain reaction:</p><ol><li>User presses Enter</li><li>Gradio triggers text_input.submit()</li><li>First calls self.log_user_message() to prepare the message</li><li>Then calls self.interact_with_agent() to run the agent</li></ol><p>Data flow:</p><pre>User Input: &quot;Search for Tokyo population and create an illustration&quot;<br>    ↓<br>log_user_message() → Formats message (adds file info if any)<br>    ↓<br>stored_messages list: [user_message]<br>    ↓<br>interact_with_agent() receives the formatted prompt</pre><h3>Step 2: The interact_with_agent Method</h3><pre>def interact_with_agent(self, prompt, messages):<br>    import gradio as gr<br>    <br>    # Add user message to chat<br>    messages.append(gr.ChatMessage(role=&quot;user&quot;, content=prompt))<br>    yield messages  # ← User sees their message immediately<br>    <br>    # Stream agent responses<br>    for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):<br>        messages.append(msg)<br>        yield messages  # ← Each agent message appears live<br>    <br>    yield messages  # ← Final update</pre><p>What this does:</p><ol><li><strong>Immediate feedback</strong>: user message appears instantly via the first yield</li><li><strong>Streaming setup</strong>: calls stream_to_gradio(), which returns a generator</li><li><strong>Live updates</strong>: each yield pushes updates to the browser without waiting</li></ol><h3>Step 3: stream_to_gradio Begins Streaming</h3><pre>def stream_to_gradio(agent, task: str, reset_agent_memory: bool = False):<br>    total_input_tokens = 0<br>    total_output_tokens = 0<br>    # This is where the magic happens - streaming agent execution<br>    for step_log in agent.run(task, stream=True, reset=reset_agent_memory):<br>        # Token tracking<br>        if hasattr(agent.model, &quot;last_input_token_count&quot;):<br>            total_input_tokens += agent.model.last_input_token_count or 0<br>            total_output_tokens += agent.model.last_output_token_count or 0<br>        <br>        # Extract messages from this step<br>        for message in pull_messages_from_step(step_log):<br>            yield message  # ← Streams to UI</pre><p>Key insight: agent.run(task, stream=True) returns a generator that yields one ActionStep at a time. This enables real-time streaming.</p><h3>Step 4: CodeAgent.run() — The Brain Starts Working</h3><p>What the agent receives:</p><pre># Context sent to the language model:<br>{<br>    &quot;system&quot;: &quot;&quot;&quot;<br>        You are an expert assistant who can solve any task using code blobs...<br>        <br>        Tools available:<br>        - final_answer: Provides a final answer...<br>        - web_search: Performs a duckduckgo web search...<br>        - image_generation_tool: Generates images from text...<br>        - get_current_time_in_timezone: Gets current time...<br>    &quot;&quot;&quot;,<br>    &quot;messages&quot;: [<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;Search for Tokyo population and create an illustration&quot;<br>        }<br>    ]<br>}</pre><p>The language model generates:</p><pre>Thought: I need to first search for Tokyo&#39;s population, then create an <br>illustration based on that information. I&#39;ll start with the web search.</pre><pre>Code:<br>```py<br>result = web_search(query=&quot;Tokyo population&quot;)<br>print(result)<br>```&lt;end_code&gt;</pre><h3>Step 5: Code Execution (Tool Invocation)</h3><p>The agent’s output is parsed:</p><ol><li>Extract the code block between ```py and `&lt;end_code&gt;`</li><li>Identify tool calls: web_search(query=&quot;Tokyo population&quot;)</li><li>Execute in the Python interpreter:</li></ol><pre># Executed by smolagents internally:<br>result = web_search(query=&quot;Tokyo population&quot;)<br>print(result)</pre><p>What happens in DuckDuckGoSearchTool.forward():</p><pre>def forward(self, query: str) -&gt; str:<br>    # Call DuckDuckGo API<br>    results = self.ddgs.text(query=&quot;Tokyo population&quot;, max_results=10)<br>    <br>    # Format as markdown<br>    formatted = [<br>        &quot;[Tokyo Population 2024](https://example.com/tokyo)\nTokyo has approximately 14 million residents...&quot;,<br>        &quot;[Demographics of Tokyo](https://example.com/demo)\nThe Greater Tokyo Area has 37 million people...&quot;,<br>        # ... more results<br>    ]<br>    <br>    return &quot;## Search Results\n\n&quot; + &quot;\n\n&quot;.join(formatted)</pre><p>The print(result) output is captured:</p><pre>## Search Results<br>[Tokyo Population 2024](https://example.com/tokyo)<br>Tokyo has approximately 14 million residents in the city proper...<br>[Demographics of Tokyo](https://example.com/demo)<br>The Greater Tokyo Area has 37 million people...<br>(8 more results...)</pre><p>This becomes the Observation for the next step.</p><h3>Step 6: ActionStep Object Creation</h3><p>smolagents creates an ActionStep object:</p><pre>ActionStep(<br>    step_number=1,<br>    model_output=&quot;&quot;&quot;<br>Thought: I need to first search for Tokyo&#39;s population, then create an <br>illustration based on that information. I&#39;ll start with the web search.</pre><pre>Code:<br>```py<br>result = web_search(query=&quot;Tokyo population&quot;)<br>print(result)<br>```&lt;end_code&gt;<br>    &quot;&quot;&quot;,<br>    tool_calls=[<br>        ToolCall(<br>            name=&quot;web_search&quot;,<br>            arguments={&quot;query&quot;: &quot;Tokyo population&quot;}<br>        )<br>    ],<br>    observations=&quot;&quot;&quot;## Search Results<br>[Tokyo Population 2024](https://example.com/tokyo)<br>Tokyo has approximately 14 million residents...<br>(truncated for brevity)<br>    &quot;&quot;&quot;,<br>    error=None,<br>    duration=2.34,  # seconds<br>    input_token_count=1247,<br>    output_token_count=156<br>)</pre><p>This object contains everything that happened in this TAO cycle.</p><h3>Step 7: pull_messages_from_step Extracts UI Messages</h3><pre>def pull_messages_from_step(step_log: ActionStep):<br>    # Step number<br>    yield gr.ChatMessage(role=&quot;assistant&quot;, content=&quot;**Step 1**&quot;)<br>    <br>    # The thought and code<br>    yield gr.ChatMessage(<br>        role=&quot;assistant&quot;, <br>        content=&quot;&quot;&quot;Thought: I need to first search for Tokyo&#39;s population...<br>Code:<br>```py<br>result = web_search(query=&quot;Tokyo population&quot;)<br>print(result)<br>```&quot;&quot;&quot;<br>    )<br>    <br>    # Tool call metadata<br>    yield gr.ChatMessage(<br>        role=&quot;assistant&quot;,<br>        content=&quot;web_search(query=&#39;Tokyo population&#39;)&quot;,<br>        metadata={<br>            &quot;title&quot;: &quot;🛠️ Used tool web_search&quot;,<br>            &quot;id&quot;: &quot;call_1&quot;,<br>            &quot;status&quot;: &quot;pending&quot;<br>        }<br>    )<br>    <br>    # Observations (nested under tool call)<br>    yield gr.ChatMessage(<br>        role=&quot;assistant&quot;,<br>        content=&quot;## Search Results\n\n[Tokyo Population 2024]...&quot;,<br>        metadata={<br>            &quot;title&quot;: &quot;📝 Execution Logs&quot;,<br>            &quot;parent_id&quot;: &quot;call_1&quot;,<br>            &quot;status&quot;: &quot;done&quot;<br>        }<br>    )<br>    <br>    # Timing footer<br>    yield gr.ChatMessage(<br>        role=&quot;assistant&quot;,<br>        content=&quot;&lt;span&gt;Step 1 | Input-tokens: 1,247 | Output-tokens: 156 | Duration: 2.34&lt;/span&gt;&quot;<br>    )<br>    <br>    yield gr.ChatMessage(role=&quot;assistant&quot;, content=&quot;-----&quot;)</pre><p>Each yield sends a message to the browser immediately.</p><h3>Step 8: Real-Time UI Updates</h3><p>What the user sees, progressively:</p><pre>[You]<br>Search for Tokyo population and create an illustration</pre><pre>[Agent - Step 1 appears]<br>🧠 Thought: I need to first search for Tokyo&#39;s population...</pre><pre>[2 seconds later]<br>⚡ Used tool: web_search<br>📝 Execution Logs:<br>   ## Search Results<br>   [Tokyo Population 2024]...<br>   <br>[Footer appears]<br>Step 1 | Input-tokens: 1,247 | Output-tokens: 156 | Duration: 2.34<br>─────────────────────────────────</pre><p>All without page reloads — pure streaming magic!</p><h3>Step 9: Agent Continues to Step 2</h3><p>The agent’s context now includes the observation:</p><pre># What the model sees:<br>{<br>    &quot;system&quot;: &quot;You are an expert assistant...&quot;,<br>    &quot;messages&quot;: [<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Search for Tokyo population...&quot;},<br>        {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Thought: I need to search... Code: ...&quot;},<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Observation: ## Search Results...&quot;},<br>        # ↑ The observation is added to the context<br>    ]<br>}</pre><p>The agent generates Step 2:</p><pre>Thought: I found that Tokyo has approximately 14 million people in the city <br>proper, and 37 million in the greater metro area. Now I&#39;ll create an <br>illustration showing Tokyo&#39;s massive scale.</pre><pre>Code:<br>```py<br>image = image_generation_tool(<br>    prompt=&quot;A beautiful aerial illustration of Tokyo cityscape showing the massive urban sprawl with 37 million people, futuristic skyscrapers, and Mount Fuji in the background&quot;<br>)<br>final_answer(image)<br>```&lt;end_code&gt;</pre><p>Notice:</p><ul><li>The agent used information from the observation (14 million, 37 million)</li><li>The image prompt is detailed and contextual</li><li>final_answer() signals completion</li></ul><h3>Step 10: Image Generation Tool Executes</h3><pre># image_generation_tool.forward() is called<br>def forward(self, prompt: str):<br>    # Calls Hugging Face Inference API<br>    response = requests.post(<br>        &quot;https://api-inference.huggingface.co/models/...&quot;,<br>        headers={&quot;Authorization&quot;: f&quot;Bearer {HF_TOKEN}&quot;},<br>        json={&quot;inputs&quot;: prompt}<br>    )<br>    <br>    # Save image to temp file<br>    image_data = response.content<br>    image_path = &quot;/tmp/tokyo_illustration_abc123.png&quot;<br>    with open(image_path, &quot;wb&quot;) as f:<br>        f.write(image_data)<br>    <br>    # Return as AgentImage<br>    return AgentImage(image_path)</pre><p>Then final_answer() is called:</p><pre>def forward(self, answer: Any) -&gt; Any:<br>    if isinstance(answer, AgentImage):<br>        return answer  # ← Returns the image object</pre><p>This signals to CodeAgent: &quot;Task complete, here&#39;s the final answer.&quot;</p><h3>Step 11: Final Answer Rendering</h3><p>Back in stream_to_gradio():</p><pre>final_answer = step_log  # Last step_log is the final answer</pre><pre># Extract the actual answer<br>if hasattr(final_answer, &#39;final_answer&#39;):<br>    final_answer_content = final_answer.final_answer  # ← AgentImage object</pre><pre># Handle AgentImage type<br>if isinstance(final_answer_content, AgentImage):<br>    image_path = final_answer_content.to_string()  # &quot;/tmp/tokyo_illustration_abc123.png&quot;<br>    <br>    yield gr.ChatMessage(<br>        role=&quot;assistant&quot;,<br>        content={&quot;path&quot;: image_path},  # ← Gradio displays this as an image<br>    )</pre><p>Gradio automatically:</p><ol><li>Reads the file at /tmp/tokyo_illustration_abc123.png</li><li>Encodes it as base64</li><li>Displays it inline in the chat</li></ol><h3>Step 12: What the User Sees (Complete)</h3><p>Final UI state:</p><pre>[You]<br>Search for Tokyo population and create an illustration<br>─────────────────────────────────<br>🧠 Step 1<br>Thought: I need to first search for Tokyo&#39;s population...<br>⚡ Used tool: web_search<br>📝 Execution Logs:<br>   ## Search Results<br>   [Tokyo Population 2024] Tokyo has approximately 14 million...<br>   [Demographics of Tokyo] The Greater Tokyo Area has 37 million...<br>   <br>Step 1 | Input-tokens: 1,247 | Output-tokens: 156 | Duration: 2.34<br>─────────────────────────────────<br>🧠 Step 2<br>Thought: I found that Tokyo has approximately 14 million people...<br>⚡ Used tool: image_generation_tool<br>📝 Execution Logs: Generated image successfully<br>Step 2 | Input-tokens: 1,503 | Output-tokens: 98 | Duration: 4.67<br>─────────────────────────────────<br>[Agent - Final Answer]<br>🖼️ [Beautiful illustration of Tokyo cityscape displayed here]</pre><h3>Step 13: The Complete Data Flow Diagram</h3><pre>User Input<br>    ↓<br>Gradio UI (text_input.submit)<br>    ↓<br>log_user_message() → Formats prompt<br>    ↓<br>interact_with_agent() → Appends user message<br>    ↓<br>stream_to_gradio() → Starts streaming<br>    ↓<br>agent.run(task, stream=True) → Generator starts<br>    ↓<br>─────────── FOR EACH STEP ───────────<br>    ↓<br>CodeAgent receives context (system prompt + history)<br>    ↓<br>Language Model generates: Thought + Code<br>    ↓<br>Code parser extracts tool calls<br>    ↓<br>Python interpreter executes code<br>    ↓<br>Tool.forward() method runs (web_search, image_gen, etc.)<br>    ↓<br>print() outputs captured as observations<br>    ↓<br>ActionStep object created (with all metadata)<br>    ↓<br>yield ActionStep → Back to stream_to_gradio<br>    ↓<br>pull_messages_from_step() extracts UI messages<br>    ↓<br>yield gr.ChatMessage → Back to interact_with_agent<br>    ↓<br>Gradio pushes update to browser (WebSocket)<br>    ↓<br>User sees update in real-time<br>    ↓<br>─────── LOOP UNTIL final_answer() ───────<br>    ↓<br>Final answer extracted<br>    ↓<br>Rendered in UI (text/image/etc.)<br>    ↓<br>Task complete ✅</pre><h3>Why This Architecture Is Brilliant</h3><p><strong>1. True streaming</strong></p><ul><li>Every step appears as it happens</li><li>No “loading…” spinners</li><li>Users see the agent thinking</li></ul><p><strong>2. Complete observability</strong></p><ul><li>Every tool call visible</li><li>Token usage tracked</li><li>Timing measured</li><li>Errors displayed</li></ul><p><strong>3. Stateful context</strong></p><ul><li>Agent remembers previous observations</li><li>Multi-step reasoning possible</li><li>Self-correction enabled</li></ul><p><strong>4. Modular design</strong></p><ul><li>Tools are independent</li><li>Prompt is configurable</li><li>Model is swappable</li><li>UI is decoupled</li></ul><p><strong>5. Robust error handling</strong></p><ul><li>Tools return errors as strings (agent can adapt)</li><li>Token counting handles None values</li><li>File operations are defensive</li><li>Type checking prevents crashes</li></ul><h3>The Key Insight</h3><p>The agent isn’t following a script — it’s reasoning at each step based on:</p><ul><li>The system prompt (its “instruction manual”)</li><li>Available tools (its capabilities)</li><li>Previous observations (what it learned)</li><li>The original task (the goal)</li></ul><p>This creates emergent behavior — the agent solves problems in ways you didn’t explicitly program.</p><p>This is the power of AI agents. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f265d77b8f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master PyTorch Step by Step (Part 1)]]></title>
            <link>https://medium.com/@bireshkumar1964/pytorch-part-1-21a28d5e0f1e?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a28d5e0f1e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pytorch-tutorial]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 15:02:08 GMT</pubDate>
            <atom:updated>2026-08-20T06:12:44.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qC7xuYKjLlT4oEoc.png" /><figcaption>Source : <a href="https://xpertlab.com/what-is-pytorch/">https://xpertlab.com/what-is-pytorch/</a></figcaption></figure><p>Pytorch Docs is the best place to get started with Pytorh (<a href="https://docs.pytorch.org/tutorials/beginner/basics/intro.html">https://docs.pytorch.org/tutorials/beginner/basics/intro.html</a> )</p><p>To continue locally like me, you can choose your appropriate system and you will get a command form this site( <a href="https://pytorch.org/get-started/locally/">https://pytorch.org/get-started/locally/</a> ) -<br>pip3 install torch torchvision — index-url <a href="https://download.pytorch.org/whl/cu126">https://download.pytorch.org/whl/cu126</a></p><p>It is a 2+ GB package so be prepared if you want to do it locally , you can also just follow on google collab.</p><p>Pytorch extends NumPy with accelerated computation of GPUs. Pytorch autograd is also a very interesting thing. It enables the automatic computation of gradients for tensor operations, simplifying backpropagation and model optimization.</p><p>Pytorch is used in Deep Learning which is a subset of ML that focuses on the training and application of deep neural networks. These deep neural networks were originally inspired by how the human brain works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*NwDwjd8qcmI3OYYCyHyvVA.png" /></figure><h3><strong>Tensors</strong></h3><p>There are similars to ndarrays in Numpy but they can run on GPUs and used for automatic differetiation which I just told you about.A scalar is a 0-dimensional tensor (for instance, just a number), a vector is a 1-dimensional tensor, and a matrix is a 2-dimensional tensor. We can create objects of PyTorch’s Tensor class using the torch.tensor function. We can access the data type of a tensor using .dtype and change it to any other data type using .to() method. See examples :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elA63BCQMdfsIisClGyacA.png" /></figure><h4>Common PyTorch tensor operations</h4><p>We can use .shape attribute to access the shape of the tensor and we can .reshape() method or .view() method to change the shape of the tensor. Also, we can transpose using the .T attribute and also perform matrix multiplication using matmul or @ method. See :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*s2brpx_G-IJWZC7hmS8L5g.png" /></figure><h3>Computational graphs</h3><p>A computational graph (or computation graph in short) is a directed graph that allows us to express and visualize mathematical expressions. In the context of deep learning, a computation graph lays out the sequence of calculations needed to compute the output of a neural network.</p><p>This is how the computation graph of logistic regression looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nUVpviyWkXoxhONA.png" /><figcaption>Source : <a href="https://datahacker.rs/computation-graph/">https://datahacker.rs/computation-graph/</a></figcaption></figure><p>PyTorch always builds such a computation graph in the background, and we can use this to calculate gradients of a loss function with respect to the model parameters (like w1 and b) to train the model, See code of simple logistic regression classifier :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*izm4Jr7LMxn63n96mmcrYQ.png" /></figure><p>If we carry out computations in PyTorch, it will build such a graph internally by default if one of its terminal nodes has the requires_grad attribute set to True. This is useful if we want to compute gradients. Lets see it in action :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*qEDOGe2lvNcj0I4VtRaL7A.png" /></figure><p>Here, we called grad function to compute the gradient of the loss with respect to model parameter w1 and gradient of the loss with respect to model parameter b . By default, PyTorch destroys the computation graph after calculating the gradients to free memory. However, since we are going to reuse this computation graph shortly, we set retain_graph=True so that it stays in memory.</p><p>Now here, we called the grad function manually but we can also automate this — we can call .backward on the loss, and PyTorch will compute the gradients of all the leaf nodes in the graph, which will be stored via the tensors’ .grad attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*JDGgt4EzxXORps7O-CxvwA.png" /></figure><h3>Implementing multilayer neural networks</h3><p>Lets see how we will build a neural network like this :</p><p>Code :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*1sebTp-K3jxZuCO7E_aZcQ.png" /></figure><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Q35oDxebCl2uu6t4cZkCeA.png" /></figure><p>Input Layer<br>50 features<br> │<br> ▼<br>┌───────────────────┐<br>│ Linear (50 → 30) │<br>│ Hidden Layer 1 │<br>└───────────────────┘<br> │<br> ▼<br> ReLU<br> │<br> ▼<br>┌───────────────────┐<br>│ Linear (30 → 20) │<br>│ Hidden Layer 2 │<br>└───────────────────┘<br> │<br> ▼<br> ReLU<br> │<br> ▼<br>┌───────────────────┐<br>│ Linear (20 → 3) │<br>│ Output Layer │<br>└───────────────────┘<br> │<br> ▼<br> 3 outputs</p><p>So this network takes:</p><blockquote><strong><em>50 numbers as input</em></strong></blockquote><p>and produces:</p><blockquote><strong><em>3 numbers as output</em></strong></blockquote><p>This could, for example, be a classification problem with 3 classes:</p><pre>Class 0<br>Class 1<br>Class 2</pre><p>Now, understand that torch.nn.Module is the <strong>base class for neural networks in PyTorch</strong>. So instead of manually managing everything, you inherit from Module.</p><p>First we use __init__() to define the architecture — SO, actually __init__() is the constructor which is called when new object is created liek when we will do :</p><blockquote>model = NeuralNetwork(50, 3)</blockquote><p>In the __init__, we call the constructor of torch.nn.Module from which we are inheriting everything :</p><blockquote>super().__init__()</blockquote><p>Then, we start creating a collection of layers that will be executed <strong>one after another :</strong></p><blockquote>torch.nn.Linear(num_inputs, 30),<br>torch.nn.ReLU(),</blockquote><blockquote>torch.nn.Linear(30, 20),<br>torch.nn.ReLU(),</blockquote><blockquote>torch.nn.Linear(20, num_outputs),</blockquote><p>As we already know, ReLU introduces <strong>nonlinearity</strong>, allowing the network to learn complex relationships.</p><p><strong>Why are we using Sequential?</strong></p><p>Without Sequential, your forward() might look like:</p><pre>def forward(self, x):<br>    x = self.layer1(x)<br>    x = self.relu1(x)<br>    x = self.layer2(x)<br>    x = self.relu2(x)<br>    x = self.layer3(x)<br>    return x</pre><p>But because the operations are simply performed one after another, we can use:</p><pre>self.layers = torch.nn.Sequential(<br>    ...<br>)</pre><p>Then:</p><pre>def forward(self, x):<br>    logits = self.layers(x)<br>    return logits</pre><p><strong>What is </strong><strong>forward()?</strong></p><p>It defines <strong>how data flows through our network</strong>. The output produced after the final layer are called as logits — these are raw numbers not probabilities produced by the network.</p><p>Now understand that Linear(50, 30) means : Take 50 input numbers and produce 30 new numbers.</p><p><strong>How many parameters does this model have?</strong></p><h3>Layer 1</h3><pre>Linear(50, 30)</pre><p>Total params = 50 * 30 + 30 (total bias ; There are 30 neurons and each neuron has one bias)= 1530</p><h3>Layer 2</h3><pre>Linear(30, 20)</pre><p>Total params = 30* 20 + 20(total bias ; There are 20 neurons and each neuron has one bias)= 620</p><h3>Layer 3</h3><pre>Linear(20, 3)</pre><p>Total params = 20* 3 + 3(total bias ; There are 3 neurons and each neuron has one bias)= 63</p><blockquote>Total number of trainable model parameters: 2213(1520+620+63 = 2213)</blockquote><p><strong>Why don’t ReLU layers have parameters?</strong></p><p>Because ReLU doesn’t have anything to learn.</p><p>It simply performs: ReLU(x)=max(0,x)</p><blockquote>So, model.parameters() gives you all the parameters that PyTorch knows belong to the model.</blockquote><p><strong>model.layers[0].weight gives the weight matrix of the first linear layer whose shape will be :</strong></p><blockquote>torch.Size([30, 50])</blockquote><p>PyTorch stores its weight matrix as: [30,50] because there are:</p><pre>30 output neurons<br>50 inputs to each neuron</pre><p>Similarly, we can also access the bias layer with model.layers[0].bias.</p><p>So, grad_fn tells you that PyTorch is tracking how this tensor was produced so it can later calculate gradients like grad_fn=&lt;AddmmBackward0&gt; means PyTorch’s internal backward operation is associated with the final matrix multiplication + addition. We can use torch.no_grad() if we are not going to call backward().</p><h3>Thank You</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a28d5e0f1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything You Need to Know About NumPy (With Code)]]></title>
            <link>https://medium.com/@bireshkumar1964/numpy-27fa02f33156?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/27fa02f33156</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[numpy-array]]></category>
            <category><![CDATA[python-list]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 23:01:59 GMT</pubDate>
            <atom:updated>2026-08-20T06:11:26.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*uNsUNuNG0Uz_smyc.jpg" /><figcaption>Source : <a href="https://www.includehelp.com/python/how-does-the-axis-parameter-from-numpy-work.aspx">https://www.includehelp.com/python/how-does-the-axis-parameter-from-numpy-work.aspx</a></figcaption></figure><p>It is building block of so many libraries like Scikit-learn, Pandas etc. It helps to interact with multi dimensional arrays called ndarray. People love NumPy because it is fast. NumPy arrays use contiguous blocks of memory that can be efficiently cached by the CPU. In contrast, Python lists are arrays of pointers to objects in random locations in memory, which cannot be easily cached and come with a more expensive memory-look-up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*FVGJdRY9lXiyBXZWVSMVIQ.png" /></figure><p>NumPy infers the datatype of elements upon construction.<br>We can also change the dtype while constructcing the array using array function :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*VhDPdOCAvnA1zp2bGyUS4A.png" /></figure><p>Once an array has been constructed, we can downcast or recast its type withthe astype method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*ImUwYUUGHF2gSpKiX7JKKg.png" /></figure><p>We can use size to get the number of elements in an array and ndim for number of dimensions in our array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*c_ksPhN5uSaYMKdSX4hZ6w.png" /></figure><p>We can also find shape like if a 2D array has 2 rows and 3 columns , then shape will be (2,3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*n_fCvoy0Yt2wIDQhHYFdPw.png" /></figure><h3><strong>Array Construction Functions</strong></h3><p>There are many array construction functions that we can use like creating arrays of ones or zeros can be useful as placeholder arrays and we can also create identity maatrices and diagonal matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*XJrgN5vgoNb7sX5q6e-XxQ.png" /></figure><p>Also, we can use arange function to create an array(Its behavior is similar to that of the range function in python) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*dijRXTcg1xB7AdYjuuId7w.png" /></figure><p>Also we use linspace function if we want to create a particular number of evenly spaced values in a specified half-open interval:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*hoZTzYKYIB9vHqQ6B5QwJA.png" /></figure><h3><strong>Array Indexing</strong></h3><p>Remember : If we work with arrays that have more than one dimension or axis, we separate our indexing or slicing operations by commas.</p><p>You need to understand axes before this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*GYaKSvauKFPhrrW6" /><figcaption>Source : <a href="https://www.statology.org/numpy-axis/">https://www.statology.org/numpy-axis/</a></figcaption></figure><p>To do indexing and slicing in one cmd, we do something like this:<br>ary[a:b,c:d]</p><p>Now here, first value before comma is for rows and second value after comma is for column and then you just apply slicing and give results, See this examples :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*XjV1v1rr0j1MacEUtnuZQQ.png" /></figure><h3>Array Math and Universal Functions</h3><p>One of the core features of NumPy is vectorization because it makes working with ndarrays really efficient. NumPy provides vectorized wrappers for performing element-wise operations if we want to perform arithmetic operations on sequence-like objects — these are called ufuncs.</p><p>The ufuncs for basic arithmetic operations are add, subtract, divide, multiply, power, and exp (exponential). However, NumPy uses operator overloading so that we can use mathematical operators (+, -, /, *, and **) directly.</p><p>Lets see some unary ufuncs such as log (natural logarithm), log10 (base-10 logarithm), and sqrt (square root) and some binary ufuncs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofn5CUbwNqkNx5qfY094Nw.png" /></figure><h3><strong>Reduce and Sum</strong></h3><p>With the help fo reduce, we can compute any operation like sum or product along an axis and reduce the array. While it can be more intuitive to use reduce as a more general operation, NumPy also provides shorthands for specific operations such as product and sum. For example, sum(axis=0) is equivalent to add.reduce . See examples :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*vvHCAhxzmrit-H1DjmNa9g.png" /></figure><p>Kindly see this , you will have a better understanding of what I am talking about:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*N6myjRg-gb3Bfr3s.png" /><figcaption>Source : <a href="https://practicaldatascience.org/notebooks/class_2/week_4/03_summarizing_arrays.html">https://practicaldatascience.org/notebooks/class_2/week_4/03_summarizing_arrays.html</a></figcaption></figure><p>So, the things that we did just now is known as <strong>Broadcasting. </strong>Broadcasting allows us to perform vectorized operations between two arrays even if their dimensions do not match by creating implicit multidimensional grids. ufuncs is one example of Broadcasting. See this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XentfakCzvs9Bjx-.jpg" /><figcaption>Source : <a href="https://blog.finxter.com/numpy-broadcasting-a-simple-tutorial/">https://blog.finxter.com/numpy-broadcasting-a-simple-tutorial/</a></figcaption></figure><h4>Advanced Indexing — Memory Views and Copies</h4><p>Remember — It is important to note that basic integer-based indexing and slicing create so-called <em>views</em> of NumPy arrays in memory. Also, whenever you change something in views, the original array is also modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*rJ0fkawPVxotUUnImuzvyw.png" /></figure><p>But if you don’t want to modify the original array, you have to use the copy() method :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*fwkSbg6DPyB6dpsyYa_q-A.png" /></figure><h3><strong>Fancy Indexing</strong></h3><p>We can use tuple or list objects of non-contiguous integer indices to return desired array elements :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*gPDDGnYV1o8M9q6EQyhiHw.png" /></figure><h4>Boolean Masks for Indexing</h4><p>We can also use Boolean masks for indexing — that is, arrays of True and False values. Consider the following example, where we return all values in the array that are greater than 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*my9SxVoEwUUkycmjZq5sAw.png" /></figure><h3>Random Number Generators</h3><p>A computer doesn’t normally generate truly random numbers. NumPy uses a <strong>pseudo-random number generator (PRNG)</strong>.</p><p>Remember — We first seed NumPy’s random number generator. Then, we draw random samples from a uniform distribution via random.rand in the half-open interval [0, 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*XlksDItBStG31bsyaPCRdg.png" /></figure><p>But lets say, we have two functions :</p><blockquote>def generate_data():<br> return np.random.rand(3)</blockquote><blockquote>def generate_noise():<br> return np.random.rand(3)</blockquote><p>So, both functions are using the same global random generator and lets say, we execute both functions:</p><blockquote>generate_data() <br>generate_noise()</blockquote><p>Then :</p><p>Global RNG<br> │<br> ├── generate_data() → consumes 3 random numbers<br> │<br> └── generate_noise() → consumes the NEXT 3 numbers</p><p>Now suppose you change generate_data() and it consumes 5 random numbers instead of 3. Suddenly generate_noise() gets completely different numbers.</p><p><em>That’s annoying for testing.</em></p><p>To solve this, we use <strong>Separate </strong><strong>RandomState objects</strong></p><pre>rng_data = np.random.RandomState(100)<br>rng_noise = np.random.RandomState(200)</pre><p>Now you have:</p><pre>rng_data<br>   ↓<br>its own random sequence<br><br><br>rng_noise<br>   ↓<br>a completely separate random sequence</pre><p>They don&#39;t interfere with each other.</p><h3>Reshaping NumPy Arrays</h3><p>NumPy provides a reshape methods that allow us to obtain a view of an array with a different shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Dy7MK1f4-Jn4HujqgaL-Ow.png" /></figure><p>We do not need to specify the number elements in each axis; NumPy is smart enough to figure out how many elements to put along an axis if only one axis is unspecified (by using the placeholder -1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LuQQ3_Yfad3VY7Gy2_lFlg.png" /></figure><p>Flattening the array using reshape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*dSABBOfUq0r_7Vzz_JrnDQ.png" /></figure><p>NumPy’s Concate Function to merge two arrays :<br><strong><em>Remember : axis = 0 means rows and axis = 1 means columns</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*Q87-cTL_sLdcEdeY2F9f7g.png" /></figure><h3>Linear Algebra with NumPy</h3><p>To perform matrix multiplication between matrices, we learned that number of columns of the left matrix must match the number of rows of the matrix to the right. In NumPy, we can perform matrix multiplication via the matmul function.</p><p>Also, NumPy can be quite forgiving if the dimensions of matrices and one-dimensional arrays do not match exactly — thanks to broadcasting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*_qHrwoDDu1jK78GWhvru1w.png" /></figure><p>NumPy has a special dot function that behaves similar to matmul on pairs of one- or two-dimensional arrays or we can also use @ :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*oyBXpjz3AIwyNlLYmVqCkg.png" /></figure><p>Transpose :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*nXlcdDkccoMNQe26xAEnHQ.png" /></figure><h3><strong>Thank you for reading till here</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27fa02f33156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let me tell you how easy understanding Entropy really is]]></title>
            <link>https://medium.com/@bireshkumar1964/let-me-tell-you-how-easy-understanding-entropy-really-is-92a8c22bb1df?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a8c22bb1df</guid>
            <category><![CDATA[entropy]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[information-theory]]></category>
            <category><![CDATA[claude-shannon]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 10:37:41 GMT</pubDate>
            <atom:updated>2026-08-07T10:37:41.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ko2y9rgZlj3QwPyL.png" /><figcaption>Source : <a href="https://www.theclickreader.com/cost-functions-in-machine-learning/">https://www.theclickreader.com/cost-functions-in-machine-learning/</a></figcaption></figure><p>This blog is about <strong>entropy</strong>, <strong>cross-entropy</strong>, and <strong>KL divergence -</strong>three concepts from Information Theory that are used everywhere in machine learning. In fact, <strong>cross-entropy is one of the most commonly used loss functions for training ML classifiers</strong>, so understanding these ideas is much more useful than they might initially seem.</p><p>It all started with Claude Shannon’s famous paper, <strong>“A Mathematical Theory of Communication.”</strong> This paper laid the foundation for what we now call <strong>Information Theory</strong>.</p><p>The original goal was surprisingly simple: <strong>how do we transmit a message from a sender to a receiver as efficiently and as reliably as possible?</strong></p><p>Every message can ultimately be represented using bits (0s and 1s). But not every bit we send is equally useful. Some bits are redundant, some may be corrupted by noise, and some carry more information than others. Shannon’s goal was to answer a fundamental question:</p><blockquote><strong><em>How can we measure the actual amount of information contained in a message?</em></strong></blockquote><p>Suppose we have a robot on the Moon, and we’re sending commands to it from Earth.</p><p>The robot can move in exactly four directions:</p><ul><li>Forward</li><li>Backward</li><li>Left</li><li>Right</li></ul><p>Since there are <strong>4 equally likely commands</strong>, we can encode them using just <strong>2 bits</strong>:</p><ul><li>00 → Forward</li><li>01 → Backward</li><li>10 → Left</li><li>11 → Right</li></ul><p>So, two bits are enough to distinguish between four equally likely possibilities.</p><p>Now let’s make things a little more interesting.</p><p>Suppose our robot no longer receives all four movement commands with equal probability.</p><p>Instead, the probabilities are:</p><ul><li><strong>Forward:</strong> 50%</li><li><strong>Backward:</strong> 25%</li><li><strong>Left:</strong> 12.5%</li><li><strong>Right:</strong> 12.5%</li></ul><p>Earlier, when every command was equally likely, assigning <strong>2 bits to every direction</strong> made perfect sense.</p><p>But now, that isn’t the most efficient way to encode the messages.</p><p>Since <strong>Forward</strong> happens much more often than the other commands, shouldn’t it have a shorter code? And shouldn’t the rarer commands get longer codes?</p><p>That’s exactly the idea behind efficient compression.</p><p>One possible encoding is:</p><ul><li><strong>Forward → 0</strong></li><li><strong>Backward → 10</strong></li><li><strong>Left → 110</strong></li><li><strong>Right → 111</strong></li></ul><p>Notice something interesting here.</p><p>The most frequent command, <strong>Forward</strong>, only needs <strong>1 bit</strong>.</p><p>The less frequent command, <strong>Backward</strong>, needs <strong>2 bits</strong>.</p><p>And the two rarest commands need <strong>3 bits</strong> each.</p><p>So, on average, we’re sending fewer bits than before while still being able to represent every command correctly.</p><p>There’s one very important property of this encoding.</p><p>It is called a <strong>prefix-free code</strong> (or simply a <strong>prefix code</strong>).</p><p>A prefix-free code means that <strong>no valid code is the prefix of another valid code</strong>. Because of this, the receiver always knows exactly where one code ends and the next one begins — without needing any extra separators.</p><p>For example, suppose the robot receives this bit sequence:</p><pre>011010</pre><p>Let’s decode it step by step.</p><ul><li>The first bit is <strong>0</strong>, which immediately means <strong>Forward</strong>.</li><li>The next bit is <strong>1</strong>, so we know it isn’t Forward anymore. It could still be Backward, Left, or Right.</li><li>The following bit is another <strong>1</strong>, so now it can only be Left or Right.</li><li>The next bit is <strong>0</strong>, giving us <strong>110</strong>, which means <strong>Left</strong>.</li><li>We’re left with <strong>10</strong>, which corresponds to <strong>Backward</strong>.</li></ul><p>So the sequence decodes unambiguously as:</p><p><strong>Forward → Left → Backward</strong></p><p>At no point do we wonder where one command ends and the next begins. That’s exactly why prefix-free codes are so useful.</p><p>More importantly, this encoding naturally gives <strong>shorter codes to common events and longer codes to rare events</strong>, making communication more efficient on average.</p><blockquote>This beautiful example comes from <strong>3Blue1Brown’s <em>Reinventing Entropy: Compression and Intelligence (Part 1-</em></strong><a href="https://youtu.be/l6DKRf-fAAM?si=JsBU56y5GaFOclna">https://youtu.be/l6DKRf-fAAM?si=JsBU56y5GaFOclna</a><strong><em>)</em></strong>, and it’s one of the best intuitions I’ve seen for why Information Theory works the way it does.</blockquote><p>As you can probably notice by now, <strong>common events deserve shorter descriptions, while rare events deserve longer ones.</strong></p><p>Imagine you had a <strong>perfect compression algorithm</strong>.</p><p>If it has removed every unnecessary bit and every bit of redundancy from a message, then the output shouldn’t have any obvious patterns left. In other words, <strong>the compressed bit stream should look almost indistinguishable from random noise.</strong></p><p>Why?</p><p>Because <strong>random noise is essentially incompressible</strong>. If there were still patterns left in the compressed data, you could compress it even further — which would mean your compression algorithm wasn’t actually perfect.</p><p>Now let’s go back to our robot example.</p><p>We assigned the following codes:</p><ul><li>Forward → <strong>0</strong></li><li>Backward → <strong>10</strong></li><li>Left → <strong>110</strong></li><li>Right → <strong>111</strong></li></ul><p>At first glance, this might just look like a clever encoding scheme. But there’s something much deeper happening.</p><p>Notice what happens while you’re decoding the message.</p><ul><li>The <strong>first bit</strong> is equally likely to be <strong>0 or 1</strong>.</li></ul><p>If it’s <strong>0</strong>, we’re done — the command is <strong>Forward</strong>.</p><p>Now suppose the first bit was <strong>1</strong>.</p><p>The <strong>next bit</strong> is again equally likely to be <strong>0 or 1</strong>.</p><ul><li>If it’s <strong>0</strong>, we’ve decoded <strong>Backward</strong>.</li><li>If it’s <strong>1</strong>, we’re left with only <strong>Left</strong> and <strong>Right</strong>.</li></ul><p>And once again, the <strong>next bit</strong> is equally likely to be <strong>0 or 1</strong>, telling us whether the command is <strong>Left</strong> or <strong>Right</strong>.</p><p>At every stage, the next bit behaves like a <strong>fair coin flip and </strong>there’s always a 50–50 split between the remaining possibilities.</p><p>That’s exactly what random bits look like.</p><p>So although the original commands had very different probabilities, the <strong>encoded bit stream itself looks statistically like random noise</strong>, which is precisely what we’d expect from an efficient compression algorithm.</p><p>This gives us a powerful way to think about information.</p><p>If an event has probability p, then an efficient encoding should assign it just enough bits so that, after encoding, the resulting bit stream still looks random.</p><p>If a <strong>perfect compression algorithm</strong> produces something that looks like random noise, then every possible compressed message of length n bits should be <strong>equally likely</strong>.</p><p>Why?</p><p>There’s one final step that beautifully connects this intuition to the formula.</p><p>If a perfect compression algorithm produces something that looks like random noise, then every possible compressed message of length n bits should be equally likely.</p><p>Why?</p><p>Because an n-bit message can have exactly 2^n different bit patterns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9-q9sGqrFvhwZLpe.png" /></figure><p>If the output truly behaves like random noise, then no particular bit pattern is more special than another. Every one of these 2^n possible messages is equally likely.</p><p>That means the probability of receiving any one specific compressed message is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/0*c1DuJ4LKBN1cDuyr.png" /></figure><p>Now comes the neat part.</p><p>Starting with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*-KDYUqpBTrmCRFGw.png" /></figure><p>Taking log base 2 on both sides gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/0*tXdGnkgx0Bwj56MY.png" /></figure><p>Rearranging,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*GIHPvCtCgeX_kqen.png" /></figure><p>But what does n represent here?</p><p>It is simply the number of bits needed to optimally encode that message.</p><p>In other words, we’ve arrived at the exact same expression we were using earlier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*aBf24xQrZJg1KmA8.png" /></figure><p>I found this derivation really satisfying because we didn’t just accept the formula — we rediscovered it by thinking about what an ideal compression algorithm should do.</p><p>The idea that information is simply the minimum number of bits needed to describe an event is, in my opinion, one of the most elegant insights in Information Theory.</p><p>We can also visualize this idea by plotting −log2​(p) against the probability p.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cyxEna3ltP2838KQk3zUw.png" /><figcaption>Source : Reinventing Entropy | Compression is Intelligence Part 1-<a href="https://youtu.be/l6DKRf-fAAM?si=Eud3UopqbrtdmHLE">https://youtu.be/l6DKRf-fAAM?si=Eud3UopqbrtdmHLE</a></figcaption></figure><p>The graph tells a very intuitive story.</p><p>When an event has a <strong>high probability</strong>, the value of −log2​(p) is small. In other words, learning that the event happened doesn’t tell us much — we were already expecting it.</p><p>On the other hand, when an event has a <strong>very low probability</strong>, the value of −log2​(p) becomes much larger. If that unlikely event actually occurs, we gain a lot more information because it was surprising.</p><p>This brings us back to the same intuition we’ve been building throughout this article:</p><blockquote><strong><em>The rarer an event is, the more information it carries when it occurs. Entropy extends this idea by asking: on average, how much information do we gain when we observe an outcome from a probability distribution?</em></strong></blockquote><p>Or even more simply:</p><blockquote><strong><em>Rare events carry more information, but entropy is the average amount of information over all possible events, weighted by their probabilities.</em></strong></blockquote><p>This naturally leads to Shannon’s entropy formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*3LJkdLgb2xewX1O-.png" /></figure><p>Lets understand Enttropy with a weather example :</p><p>Suppose tomorrow’s weather has only two possible outcomes:</p><ul><li><strong>Sunny:</strong> 75%</li><li><strong>Rainy:</strong> 25%</li></ul><p>But Sunny doesn’t happen as often as Rainy -it occurs <strong>75% of the time</strong>, while Rainy occurs only <strong>25% of the time</strong>.</p><p>So, if we want the <strong>average information per day</strong>, we simply take a weighted average, where each outcome is weighted by how often it occurs.</p><p>That gives us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZDSjJ76QS779vdOq.png" /></figure><p>Evaluating this expression gives approximately 0.81 bits.</p><p>This means that, <strong>on average, observing tomorrow’s weather gives us about 0.81 bits of information.</strong></p><p>This quantity is called <strong>entropy</strong>.</p><p>Now that we understand entropy, we can finally talk about <strong>cross-entropy</strong>.</p><p>The easiest way to think about cross-entropy is this:</p><blockquote><strong><em>Suppose we designed the perfect compression scheme for one probability distribution. What happens if the world changes, but we keep using the old compression scheme?</em></strong></blockquote><p>How many bits would we need <strong>on average</strong> now?</p><p>That’s exactly what cross-entropy measures.</p><p>Let’s go back to our robot example.</p><p>Suppose we originally believed the robot would move with these probabilities:</p><ul><li><strong>Forward:</strong> 1/2</li><li><strong>Backward:</strong> 1/4</li><li><strong>Left:</strong> 1/8</li><li><strong>Right:</strong> 1/8</li></ul><p>Based on these probabilities, we designed an efficient code:</p><ul><li>Forward → <strong>0</strong> (1 bit)</li><li>Backward → <strong>10</strong> (2 bits)</li><li>Left → <strong>110</strong> (3 bits)</li><li>Right → <strong>111</strong> (3 bits)</li></ul><p>This code is optimal <strong>for this particular probability distribution</strong>.</p><p>But now imagine the robot’s behavior changes.</p><p>The new probabilities become:</p><ul><li><strong>Forward:</strong> 1/8</li><li><strong>Backward:</strong> 1/8</li><li><strong>Left:</strong> 1/4</li><li><strong>Right:</strong> 1/2</li></ul><p>Notice that our old encoding is no longer a good fit.</p><p>The event that now happens most often (<strong>Right</strong>) still requires <strong>3 bits</strong>, while the least frequent event (<strong>Forward</strong>) only requires <strong>1 bit</strong>.</p><p>We’re using the wrong compression scheme for the new distribution.</p><p>To find the average number of bits we now need, we weight each code length by the <strong>new (true) probabilities</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sNO5kHqHvxjtOPKv.png" /></figure><p>This average number of bits is called the <strong>cross-entropy</strong>.</p><p>Notice what’s happening here.</p><p>The <strong>probabilities</strong> come from the <strong>true distribution</strong> — the way the world actually behaves today.</p><p>But the <strong>code lengths</strong> come from the <strong>old distribution</strong> that we originally optimized for.</p><p>We can write the cross-entropy mathematically as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h5q-aljGieSr2XjD.png" /></figure><p>Here:</p><ul><li>P(x) is the <strong>true probability</strong> of each event.</li><li>Q(x) is the <strong>probability assumed by our compression scheme (or our model).</strong></li></ul><p>So, in words:</p><blockquote><strong><em>Cross-entropy is the average number of bits needed to encode data that actually follows distribution P, when we use a code that was designed for distribution Q.</em></strong></blockquote><p>Now we have one final concept left: <strong>KL divergence</strong>.</p><p>Fortunately, it’s much simpler once you understand entropy and cross-entropy.</p><p>Remember what we learned:</p><ul><li><strong>Entropy</strong> tells us the average number of bits needed when we use the <strong>optimal code for the true distribution</strong>.</li><li><strong>Cross-entropy</strong> tells us the average number of bits needed when we use a <strong>code designed for a different distribution</strong>.</li></ul><p>Since the second code is generally not optimal, it usually requires <strong>more bits</strong>.</p><p>This naturally raises a question:</p><blockquote><strong><em>How many extra bits are we wasting because we’re using the wrong probability distribution?</em></strong></blockquote><p>That’s exactly what <strong>KL divergence</strong> measures.</p><p>Mathematically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gJcR7B79qdPcdUXu.png" /></figure><p>where:</p><ul><li>(H(P)) is the entropy of the true distribution.</li><li>(H(P,Q)) is the cross-entropy between the true distribution (P) and the predicted distribution (Q).</li></ul><p>So, KL divergence is simply the <strong>difference between cross-entropy and entropy</strong>.</p><p>If our assumed distribution is exactly the same as the true distribution, then the compression scheme is already optimal.</p><p>In that case,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*J-aM0pZ5aMwPOzYG.png" /></figure><p>which means</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*4DZUuOIzBc-MpLcK.png" /></figure><p>A KL divergence of <strong>zero</strong> means the two probability distributions are identical. As the two distributions become more different, the KL divergence increases.</p><p>Now let’s see why cross-entropy is used as the loss function for machine learning classifiers.</p><p>Suppose we’re training a classifier to recognize the following animals:</p><ul><li>Cat</li><li>Dog</li><li>Fox</li><li>Cow</li><li>Panda</li><li>Bear</li><li>Dolphin</li></ul><p>Imagine the input image is actually a <strong>panda</strong>.</p><p>Since this is a supervised learning problem, we already know the correct answer.</p><p>The <strong>true distribution</strong> is therefore:</p><ul><li>Panda → 1</li><li>Every other class → 0</li></ul><p>Now suppose our model predicts the following probabilities:</p><ul><li>Cat → 2%</li><li>Dog → 30%</li><li>Fox → 45%</li><li>Cow → 0%</li><li>Panda → 25%</li><li>Bear → 5%</li><li>Dolphin → 0%</li></ul><p>To compute the loss, we use the cross-entropy formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*y8M5004azpk2XP74.png" /></figure><p>where:</p><ul><li>(y_i) is the true probability.</li><li>(y_i hat) is the probability predicted by the model.</li></ul><p>Since only the Panda class has a true probability of 1, every other term becomes zero.</p><p>The loss therefore simplifies to -log(0.25) which is approximately 1.386.</p><p>Notice something really elegant here.</p><p>The model is <strong>only penalized based on the probability it assigns to the correct class</strong>.</p><p>If the model had predicted Panda with 90% confidence instead of 25%, the loss would have been much smaller.</p><p>If it predicted Panda with 100% confidence, the loss would become <strong>zero</strong>, which is exactly what we want.</p><p>During training, the optimizer keeps adjusting the model’s parameters to minimize this cross-entropy loss.</p><p>But remember the relationship we just learned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VeO-Tonr8c2wShFk.png" /></figure><p>For a supervised learning dataset, the true labels (P) are fixed.</p><p>That means the entropy (H(P)) is also fixed -it doesn’t change while training.</p><p>So when we minimize the cross-entropy, we’re really minimizing only one thing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*pPbqmXhnwAAoHNOQ.png" /></figure><p>In other words, we’re making our model’s predicted distribution (Q) as close as possible to the true distribution (P).</p><p>That’s why cross-entropy works so well as a loss function. <strong>Minimizing cross-entropy is equivalent to minimizing the KL divergence between what the model predicts and what the data actually says.</strong></p><h3>A different way to think about KL divergence: “Expected surprise”</h3><p>Imagine you’re new in a city.</p><p>Your friend tells you,</p><blockquote><em>“Don’t worry. It hardly ever rains here.”</em></blockquote><p>So you leave your umbrella at home.</p><p>But for the next week, it rains almost every day.</p><p>Every morning you’re surprised.</p><p>Not because rain itself is surprising.</p><p>But because <strong>your mental model of the weather was wrong.</strong></p><p>Now imagine another friend who correctly told you,</p><blockquote><em>“It rains almost every day.”</em></blockquote><p>Now when it rains, you’re not surprised at all.</p><p>This is exactly what KL divergence measures.</p><p>It measures <strong>how much extra surprise you experience because you believed the wrong probability distribution.</strong></p><p>Notice the subtle wording.</p><p>It is <strong>not</strong> measuring how surprising reality is.</p><p>Reality is fixed.</p><p>It is measuring <strong>how surprised <em>your model</em> is by reality.</strong></p><p>That’s why</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*pPbqmXhnwAAoHNOQ.png" /></figure><p>is read as</p><blockquote><em>“How wrong is model Q, assuming reality actually follows P?”</em></blockquote><h3>Why isn’t KL divergence symmetric?</h3><p>This is the question almost everyone asks.</p><p>If it’s measuring the difference between two distributions, shouldn’t</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P74waqibhQuL9tbt.png" /></figure><p>The answer is <strong>no</strong>, because only <strong>one</strong> of them is assumed to be reality.</p><p>Think about this.</p><p>Suppose reality says</p><ul><li>Sunny = 99%</li><li>Rainy = 1%</li></ul><p>but your model believes</p><ul><li>Sunny = 50%</li><li>Rainy = 50%</li></ul><p>Your model isn’t great.</p><p>But you’ll rarely experience huge surprises.</p><p>Most days are sunny.</p><p>Your model thought there was a 50% chance of sunny.</p><p>Reality gave sunny.</p><p>Not too shocking.</p><p>Now flip the situation.</p><p>Reality says</p><ul><li>Sunny = 50%</li><li>Rainy = 50%</li></ul><p>but your model believes</p><ul><li>Sunny = 99%</li><li>Rainy = 1%</li></ul><p>Now something bad happens.</p><p>Every second day it rains.</p><p>Whenever it rains, your model is shocked because it thought rain almost never happens.</p><p>Reality keeps proving your model wrong.</p><p>So the KL divergence becomes much larger.</p><p>This is why KL divergence is <strong>not symmetric</strong>.</p><p>It always asks</p><blockquote><strong><em>“How wrong is my model in the world where reality follows P?”</em></strong></blockquote><p>It never asks the opposite question unless you explicitly swap P and Q.</p><h3>My favorite one-line intuition</h3><p>If I had to explain KL divergence in a single sentence, I’d say:</p><blockquote><strong><em>Entropy measures how surprising reality is. Cross-entropy measures how surprising reality is to your model. KL divergence measures the extra surprise caused because your model is wrong.</em></strong></blockquote><p>I genuinely think this is one of the cleanest ways to remember the relationship:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7FBdjT0XIcUiKGJ.png" /></figure><p>Entropy is the unavoidable uncertainty in the world.</p><p>KL divergence is the <strong>avoidable part</strong> — the extra cost you pay because your model doesn’t match reality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a8c22bb1df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backend Handbook Part 2 — Independent of any language]]></title>
            <link>https://medium.com/@bireshkumar1964/backend-handbook-part-2-independent-of-any-language-cdb10a86c8e4?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdb10a86c8e4</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 01:19:01 GMT</pubDate>
            <atom:updated>2026-02-18T01:19:01.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*SAlyZmXJPcLgmsVO.jpg" /><figcaption>credit — image from <a href="https://cyberacademy.co/new-attack-leverages-http-2-for-effective-remote-timing-side-channel-leaks/">https://cyberacademy.co/new-attack-leverages-http-2-for-effective-remote-timing-side-channel-leaks/</a></figcaption></figure><h3>Routing, Authentication, and Beyond</h3><h3>Routing: Mapping URLs to Logic</h3><p>HTTP methods describe the <strong>intent</strong> → they express the “what” of a request.</p><p>The role of <strong>routing</strong> is to express <strong>where</strong> or <strong>which resource</strong> you want to perform action on.</p><p><strong>Routing</strong> is mapping URL patterns to a particular handler. The route along with the method acts as a <strong>key</strong> that maps to the server handler.</p><h3>Types of Routes</h3><h4>1. Static Routes</h4><p>Constant, no dynamic parameters inside the route.</p><pre>/api/books<br>/api/users<br>/api/products</pre><h4>2. Dynamic Routes</h4><p>Contains dynamic parameters using : notation.</p><pre>/api/users/:id<br>/api/products/:productId</pre><p>The :id is a dynamic param or <strong>path param</strong>.</p><h4>3. Query Parameters</h4><p>Parameters passed after ? in the URL.</p><pre>/api/search?query=some+value<br>/api/books?page=2&amp;limit=10</pre><p><strong>Common use case: Pagination</strong></p><p>When user sends request to /api/books, server responds with:</p><pre>{<br>  &quot;data&quot;: [...],<br>  &quot;total&quot;: 100,<br>  &quot;page&quot;: 1,<br>  &quot;totalPages&quot;: 10,<br>  &quot;limit&quot;: 10<br>}</pre><p>Using this info, client can send subsequent request:</p><pre>/api/books?page=2</pre><h4>4. Nested Routes</h4><p>Hierarchical resource structure.</p><pre>/api/users/123/posts/456<br>/api/organizations/org-1/teams/team-5/members</pre><h4>5. Route Versioning</h4><p>Different versions of the same API.</p><pre>/api/v1/products<br>/api/v2/products</pre><p><strong>Use case:</strong> Let’s say you have an API version where you’re returning things in a special format, and later you have a different version that returns things in a different format — so you create a different route for that.</p><h4>6. Catch-All Route</h4><p>Route for URLs the server didn’t match — it gives a user-friendly message like “Route not found”.</p><pre>// Express.js example<br>app.use(&#39;*&#39;, (req, res) =&gt; {<br>  res.status(404).json({ error: &quot;Route not found&quot; });<br>});</pre><h3>Serialization and Deserialization</h3><p>Let’s say we have a JavaScript framework like React on the client side which sends a request body attached with GET or POST to a Rust server. Now, how will this server be able to understand the request body in its own language? We know Rust is pretty strict with types — so how?</p><h3>The Problem: Language-Agnostic Communication</h3><p><strong>Brief OSI Model Context:</strong> The OSI model has 7 layers — application layer on top and physical layer on bottom. We need some technique so that one machine is able to send data and another machine is able to parse and understand it — <strong>language agnostic</strong>.</p><h3>The Solution: Serialization Standards</h3><p>We come up with a <strong>common standard</strong> that client and server should follow. This is called a <strong>serialization standard</strong>.</p><p><strong>Serialization/Deserialization</strong> is converting to/from data to a common format during transmission so that it is language agnostic.</p><p><em>Note: In this guide, we focus on HTTP. For WebSockets, gRPC, etc., we can explore elsewhere.</em></p><h3>Types of Serialization Formats</h3><p><strong>Text-Based Serialization</strong> (80% of the time):</p><ol><li><strong>JSON</strong> — Most common</li><li><strong>XML</strong> — Legacy systems</li><li><strong>YAML</strong> — Configuration files</li></ol><p><strong>Binary Serialization:</strong></p><ol><li><strong>Protocol Buffers (protobuf)</strong> — Google’s format</li><li><strong>Avro</strong> — Apache’s format</li><li><strong>MessagePack</strong> — Compact binary format</li></ol><h3>JSON: The Standard</h3><p>JSON structure:</p><ul><li><strong>Key</strong>: Always a string in quotes</li><li><strong>Value</strong>: Can be string, number, boolean, array, or nested object</li></ul><pre>{<br>  &quot;user&quot;: {<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John&quot;,<br>    &quot;active&quot;: true,<br>    &quot;roles&quot;: [&quot;admin&quot;, &quot;editor&quot;],<br>    &quot;metadata&quot;: {<br>      &quot;lastLogin&quot;: &quot;2025-02-18&quot;<br>    }<br>  }<br>}</pre><p>JSON can be <strong>nested</strong> — inside a key, there can be another JSON object.</p><p><strong>Flow:</strong> Client sends JSON → Server responds with JSON</p><h3>Authentication and Authorization</h3><h3>Core Concepts: CIA Triad</h3><p><strong>CIA</strong> = Confidentiality, Integrity, <strong>Availability</strong></p><p><strong>Authentication</strong> — Who you are. It gives identity.</p><p><strong>Authorization</strong> — What capability you have. What permissions you have.</p><h3>Historical Evolution</h3><p><strong>1970s-1980s:</strong> Diffie-Hellman key exchange introduced asymmetric cryptography, which became the background of modern <strong>PKI (Public Key Infrastructure)</strong>. This eventually gave rise to Kerberos and then token-based auth.</p><p><strong>1990s:</strong> Need for scalable auth grew because username and password were prone to dictionary or brute force attacks. This led to <strong>MFA (Multi-Factor Authentication)</strong>.</p><p><strong>MFA combines:</strong></p><ol><li>Something you <strong>know</strong> (password)</li><li>Something you <strong>have</strong> (OTP generator, security card)</li><li>Something you <strong>are</strong> (biometric, fingerprint)</li></ol><p><strong>2000s-Present:</strong> Cloud and modern tech needed advanced auth. Latest auth mechanisms:</p><ul><li>OAuth 2.0</li><li>JWT (JSON Web Tokens)</li><li>Zero Trust Architecture</li><li>Passwordless authentication</li></ul><p><strong>Future:</strong> Decentralized identity, behavioral biometrics, post-quantum cryptography</p><h3>Why Stateful Auth Became Necessary</h3><p>Previously we used <strong>stateless interactions</strong> with HTTP, but as we needed dynamic content for e-commerce sites, we needed <strong>stateful content</strong>.</p><h3>Sessions: Server-Side State</h3><p><strong>Session</strong> is a way to establish temporary server-side context for a user.</p><h3>How Sessions Work</h3><ol><li>User logs in</li><li>Server creates <strong>unique session ID</strong> and stores it with user info in persistent store (DB or Redis)</li><li>Server sends <strong>session ID</strong> to browser as a <strong>cookie</strong></li><li>All subsequent requests include this cookie</li><li>Server uses session ID to fetch user info</li></ol><p>This enables some kind of <strong>memory</strong> for the browser, but sessions are short-lived and expire after some time.</p><h3>Evolution of Session Storage</h3><p><strong>Early days:</strong> File-based sessions → Scalability issues</p><p><strong>Later:</strong> Database lookup sessions</p><p><strong>Modern:</strong> Distributed architectures:</p><ul><li><strong>Redis</strong> — In-memory store (storing data in RAM)</li><li><strong>Memcache</strong> — Very fast compared to DB lookups</li></ul><h3>JWT: The Stateless Revolution</h3><h3>Why JWT?</h3><p>Sessions had problems:</p><ol><li>Retaining session data for thousands became large overhead</li><li>In distributed systems, synchronizing user data across servers in different regions introduced latencies and consistency challenges</li></ol><p>This led to the birth of <strong>JWT</strong>.</p><h3>What is JWT?</h3><p>JWT is a form of <strong>stateless mechanism</strong> for transferring claims between two parties. The key innovation: <strong>self-contained tokens</strong>.</p><p>JWT tokens contain:</p><ul><li>User data</li><li>Cryptographic signature</li><li>Base64 encoding</li></ul><h3>JWT Structure (3 Parts)</h3><p><strong>1. Header</strong> — Metadata about JWT</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>Information on signing algorithm used.</p><p><strong>2. Payload</strong> — User data</p><pre>{<br>  &quot;sub&quot;: &quot;user123&quot;,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;iat&quot;: 1516239022<br>}</pre><ul><li>sub - User ID</li><li>name - User name</li><li>iat - Issued at (timestamp)</li></ul><p><strong>3. Verify Signature</strong></p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; +<br>  base64UrlEncode(payload),<br>  secret<br>)</pre><p>To verify that the issuer was authentic.</p><h3>Benefits of JWT</h3><p>✅ <strong>Stateless</strong> — No database lookup needed<br> ✅ <strong>Scalable</strong> — Works across multiple servers<br> ✅ <strong>Portable</strong> — Can be used across different domains</p><h3>Challenges with JWT</h3><p>❌ <strong>Token theft</strong> — If someone has access to your JWT, they can perform actions on your behalf unless JWT expires.</p><p><strong>Solution: Hybrid Approach</strong></p><ol><li>User logs in → Server sends JWT to user → User stores JWT</li><li>User sends JWT as Authorization header in every subsequent request</li><li>Server maintains a <strong>blacklist</strong> of compromised JWTs in persistent storage</li><li>After verifying JWT, check against blacklist to temporarily block hacked users</li></ol><p><em>Note: This reintroduces some statefulness, but adds security.</em></p><h3>Industry Practice</h3><p>In industry, we don’t implement these strategies ourselves — we use <strong>auth providers</strong> like:</p><ul><li><strong>Clerk</strong></li><li><strong>Auth0</strong></li><li><strong>Firebase Auth</strong></li><li><strong>Supabase Auth</strong></li></ul><p>It’s a good idea to use auth providers for really large production systems.</p><h3>Cookies: Client-Side Storage</h3><p><strong>Cookies</strong> are a way of storing a piece of information in a user’s browser from the server side, provided that the server can’t see cookies of other browsers.</p><h3>Cookie Attributes</h3><pre>Set-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict; Max-Age=3600</pre><ul><li>Secure - Only sent over HTTPS</li><li>HttpOnly - Inaccessible to JavaScript (prevents XSS)</li><li>SameSite - Prevents CSRF attacks</li><li>Max-Age - Expiration time</li></ul><h3>The Three Pillars of Modern Auth</h3><ol><li><strong>Sessions</strong> — Server-side state management</li><li><strong>JWT</strong> — Stateless token-based auth</li><li><strong>Cookies</strong> — Client-side storage mechanism</li></ol><h3>Authentication Strategies</h3><h3>1. Stateful Authentication</h3><p><strong>Flow:</strong></p><ol><li>Client sends username and password to server</li><li>Server checks correctness and validity</li><li>If correct, server generates <strong>session ID</strong> and stores in Redis or DB</li><li>Server sends session ID back to client in a cookie</li><li>All subsequent requests include this cookie</li></ol><p><strong>Pros:</strong></p><ul><li>Centralized control over all sessions</li><li>Easy to revoke access to a user</li><li>Most secure for applications with moderate traffic</li></ul><p><strong>Challenges:</strong></p><ul><li>Limited scalability</li><li>Higher operational complexity</li></ul><h3>2. Stateless Authentication (JWT)</h3><p><strong>Flow:</strong></p><ol><li>If credentials are correct, server uses <strong>secret key</strong> to generate signed JWT token</li><li>Server sends JWT back to client</li><li>In all subsequent requests, client sends JWT as Authorization header</li><li>Server verifies with secret key → Auth successful</li></ol><p>This is stateless because we don’t have to do DB lookup — we can get all info from the token itself.</p><p><strong>Pros:</strong></p><ul><li>Scalability</li><li>Lightweight</li></ul><p><strong>Cons:</strong></p><ul><li>Token revocation is complex</li></ul><p><strong>Hybrid Approach:</strong> Webapp in browser uses stateful auth, mobile apps or third-party integrations use stateless.</p><h3>3. API Key-Based Auth</h3><p>Simple authentication using API keys to gain access to a server.</p><pre>GET /api/data HTTP/1.1<br>X-API-Key: your-api-key-here</pre><p>Common for:</p><ul><li>Server-to-server communication</li><li>Third-party API access</li><li>Internal services</li></ul><h3>4. OAuth 2.0</h3><h4>The Delegation Problem</h4><p><strong>Scenario:</strong> Facebook wants to access your Google contacts.</p><p><strong>Problem:</strong> Sharing password is not a good idea.</p><p><strong>Solution:</strong> Tokens with limited permissions.</p><h4>OAuth 1.0 (Legacy)</h4><p><strong>Components:</strong></p><ul><li><strong>Resource Owner</strong> — Who owns the data (you)</li><li><strong>Client</strong> — Who is requesting access (Facebook)</li><li><strong>Resource Server</strong> — Where the data lives (Google)</li><li><strong>Authorization Server</strong> — Who provides the token (Google Auth)</li></ul><p><strong>Flow:</strong></p><ol><li>Client redirects user to authorization server</li><li>User authenticates and grants permissions</li><li>Auth server sends token to client (Facebook)</li><li>Client uses auth token to access the resource (contacts)</li></ol><h4>OAuth 2.0 (Modern)</h4><p><strong>Improvements:</strong></p><ul><li>Introduced <strong>bearer tokens</strong> (more vulnerable but simpler)</li><li>Multiple flows based on app type:</li></ul><ol><li><strong>Authorization Code Flow</strong> — Server-side apps</li><li><strong>Implicit Flow</strong> — Browser-based apps</li><li><strong>Client Credentials</strong> — Machine-to-machine communication</li><li><strong>Device Code Flow</strong> — Devices with limited input (Smart TV)</li></ol><h4>OpenID Connect (OIDC)</h4><p>OAuth was great for <strong>authorization</strong> but not for <strong>authentication</strong>.</p><p>In 2014, <strong>OpenID Connect</strong> was built on top of OAuth 2.0 to fill the authentication gap.</p><p><strong>OIDC extended OAuth 2.0</strong> with <strong>ID Token</strong> (generally JWT) which contains:</p><ul><li>User ID</li><li>Issued at timestamp (iat)</li><li>Issuing authority</li><li>Other user info</li></ul><p><strong>Working of OpenID Connect:</strong></p><ol><li>Client redirects to auth server after clicking “Sign In”</li><li>User logs in Google account and provides permissions</li><li>Auth server sends <strong>auth code</strong> and <strong>ID token</strong> back to client</li><li>Client uses auth code and exchanges it with server for <strong>access token</strong> and gets <strong>ID token</strong></li></ol><h3>When to Use What?</h3><p>Auth Type Use Case <strong>Stateful</strong> Web applications <strong>Stateless (JWT)</strong> APIs, microservices <strong>OAuth 2.0</strong> Third-party integrations <strong>API Key</strong> Server-to-server</p><h3>Role-Based Access Control (RBAC)</h3><p>In modern applications, we use <strong>RBAC</strong>.</p><p><strong>Example roles:</strong></p><ul><li><strong>User</strong> — Read only</li><li><strong>Admin</strong> — Read/Write</li><li><strong>Owner</strong> — Full control</li><li><strong>Editor</strong> — Edit content</li></ul><p>Using different roles and permissions, we can go <strong>as granular as we want</strong>.</p><pre>{<br>  &quot;role&quot;: &quot;editor&quot;,<br>  &quot;permissions&quot;: [<br>    &quot;posts:read&quot;,<br>    &quot;posts:write&quot;,<br>    &quot;posts:edit&quot;,<br>    &quot;posts:delete&quot;<br>  ]<br>}</pre><h3>Cybersecurity Best Practices</h3><h3>1. Appropriate Error Messages</h3><p><strong>❌ Bad Practice:</strong></p><pre>{ &quot;error&quot;: &quot;Incorrect password&quot; }</pre><p>Attacker learns that the username exists.</p><p><strong>✅ Good Practice:</strong></p><pre>{ &quot;error&quot;: &quot;Invalid credentials&quot; }</pre><p>Always send <strong>generic messages</strong> to the client so that attackers get confused. Don’t send user-friendly error messages in auth endpoints.</p><h3>2. Timing Attacks</h3><p><strong>Timing attack</strong> is an attack utilizing timing differences between different processes.</p><p><strong>Example scenario:</strong></p><pre>Username invalid → Fast response (no password hashing)<br>Username valid but password wrong → Slower response (password hashing performed)</pre><p>Using that delay, attackers can find out whether the username was correct or not.</p><h3>Defense Against Timing Attacks</h3><p><strong>1. Constant-time operations</strong> — Constant time comparison functions which ensure execution time doesn’t depend on input similarity.</p><p><strong>2. Simulate response delay</strong> — Add fake delay always.</p><pre>// Example: Always take at least 500ms to respond<br>const startTime = Date.now();<br>// ... authentication logic ...<br>const elapsed = Date.now() - startTime;<br>if (elapsed &lt; 500) {<br>  await new Promise(resolve =&gt; setTimeout(resolve, 500 - elapsed));<br>}<br>return response;</pre><p>This ensures auth endpoints take the same time regardless of whether username exists or password is wrong.</p><p><em>If you found this helpful, give it a clap 👏 and follow for Part 3!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdb10a86c8e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backend Handbook Part 1 — Independent of any language]]></title>
            <link>https://medium.com/@bireshkumar1964/backend-handbook-part-1-independent-of-any-language-252fc358cb45?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/252fc358cb45</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[first-principles-thinking]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[scalable-systems]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 23:21:55 GMT</pubDate>
            <atom:updated>2026-02-16T23:21:55.229Z</atom:updated>
            <content:encoded><![CDATA[<h3>You kinda understand it, but do you want to feel it? If yes, read this article.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yXS6a19d2gXx69TU.jpg" /><figcaption>credits of the image — <a href="https://www.slideshare.net/slideshow/introduction-to-backend-engineering/264496270">https://www.slideshare.net/slideshow/introduction-to-backend-engineering/264496270</a></figcaption></figure><h4>Why Backend Matters</h4><p>Backend is required if you want to transfer your knowledge from one programming language to another because <strong>the first principles are always the same</strong>. This article will take you through the journey of how a request flows through the internet and back, breaking down every hop, firewall, and protocol along the way.</p><h3>The Journey of a Request: DNS to Your Server</h3><h3>How Requests Reach Your EC2 Instance</h3><p>When you configure DNS, you create records:</p><ul><li><strong>A Record</strong> — Points to a particular IP address</li><li><strong>CNAME Record</strong> — Points to a particular domain name</li></ul><p>The IP address typically comes from an <strong>AWS EC2 instance</strong> (public IP). Here’s the flow:</p><pre>Browser → DNS → AWS Firewall (Security Group) → EC2 Instance → Nginx → localhost:PORT</pre><p><strong>Security Groups</strong> act as AWS firewalls where you define rules to allow specific ports.</p><h3>Reverse Proxy with Nginx</h3><p>Once the request reaches EC2, <strong>Nginx</strong> acts as a reverse proxy — a server in front of other servers to manage different configurations and redirect from a centralized place.</p><p>Your Node.js server runs on localhost:PORT, and Nginx redirects any request to your domain name to this localhost.</p><p><strong>Proof?</strong> SSH into your EC2 instance and run:</p><pre>curl localhost:3000/api/users</pre><p>You’ll see the same response as visiting the site externally.</p><h3>Tools in the Stack</h3><ul><li><strong>Certbot</strong>: Assigns SSL certificates automatically</li><li><strong>PM2</strong>: Process manager for Node.js applications</li><li><strong>Nginx</strong>: Reverse proxy configuration</li></ul><h3>Frontend vs Backend: Runtime Differences</h3><h3>Frontend (Browser)</h3><ul><li>HTML, CSS, and JS are <strong>fetched by the browser from the server</strong></li><li>Browser works as a <strong>runtime environment</strong></li><li>Once CSS is fetched → <strong>paints the window</strong></li><li>Once JS is fetched → <strong>hydration, event listeners</strong> run in the browser</li><li>Then buttons start working</li></ul><h3>Backend (Server)</h3><ul><li>Things are <strong>directly run and fetched from the server itself</strong></li><li>Processing happens <strong>on the server</strong></li></ul><h3>Browser Security</h3><p>Browsers are <strong>sandbox environments</strong> — isolated from your OS. Code can only access limited resources like storage.</p><p><strong>CORS Policy</strong> prevents remote code from accessing things rendered in your local browser — otherwise that would be scary!</p><h3>HTTP Protocol: The Foundation</h3><h3>Statelessness: No Memory</h3><p>Each HTTP request is <strong>independent</strong> with no memory of past interactions.</p><p><strong>This means:</strong></p><ul><li>Each request should include all data (access tokens, cookies, etc.)</li></ul><p><strong>Benefits:</strong></p><ol><li><strong>Simplicity</strong> — Server doesn’t need to store session info</li><li><strong>Scalability</strong> — Easy to distribute requests across multiple servers</li><li><strong>Fault Tolerance</strong> — Server crashes don’t affect other requests</li></ol><p><strong>Trade-off:</strong> Cookie management or state management becomes necessary.</p><h3>Client-Server Model</h3><p>Communication is always <strong>initiated by the client</strong>, response given by the server.</p><p>To establish communication, they use <strong>TCP (Transmission Control Protocol)</strong>.</p><p><strong>TCP vs UDP:</strong></p><ul><li><strong>TCP</strong>: Reliable, HTTP relies on it (uses three-way handshake: SYN → SYN-ACK → ACK)</li><li><strong>UDP</strong>: Faster but unreliable</li></ul><h3>Evolution of HTTP</h3><h3>HTTP 1.0</h3><p>Each request opened a <strong>new connection</strong> (inefficient).</p><h3>HTTP 1.1</h3><p>Introduced <strong>persistent connections</strong>:</p><ul><li>Multiple requests over the same connection</li><li>Chunked transfer encoding</li></ul><h3>HTTP 2.0</h3><p>Major improvements:</p><ul><li><strong>Multiplexing</strong> — Multiple requests over a single connection</li><li><strong>Binary Framing</strong> — More efficient than text</li><li><strong>Header Compression (HPACK)</strong> — Reduces overhead</li><li><strong>Server Push</strong> — Server sends resources before they’re requested</li></ul><h3>HTTP 3.0</h3><p>Built on <strong>UDP (QUIC protocol)</strong>:</p><ul><li>Better handling of packet loss</li><li>Improved multiplexing without head-of-line blocking</li><li>Faster connection establishment</li></ul><h3>HTTP Headers: The Postal Analogy</h3><p><strong>Why headers outside the body?</strong></p><p>When you post a letter, you write the <strong>address, pincode, phone number outside</strong> the envelope — not inside. The postal worker (dakiya) needs this metadata to transmit your letter without opening it.</p><p>Similarly, headers give <strong>quick access to metadata</strong> without parsing the entire body.</p><h3>Types of Headers</h3><h4>1. Request Headers</h4><p>Provide information about the request:</p><ul><li>User-Agent - Client information</li><li>Authorization - Auth tokens</li><li>Cookie - Session data</li><li>Accept - Expected content type</li></ul><h4>2. General Headers</h4><p>Metadata about the message:</p><ul><li>Date - Timestamp</li><li>Cache-Control - Caching mechanisms (max-age, no-cache)</li><li>Connection - Connection type (keep-alive)</li></ul><h4>3. Representation Headers</h4><p>Representation of the resource:</p><ul><li>Content-Type - MIME type</li><li>Content-Length - Body size</li><li>Content-Encoding - Compression (gzip, deflate, br)</li><li>ETag - Unique identifier for caching</li></ul><h4>4. Security Headers</h4><p>Enhance security by controlling behavior:</p><pre># Ensures client only communicates over HTTPS<br>Strict-Transport-Security: max-age=31536000</pre><pre># Restricts sources from which content can be loaded (prevents XSS)<br>Content-Security-Policy: default-src &#39;self&#39;</pre><pre># Prevents iframe embedding (reduces clickjacking)<br>X-Frame-Options: DENY</pre><pre># Prevents MIME type sniffing<br>X-Content-Type-Options: nosniff</pre><pre># Secure cookies<br>Set-Cookie: sessionId=abc123; Secure; HttpOnly; SameSite=Strict</pre><p><strong>Why HTTP is Extensible:</strong></p><ul><li>Headers can be added without altering the protocol</li><li>Custom headers for specific applications</li><li>Content negotiation allows different versions based on client preferences</li></ul><h3>HTTP Methods: Define Intent</h3><h3>Common Methods</h3><pre>GET     - Retrieve data<br>POST    - Create new resource<br>PUT     - Complete replacement<br>PATCH   - Partial update (always prefer this unless you need full replacement)<br>DELETE  - Remove resource<br>OPTIONS - Query server capabilities (used in CORS)</pre><h3>Idempotency</h3><p><strong>Idempotent</strong> (same result no matter how many times executed):</p><ul><li>GET, PUT, DELETE</li><li>Example: Deleting a resource twice has the same effect</li></ul><p><strong>Non-Idempotent</strong>:</p><ul><li>POST</li><li>Example: Creating a user twice creates two users</li></ul><h3>CORS: Cross-Origin Resource Sharing</h3><p>CORS <strong>prevents servers from accepting requests from domains different from their own</strong>.</p><h3>Example Setup</h3><ul><li><strong>Client</strong>: example.com</li><li><strong>Server</strong>: api.example.com</li></ul><h3>Simple Request Flow</h3><ol><li>Client sends GET request</li><li>Browser adds Origin header</li><li>Server checks origin against CORS policy</li><li>Server responds with Access-Control-Allow-Origin header</li><li>If header matches client domain or *, browser allows JS to access the resource</li></ol><p><strong>Result:</strong> If CORS origin doesn’t match → <strong>CORS error</strong> in browser network tab.</p><h3>Preflight Request Flow</h3><p><strong>Triggers when: We are doing a CORS origin request and any of the below three is true:</strong></p><ol><li>Method is NOT GET, POST, or HEAD</li><li>Includes custom headers (e.g., Authorization)</li><li>Content-Type is NOT:</li></ol><ul><li>application/x-www-form-urlencoded</li><li>multipart/form-data</li><li>text/plain</li></ul><p><strong>How it works:</strong></p><pre># 1. OPTIONS request (preflight)<br>OPTIONS /api/users HTTP/1.1<br>Origin: example.com<br>Access-Control-Request-Method: PUT<br>Access-Control-Request-Headers: Authorization</pre><pre># 2. Server response<br>HTTP/1.1 204 No Content<br>Access-Control-Allow-Origin: example.com<br>Access-Control-Allow-Methods: PUT, DELETE<br>Access-Control-Allow-Headers: Authorization</pre><pre># 3. Actual PUT request<br>PUT /api/users/123 HTTP/1.1<br>Authorization: Bearer token123</pre><p>If preflight doesn’t pass → <strong>request blocked</strong>.</p><h3>HTTP Status Codes</h3><h3>1xx — Informational</h3><ul><li>100 Continue - Headers received, client can send body</li><li>101 Switching Protocols - Upgrading from HTTP to WebSockets</li></ul><h3>2xx — Success</h3><ul><li>200 OK - Request successful</li><li>201 Created - New resource created</li><li>204 No Content - Successful but no response body (common for DELETE)</li></ul><h3>3xx — Redirection</h3><ul><li>301 Moved Permanently - Resource moved to new URL</li><li>302 Found - Temporary redirect (e.g., temporary maintenance page)</li><li>304 Not Modified - Resource hasn&#39;t changed (used in caching)</li></ul><h3>4xx — Client Errors</h3><ul><li>400 Bad Request - Invalid data sent by client</li><li>401 Unauthorized - Not authenticated</li><li>403 Forbidden - Authenticated but lacks permission</li><li>404 Not Found - Resource unavailable, deleted, or URL incorrect</li><li>405 Method Not Allowed - Invalid HTTP method</li><li>409 Conflict - Request conflicts with server state (e.g., duplicate file names)</li><li>429 Too Many Requests - Rate limit exceeded</li></ul><h3>5xx — Server Errors</h3><ul><li>500 Internal Server Error - Unhandled exception</li><li>501 Not Implemented - Server doesn&#39;t support the method yet</li><li>502 Bad Gateway - Error in proxy (like Nginx)</li><li>503 Service Unavailable - Maintenance or high traffic</li><li>504 Gateway Timeout - Upstream server failed to respond in time</li></ul><h3>HTTP Caching</h3><h3>How It Works</h3><p><strong>First Request:</strong></p><pre>HTTP/1.1 200 OK<br>Cache-Control: max-age=10<br>ETag: &quot;abc123xyz&quot;</pre><p><strong>Cached Response:</strong></p><ul><li>Response cached for <strong>10 seconds</strong></li><li>ETag is a hash value</li></ul><p><strong>Second Request (within 10 seconds):</strong></p><pre>GET /api/data HTTP/1.1<br>If-None-Match: &quot;abc123xyz&quot;<br>If-Modified-Since: Mon, 15 Jan 2025 10:00:00 GMT</pre><p><strong>Server evaluates:</strong></p><ol><li>Has ETag changed?</li><li>Is request after max-age (10 sec)?</li></ol><p><strong>If unchanged:</strong></p><pre>HTTP/1.1 304 Not Modified</pre><p><strong>If changed:</strong></p><pre>HTTP/1.1 200 OK<br>(new data)</pre><p><strong>Modern Solution:</strong> For production, use better caching like <strong>React Query</strong> (client-side caching) instead of relying solely on HTTP caching.</p><h3>Content Negotiation</h3><p>Client and server agree on a format to exchange data.</p><h3>Types</h3><h4>1. Media Type</h4><pre># Client<br>Accept: application/json</pre><pre># Server<br>Content-Type: application/json</pre><h4>2. Language</h4><pre># Client<br>Accept-Language: en-US</pre><pre># Server<br>Content-Language: en-US</pre><h4>3. Encoding</h4><pre># Client<br>Accept-Encoding: gzip, deflate, br</pre><pre># Server<br>Content-Encoding: gzip</pre><p><strong>Why Compression?</strong> Reduces request/response size. Browser decompresses automatically.</p><p><strong>Common Algorithms:</strong></p><ul><li>gzip - Good compression, widely supported</li><li>deflate - Similar to gzip</li><li>br (Brotli) - Better compression, modern browsers</li></ul><h3>Persistent Connections &amp; Keep-Alive</h3><p><strong>Early Days:</strong> Each request required a new connection (inefficient).</p><p><strong>HTTP 1.1+:</strong> Persistent connections via Connection: keep-alive</p><p><strong>Benefits:</strong></p><ul><li>Reuse same TCP connection</li><li>Reduces latency</li><li>Improves performance</li></ul><h3>Handling Large Files</h3><h3>1. Multipart Requests (Client → Server)</h3><p>Large files transferred in multiple parts.</p><pre>POST /upload HTTP/1.1<br>Content-Type: multipart/form-data; boundary=----WebKitFormBoundary</pre><pre>------WebKitFormBoundary<br>Content-Disposition: form-data; name=&quot;file&quot;; filename=&quot;image.jpg&quot;</pre><pre>(binary data)<br>------WebKitFormBoundary--</pre><p><strong>Key:</strong> boundary delimiter separates file parts.</p><h3>2. Streaming Responses (Server → Client)</h3><p>Server sends data in chunks.</p><pre>HTTP/1.1 200 OK<br>Content-Type: text/event-stream<br>Connection: keep-alive</pre><pre>(chunk 1)<br>(chunk 2)<br>(chunk 3)</pre><p>Connection stays open until complete.</p><h3>SSL/TLS &amp; HTTPS</h3><h3>SSL (Secure Sockets Layer)</h3><p>Encrypts data between client and browser (legacy).</p><h3>TLS (Transport Layer Security)</h3><p>Modern, more secure version of SSL.</p><ul><li><strong>TLS 1.3</strong> is the current recommended version</li><li>Uses certificates to establish secure connection</li></ul><h3>HTTPS</h3><p>HTTP + TLS = Secure communication</p><p><strong>How it works:</strong></p><ol><li>Client requests connection</li><li>Server sends SSL/TLS certificate</li><li>Client verifies certificate</li><li>Encrypted connection established</li><li>Data transmitted securely</li></ol><p><em>If you found this helpful, give it a clap 👏 and follow for Part 2!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252fc358cb45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VS Code Suddenly not Opening — This will work]]></title>
            <link>https://medium.com/@bireshkumar1964/vs-code-suddenly-not-opening-this-will-work-12c5a69d5351?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/12c5a69d5351</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 06:11:51 GMT</pubDate>
            <atom:updated>2025-12-15T06:17:49.811Z</atom:updated>
            <content:encoded><![CDATA[<h3>VS Code Suddenly Won’t Open — Quick Fix That Worked for Me</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHYu8jyNuETUyIbKrkIsYg.jpeg" /></figure><blockquote>Tired of VS Code refusing to open? Step-by-step fixes to check for a missing icudtl.dat, restore from Windows Security, add safe exclusions, and reinstall VS Code safely.</blockquote><p>I opened VS Code one day and it simply didn’t launch. Task Manager showed Antimalware Service Executable running — Windows Defender had flagged something. If your VS Code refuses to open and shows errors about icudtl.dat, this guide will get you back up in minutes.</p><h3>TL;DR</h3><p>If code in CMD prints an icudtl.dat error or VS Code won’t launch, check whether Defender quarantined icudtl.dat. Restore or reinstall VS Code, add Defender exclusions for your VS Code folder, and optionally turn off “Potentially unwanted app blocking”.</p><h3>What happened</h3><p>Many developer workflows (local web UIs, ngrok, Electron apps, ML/AI tools, proxies) look like suspicious activity to endpoint protection. Defender may quarantine a runtime file icudtl.dat from the VS Code installation causing it to fail to start.</p><h3>Step-by-step: quick recovery</h3><h3>1) Verify the problem from Command Prompt</h3><p>Open Command Prompt (Start → type cmd → Enter) and run:</p><pre>code</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Dc4_tCXY2vV2BXGDNTy8Q.png" /></figure><p>If you see an error mentioning icudtl.dat or a path-related error, continue.</p><h3>2) Check if the file exists</h3><p>Open CMD and run:</p><pre>dir &quot;%LOCALAPPDATA%\Programs\Microsoft VS Code\icudtl.dat&quot;</pre><p>If it says “File Not Found”, Defender likely quarantined it.</p><h3>3) Check Windows Security → Protection history</h3><p>Windows Security → Virus &amp; threat protection → Protection history<br> If you see icudtl.dat or Visual Studio Code entries, <strong>Restore</strong> or <strong>Allow</strong> the item from protection history.</p><h3>4) Add exclusions (do this first)</h3><p>Windows Security → Virus &amp; threat protection → Exclusions → Add or remove exclusions<br> Add the VS Code install folder:</p><pre>C:\Users\&lt;Your_User_Name&gt;\AppData\Local\Programs\Microsoft VS Code</pre><p>and any dev folders that Defender keeps flagging (be conservative — only add folders you trust).</p><blockquote><em>Security note: Exclusions reduce scanning for those paths. Only exclude folders you control.</em></blockquote><h3>5) Reinstall VS Code (one clean reinstall)</h3><ol><li>Uninstall VS Code (Control Panel → Programs → Uninstall).</li><li>Delete any leftover files in:</li></ol><pre>%LOCALAPPDATA%\Programs\Microsoft VS Code<br>%USERPROFILE%\.vscode</pre><ol><li>Download the latest installer from the official VS Code site and reinstall. Run the installer as Administrator if needed.</li></ol><p>After reinstall, icudtl.dat will be restored and the program should open.</p><h3>Optional: disable the Defender behavior that triggers this</h3><p>Windows Security → App &amp; browser control → Reputation-based protection → Turn off <strong>Potentially unwanted app blocking</strong>.</p><p>This reduces false positives for developer tools and local servers without turning off core antivirus protections.</p><h3>Advanced troubleshooting (if it still won’t open)</h3><ul><li>Run VS Code from terminal to see verbose logs:</li></ul><pre>code --verbose</pre><ul><li>Check Event Viewer for App errors (Windows Logs → Application).</li><li>Restore icudtl.dat from quarantine (Protection history) or copy from another machine’s VS Code installation.</li><li>Run sfc /scannow only if system files seem corrupted.</li></ul><h3>Why this hits AI/ML devs more</h3><p>You often run:</p><ul><li>local servers (gradio, streamlit),</li><li>proxies / ngrok,</li><li>Electron-based tools,<br> which can look like malware to heuristics-based scanners. Defender optimizes for office use, not developer workflows.</li></ul><h3>Closing / CTA</h3><p>After exclusions + reinstall, VS Code worked fine for me while running a Gradio local server. If you still face issues, drop the exact error logs or the output of code --verbose in the comments and I’ll try to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12c5a69d5351" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents from absolute scratch to complete explanation — Part 2]]></title>
            <link>https://medium.com/@bireshkumar1964/ai-agents-from-absolute-scratch-to-complete-explanation-part-2-9a3233075374?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a3233075374</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 15:58:49 GMT</pubDate>
            <atom:updated>2025-12-14T15:58:49.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI Agents from absolute scratch to complete explanation — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*iIyaRrSNA9jhisft.png" /><figcaption>Image taken from peterroelants.github.io</figcaption></figure><p>We are very close to the good stuff now and we will <strong>create our first real Agent</strong> today using the smolagents library.</p><p>Agents’ work is a continuous cycle of: <strong>thinking (Thought) → acting (Act) and observing (Observe)</strong>. To use an analogy from programming, the agent uses a while loop: the loop continues until the objective of the agent has been fulfilled.</p><p>For example : Lets say you asked about the weather in Pune from your AI Assistant. <br>Here’s how the cycle unfolds:</p><h3>Thought</h3><p>Internal Reasoning:</p><p>Upon receiving the query, the aagent first thinks :</p><p><em>“The user needs current weather information for Pune. I have access to a tool that fetches weather data. First, I need to call the weather API to get up-to-date details.”</em></p><h3>Action</h3><p>Tool Usage:</p><p>Now the agent prepares a JSON-formatted command that calls the weather API tool.</p><h3>Observation</h3><p>Feedback from the Environment:</p><p>After the tool call, the agent receives an observation. This might be the raw weather data from the API such as:</p><p><em>“Current weather in Pune: partly cloudy, 15°C, 60% humidity.”</em></p><h3>Updated thought</h3><p>Reflecting:</p><p>With the observation in hand, the agent updates its internal reasoning:</p><p><em>“Now that I have the weather data for Pune, I can compile an answer for the user.”</em></p><h3>Final Action</h3><p>The agent then generates a final response formatted as we told it to:</p><p>Thought: I have the weather data now. The current weather in Pune is partly cloudy with a temperature of 15°C and 60% humidity.”</p><p>Final answer : The current weather in Pune is partly cloudy with a temperature of 15°C and 60% humidity.</p><p>Now, Lets create our <strong>First Agent</strong>.</p><h3>Prerequisites for Building our First Agent</h3><p>Before building, first follow these steps:</p><ol><li>Go to Google Collab and click on the blue “New Notebook” button in the dialog box : <a href="https://colab.research.google.com/">https://colab.research.google.com/</a><br>Name it anything at the top.(It will have a .ipynb extension)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLWlY31dPs0FT_LkJj2xAA.png" /></figure><p>2. Create a new account on <a href="https://huggingface.co/">https://huggingface.co/</a> and log in.</p><p>3. Go to <a href="https://hf.co/settings/tokens,"><em>https://hf.co/settings/tokens,</em></a><em> </em>ensure that you select ‘Read’ as the token type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TmN2A6Kmgs1cbCgRTSAzXw.png" /></figure><p>Create a new token and call it “HF_TOKEN”. Copy this token and keep it somewhere safe.</p><p>4. Go to the secrets tab in the Google Collab and add a new secret and value of the HF_TOKEN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qoKkC19M4f47FCR8I_ATg.png" /></figure><p>5. Now restart the session to load the environment variable (Runtime -&gt; Restart session).</p><p>6. First lets install and update our hugging face hub :</p><pre>!pip install -U huggingface_hub</pre><p>7. Lets test and output the next token from the model.We use the chat method since is a convenient and reliable way to apply chat templates:</p><pre>import os<br>from huggingface_hub import InferenceClient<br>from google.colab import userdata<br><br>HF_TOKEN = userdata.get(&#39;HF_TOKEN&#39;)<br><br># Try one of these models instead:<br>client = InferenceClient(<br>    model=&quot;meta-llama/Llama-3.2-3B-Instruct&quot;,<br>    token=HF_TOKEN<br>)<br><br>output = client.chat.completions.create(<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;The capital of France is&quot;},<br>    ],<br>    stream=False,<br>    max_tokens=20,<br>)<br>print(output.choices[0].message.content)</pre><p>The output displayed is :</p><pre>Paris</pre><p>8. Now we will write a detailed system prompt :</p><pre># This system prompt is a bit more complex and actually contains the function description already appended.<br># Here we suppose that the textual description of the tools have already been appended<br>SYSTEM_PROMPT = &quot;&quot;&quot;Answer the following questions as best you can. You have access to the following tools:<br><br>get_weather: Get the current weather in a given location<br><br>The way you use the tools is by specifying a json blob.<br>Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).<br><br>The only values that should be in the &quot;action&quot; field are:<br>get_weather: Get the current weather in a given location, args: {{&quot;location&quot;: {{&quot;type&quot;: &quot;string&quot;}}}}<br>example use :<br>```<br>{{<br>  &quot;action&quot;: &quot;get_weather&quot;,<br>  &quot;action_input&quot;: {&quot;location&quot;: &quot;Pune&quot;}<br>}}<br><br>ALWAYS use the following format:<br><br>Question: the input question you must answer<br>Thought: you should always think about one action to take. Only one action at a time in this format:<br>Action:<br>```<br>$JSON_BLOB<br>```<br>Observation: the result of the action. This Observation is unique, complete, and the source of truth.<br>... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.)<br><br>You must always end your output with the following format:<br><br>Thought: I now know the final answer<br>Final Answer: the final answer to the original input question<br><br>Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer. &quot;&quot;&quot;<br></pre><p>9. We don’t have given our model access to any particular weather api etc so now if we want to print the output of weather — it will <strong>hallunciate</strong>.</p><p>10. Now we will create our get_weather() function and we will use open meteo free api for this. For this, you require no apis, no signups.</p><pre>import requests<br><br>def get_weather(location):<br>    geo_url = &quot;https://geocoding-api.open-meteo.com/v1/search&quot;<br>    geo_params = {<br>        &quot;name&quot;: location,<br>        &quot;count&quot;: 1,<br>        &quot;language&quot;: &quot;en&quot;,<br>        &quot;format&quot;: &quot;json&quot;<br>    }<br><br>    geo_res = requests.get(geo_url, params=geo_params).json()<br>    if &quot;results&quot; not in geo_res:<br>        return f&quot;Could not find location: {location}&quot;<br><br>    lat = geo_res[&quot;results&quot;][0][&quot;latitude&quot;]<br>    lon = geo_res[&quot;results&quot;][0][&quot;longitude&quot;]<br><br>    weather_url = &quot;https://api.open-meteo.com/v1/forecast&quot;<br>    weather_params = {<br>        &quot;latitude&quot;: lat,<br>        &quot;longitude&quot;: lon,<br>        &quot;current_weather&quot;: True<br>    }<br><br>    weather_res = requests.get(weather_url, params=weather_params).json()<br>    weather = weather_res[&quot;current_weather&quot;]<br><br>    temp = weather[&quot;temperature&quot;]<br>    wind = weather[&quot;windspeed&quot;]<br><br>    return f&quot;The weather in {location} is {temp}°C with wind speed {wind} km/h.\n&quot;<br><br>get_weather(&quot;Pune&quot;)</pre><p>11. Now we will write our messages variable :</p><pre>messages=[<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What&#39;s the weather in Pune?&quot;},<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: output.choices[0].message.content+&quot;Observation:\n&quot;+get_weather(&#39;London&#39;)},<br>]</pre><p>13. Now we will write our prompt and print the weather :</p><pre>output = client.chat.completions.create(<br>    messages=messages,<br>    stream=False,<br>    max_tokens=200,<br>)<br><br>print(output.choices[0].message.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRFW80OKI7U45d7Vp7HZnA.png" /></figure><p>Now we are ready to create our first agent using smolagents library in the next part.Follow and stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3233075374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents from absolute scratch to complete explanation — Part 1]]></title>
            <link>https://medium.com/@bireshkumar1964/ai-agents-from-absolute-scratch-to-complete-explanation-part-1-17f5dca55c9d?source=rss-12f5c0e98e39------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f5dca55c9d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Biresh Kumar Singh]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 14:50:19 GMT</pubDate>
            <atom:updated>2025-12-14T09:23:49.672Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI Agents from absolute scratch to complete explanation — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZqDK-cV_aFjKzVb6.png" /><figcaption>Image from bytebytego.com</figcaption></figure><p>I understand your frustation. You have always understood the basics but never been able to use these AI Agents in your projects. Don’t Worry — I got you. First I will quickly skim through the basics and teach you how to build one.</p><h3>What is an Agent ?</h3><p>An agent is an AI model(it is just a pre-trained computer program that returns outputs for specific inputs) that :<br>1. <strong>listens </strong>to the user request<br>2. <strong>thinks</strong>(selects particular tools) and <strong>plans</strong><br>3. then <strong>acts</strong> using tools</p><p>An Agent can perform any task we implement with the help of <strong>Tools.</strong></p><p>For example, if I write an Agent to act as my personal assistant (like Siri) on my computer, and I ask it to “send an email to my Manager asking to delay today’s meeting”, I can give it some code to send emails. This will be a new Tool the Agent can use whenever it needs to send an email.</p><h3>What type of AI Models do we use for Agents?</h3><p>The most common AI model found in Agents is an LLM (Large Language Model), which takes Text as an input and outputs Text as well.</p><p>Well known examples are GPT4 from OpenAI, LLama from Meta, Gemini from Google, etc.</p><h3>What is a Large Lanaguage Model (LLM)?</h3><p>LLM is a type of AI model that can understand and generate human language. Most LLMs nowadays are built on the Transformer architecture — a deep learning architecture based on the “Attention” algorithm, that has gained significant interest since the release of BERT from Google in 2018.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*FNQol0qlAFCxmQOLVQCSzA.png" /><figcaption>The original Transformer architecture looked like this, with an encoder on the left and a decoder on the right.</figcaption></figure><p>There are 3 types of transformers:</p><h4>1. Encoders(Understand Only)</h4><p>Encoders <strong>read</strong> and <strong>understand</strong> text. They don’t write or generate anything. They take your sentence → convert it into <strong>meaningful numeric representation</strong> (called <strong>embedding</strong>).</p><h4>2. Decoders (Generate Only)</h4><p>Decoders <strong>generate text</strong> word by word, like a story writer or chatbot.<br>They don’t focus on deep understanding — they mainly focus on <strong>what word comes next</strong>.</p><h4>3. Seq2Seq Models (Encoder + Decoder Together)</h4><p>These have <strong>two parts</strong>:</p><ol><li><strong>Encoder</strong> → reads and understands text</li><li><strong>Decoder</strong> → writes new text based on that understanding</li></ol><p>So it’s a full pipeline:<br> <strong>Input text → understood → transformed into new text</strong></p><blockquote>The underlying principle of an LLM is simple yet highly effective: its objective is to predict the next token, given a sequence of previous tokens.</blockquote><p>Each LLM has some<strong> special tokens </strong>specific to the model. The LLM uses these tokens to <strong>open and close the structured components</strong> of its generation. For example, to indicate the start or end of a sequence, message, or response.</p><p>Moreover, the input prompts that we pass to the model are also structured with special tokens. The most important of those is the <strong>End of sequence token (EOS).</strong></p><h4>Understanding next token prediction.</h4><p>LLMs are said to be autoregressive, meaning that the <strong>output from one pass becomes the input for the next one</strong>. This loop continues until the model predicts the next token to be the EOS token, at which point the model can stop.</p><p>In other words, an LLM will decode text until it reaches the EOS. But what happens during a single decoding loop?</p><h4>During Single Decoding Loop (Optional — maybe too much for some):</h4><ul><li>Once the input text is tokenized, the model computes a representation of the sequence that captures information about the meaning and the position of each token in the input sequence.</li><li>This representation goes into the model, which outputs scores that rank the likelihood of each token in its vocabulary as being the next one in the sequence.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*-kQ6uxqo8bAQ4IRImyK7Cg.png" /><figcaption>Image taken from Hugging Face AI Agents Course</figcaption></figure><p>Based on these scores, we have multiple strategies to select the tokens to complete the sentence.</p><ul><li>The easiest decoding strategy would be to always take the token with the maximum score.</li></ul><h4>Attention is all you need</h4><p>A key aspect of the Transformer architecture is Attention. When predicting the next word, not every word in a sentence is equally important; words like “France” and “capital” in the sentence <em>“The capital of France is …”</em> carry the most meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*oiJFHnzZvCImD3dnYEJCVA.png" /><figcaption>Image from Hugging Face AI Agents Course</figcaption></figure><h4>Prompting the LLM is important</h4><p>The input sequence you provide an LLM is called <em>a prompt</em>. Careful design of the prompt makes it easier to guide the generation of the LLM toward the desired output.</p><blockquote>You should only remember one most important thing that the LLM is the brain of the agent.</blockquote><h3>How LLMs structure their generations through chat templates?</h3><p>Whenever we use ChatGPT, the messages are concatenated and formatted into a prompt that the model can understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*G-T87PNrTO4e2npn4Kns2A.png" /><figcaption>We see here the difference between what we see in UI and the prompt fed to the model.</figcaption></figure><p>This is where chat templates come in. They act as the bridge between conversational messages (user and assistant turns) and the specific formatting requirements of your chosen LLM.</p><h3>Messages: The Underlying System of LLMs</h3><h3>System Messages</h3><p>System messages (also called System Prompts) define how the model should behave. They serve as persistent instructions, guiding every subsequent interaction.</p><p>For example:</p><pre>system_message = {<br>    &quot;role&quot;: &quot;system&quot;,<br>    &quot;content&quot;: &quot;You are a professional customer service agent. Always be polite, clear, and helpful.&quot;<br>}</pre><h3>Conversations: User and Assistant Messages</h3><p>A conversation consists of alternating messages between a Human (user) and an LLM (assistant).</p><p>Chat templates help maintain context by preserving conversation history, storing previous exchanges between the user and the assistant. This leads to more coherent multi-turn conversations.</p><p>For example:</p><pre>conversation = [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;I need help with my order&quot;},<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;I&#39;d be happy to help. Could you provide your order number?&quot;},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;It&#39;s ORDER-123&quot;},<br>]</pre><h3>Base Models vs. Instruct Models</h3><p>Another point we need to understand is the difference between a Base Model vs. an Instruct Model:</p><ul><li><em>A Base Model</em> is trained on raw text data to predict the next token.</li><li>An <em>Instruct Model</em> is fine-tuned specifically to follow instructions and engage in conversations.</li></ul><p>To make a Base Model behave like an instruct model, we need to format our prompts in a consistent way that the model can understand. This is where chat templates come in.</p><p><em>ChatML</em> is one such template format that structures conversations with clear role indicators (system, user, assistant).</p><p>Below is a simplified version of the SmolLM2-135M-Instruct chat template:</p><pre>{% for message in messages %}<br>{% if loop.first and messages[0][&#39;role&#39;] != &#39;system&#39; %}<br>&lt;|im_start|&gt;system<br>You are a helpful AI assistant named SmolLM, trained by Hugging Face<br>&lt;|im_end|&gt;<br>{% endif %}<br>&lt;|im_start|&gt;{{ message[&#39;role&#39;] }}<br>{{ message[&#39;content&#39;] }}&lt;|im_end|&gt;<br>{% endfor %}</pre><p>As you can see, a chat_template describes how the list of messages will be formatted.The transformers library will take care of chat templates for you as part of the tokenization process.</p><h3>What are AI Tools?</h3><p>A Tool is a function given to the LLM. This function should fulfill a clear objective.</p><p>Some commonly used tools in AI agents are Web Search, Image Generation, Retrieval etc.</p><p><strong>VVIP Note —</strong></p><blockquote>Furthermore, LLMs predict the completion of a prompt based on their training data, which means that their internal knowledge only includes events prior to their training. Therefore, if your agent needs up-to-date data you must provide it through some tool.</blockquote><blockquote>For instance, if you ask an LLM directly (without a search tool) for today’s weather, the LLM will potentially hallucinate random weather.</blockquote><p>A Tool should contain:</p><ul><li>A textual description of what the function does.</li><li>A <em>Callable</em> (something to perform an action).</li><li><em>Arguments</em> with typings.</li></ul><h3>How do we give tools to an LLM?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*M2K3jKUw5lWTIOe23SBuLg.png" /></figure><p>We essentially use the system prompt to provide textual descriptions of available tools to the model.For this to work, we have to be very precise and accurate about:</p><ol><li>What the tool does</li><li>What exact inputs it expects</li></ol><p>This is the reason why tool descriptions are usually provided using expressive but precise structures, such as computer languages or JSON. It’s not <em>necessary</em> to do it like that, any precise and coherent format would work.</p><p>Also, we want to give textual description about the tool to LLMs (For eg -)-</p><pre>Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int</pre><blockquote>Reminder: This textual description is what we want the LLM to know about the tool.</blockquote><p>But lets see how we can automatically give this textual description to LLMs-<br>We create a generic Tool class that we can reuse whenever we need to use a tool.</p><blockquote>Disclaimer: This example implementation is fictional but closely resembles real implementations in most libraries.I know this is a lot of code — so you don’t need to necessarily understand this.</blockquote><pre>from typing import Callable<br>class Tool:<br>    &quot;&quot;&quot;<br>    A class representing a reusable piece of code (Tool).<br>    Attributes:<br>        name (str): Name of the tool.<br>        description (str): A textual description of what the tool does.<br>        func (callable): The function this tool wraps.<br>        arguments (list): A list of arguments.<br>        outputs (str or list): The return type(s) of the wrapped function.<br>    &quot;&quot;&quot;<br>    def __init__(self,<br>                 name: str,<br>                 description: str,<br>                 func: Callable,<br>                 arguments: list,<br>                 outputs: str):<br>        self.name = name<br>        self.description = description<br>        self.func = func<br>        self.arguments = arguments<br>        self.outputs = outputs<br>    def to_string(self) -&gt; str:<br>        &quot;&quot;&quot;<br>        Return a string representation of the tool,<br>        including its name, description, arguments, and outputs.<br>        &quot;&quot;&quot;<br>        args_str = &quot;, &quot;.join([<br>            f&quot;{arg_name}: {arg_type}&quot; for arg_name, arg_type in self.arguments<br>        ])<br>        return (<br>            f&quot;Tool Name: {self.name},&quot;<br>            f&quot; Description: {self.description},&quot;<br>            f&quot; Arguments: {args_str},&quot;<br>            f&quot; Outputs: {self.outputs}&quot;<br>        )<br>    def __call__(self, *args, **kwargs):<br>        &quot;&quot;&quot;<br>        Invoke the underlying function (callable) with provided arguments.<br>        &quot;&quot;&quot;<br>        return self.func(*args, **kwargs)</pre><p>It may seem complicated, but if we go slowly through it we can see what it does. We define a Tool class that includes:</p><ul><li>name (<em>str</em>): The name of the tool.</li><li>description (<em>str</em>): A brief description of what the tool does.</li><li>function (<em>callable</em>): The function the tool executes.</li><li>arguments (<em>list</em>): The expected input parameters.</li><li>outputs (<em>str</em> or <em>list</em>): The expected outputs of the tool.</li><li>__call__(): Calls the function when the tool instance is invoked.</li><li>to_string(): Converts the tool’s attributes into a textual representation.</li></ul><p>We could create a Tool with this class using code like the following:</p><pre>calculator_tool = Tool(<br>    &quot;calculator&quot;,                   # name<br>    &quot;Multiply two integers.&quot;,       # description<br>    calculator,                     # function to call<br>    [(&quot;a&quot;, &quot;int&quot;), (&quot;b&quot;, &quot;int&quot;)],   # inputs (names and types)<br>    &quot;int&quot;,                          # output<br>)</pre><p>But we can also use Python’s inspect module to retrieve all the information for us! This is what the @tool decorator does.</p><pre>import inspect<br>def tool(func):<br>    &quot;&quot;&quot;<br>    A decorator that creates a Tool instance from the given function.<br>    &quot;&quot;&quot;<br>    # Get the function signature<br>    signature = inspect.signature(func)<br>    # Extract (param_name, param_annotation) pairs for inputs<br>    arguments = []<br>    for param in signature.parameters.values():<br>        annotation_name = (<br>            param.annotation.__name__<br>            if hasattr(param.annotation, &#39;__name__&#39;)<br>            else str(param.annotation)<br>        )<br>        arguments.append((param.name, annotation_name))<br>    # Determine the return annotation<br>    return_annotation = signature.return_annotation<br>    if return_annotation is inspect._empty:<br>        outputs = &quot;No return annotation&quot;<br>    else:<br>        outputs = (<br>            return_annotation.__name__<br>            if hasattr(return_annotation, &#39;__name__&#39;)<br>            else str(return_annotation)<br>        )<br>    # Use the function&#39;s docstring as the description (default if None)<br>    description = func.__doc__ or &quot;No description provided.&quot;<br>    # The function name becomes the Tool name<br>    name = func.__name__<br>    # Return a new Tool instance<br>    return Tool(<br>        name=name,<br>        description=description,<br>        func=func,<br>        arguments=arguments,<br>        outputs=outputs<br>    )<br><br>Just to reiterate, with this decorator in place we can implement our tool like this:<br>Copied<br>def calculator(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Multiply two integers.&quot;&quot;&quot;<br>    return a * b<br>print(calculator.to_string())</pre><p>And we can use the Tool’s to_string method to automatically retrieve a text suitable to be used as a tool description for an LLM:</p><pre>Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int</pre><p>The description is injected in the system prompt. Taking the example with which we started this section, here is how it would look like after replacing the tools_description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*dZSVQya3u4mZrytfpS1EcA.png" /></figure><h3>Model Context Protocol (MCP): a unified tool interface</h3><p>Model Context Protocol (MCP) is an open protocol that standardizes how applications provide tools to LLMs. MCP provides:</p><ul><li>A growing list of pre-built integrations that your LLM can directly plug into</li><li>The flexibility to switch between LLM providers and vendors</li><li>Best practices for securing your data within your infrastructure</li></ul><p>This means that any framework implementing MCP can leverage tools defined within the protocol, eliminating the need to reimplement the same tool interface for each framework.</p><p>If you like it, Give me a follow. So, you will be notified for Part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f5dca55c9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>