<?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 Siddharth Parmar (Sid) on Medium]]></title>
        <description><![CDATA[Stories by Siddharth Parmar (Sid) on Medium]]></description>
        <link>https://medium.com/@siddharthparmar7?source=rss-366e770aced0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c_ixn8fX_CfCKvRxzm3W3Q.jpeg</url>
            <title>Stories by Siddharth Parmar (Sid) on Medium</title>
            <link>https://medium.com/@siddharthparmar7?source=rss-366e770aced0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siddharthparmar7/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[How LLM Inference Got 10x Cheaper]]></title>
            <link>https://medium.com/@siddharthparmar7/how-llm-inference-got-10x-cheaper-467d1dfd4675?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/467d1dfd4675</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[production-ml]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 13:56:00 GMT</pubDate>
            <atom:updated>2026-03-04T13:56:00.653Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How the field slashed LLM inference costs through attention redesigns, IO-aware computation, KV cache paging, and speculative decoding, and what comes next.</blockquote><p>In late 2022, running a state-of-the-art language model cost around $20 per million tokens. By 2025, the same capability costs roughly $0.40. Fifty times cheaper in three years. If you’ve used AI APIs like OpenAI or Gemini recently and been surprised by the price, this is the story behind that number, and it wasn’t driven by faster hardware alone.</p><p>To understand why, it helps to separate two things that often get conflated: training and inference. Training is the one-time process of building a model from data, expensive, done once, absorbed as a capital cost. <strong>Inference</strong> is what happens every time a user sends a message: the model generates a response token by token. It happens billions of times a day across every AI product, which means inference cost is the tax on every interaction. Making inference cheaper is what determines whether AI can be in every app or only the premium-priced ones.</p><p>Here’s a concrete example of why inference is expensive. Take the sentence “The cat sat on the mat.” That’s 6 tokens. At inference time, when the model generates the next token, it needs to compute attention between every token and every other token. That’s 6 x 6 = 36 comparisons. Seems fine. Now scale that to a 128K-token document: 128,000 x 128,000 = over 16 billion comparisons per layer. That’s O(n²) scaling, and it’s the core reason inference costs explode with longer contexts.</p><p>The improvements that drove costs down came in six distinct layers, each solving a different piece of the problem: the attention mechanism at the model’s core, the GPU kernel that computes it, the memory system that stores the working state, the generation algorithm that produces tokens, the position encoding that enables long contexts, and the architecture underneath it all. No single technique explains the full reduction. Stacked together, they do.</p><p>Notably, many of these improvements are not entirely new inventions. They are novel <em>applications</em> of well-established algorithmic ideas: PagedAttention borrows directly from OS virtual memory (and was published at SOSP, an operating systems conference, not an ML venue). FlashAttention applies IO-aware tiling, a technique standard in high-performance computing for decades, to the specific pattern of fused softmax-matmul attention. Speculative decoding echoes speculative execution in CPUs: predict ahead, verify, roll back if wrong. The novelty lies in recognizing which classical ideas map onto which LLM bottlenecks, and engineering them to work at GPU scale.</p><p>If you want the foundation, how transformers and attention work from first principles, <a href="https://sidparmar.ca/blog/transformers-simple-yet-wildly-versatile">Transformers: Simple Yet Wildly Versatile</a> covers that. This post picks up where that one leaves off, at the point where the engineering problem shifts from “make it work” to “make it affordable at scale.”</p><h3>The Attention Tax: O(n²) in Two Places</h3><p>The first cost problem starts inside the attention mechanism itself. Standard <strong>Multi-Head Attention</strong> (MHA) has two costs that both scale quadratically with sequence length. Compute is O(n²) because every token attends to every other token. Remember our 6-token sentence, “The cat sat on the mat.” With MHA, attention computes all 36 token pairs per layer. That’s manageable. But at 128K tokens, that’s 128,000 x 128,000 = roughly 16 billion comparisons per layer, and a large model might have 80+ layers. Memory scales similarly because you store a separate key-value pair for every head at every layer.</p><p>The first generation of fixes targeted the KV cache specifically, by reducing how many distinct K/V pairs you actually need to store.</p><p><strong>Multi-Query Attention (MQA)</strong> (<a href="https://arxiv.org/abs/1911.02150">Shazeer, 2019</a>) went furthest: all query heads share a single K/V pair. Cache size drops dramatically, but quality degrades, especially on tasks requiring precise, head-specific retrieval. MQA was widely adopted early on, appearing in models like Falcon and early PaLM, but it was quickly superseded because the quality tradeoff was too steep for most use cases.</p><p><strong>Grouped Query Attention (GQA)</strong> (<a href="https://arxiv.org/abs/2305.13245">Ainslie et al., 2023</a>) landed as the practical middle ground. GQA divides the query heads into G groups. Each group shares a single set of key-value vectors instead of having its own. Back to our sentence, “The cat sat on the mat.” With MHA and 32 heads, the model stores 32 separate key-value pairs per layer, one per head. GQA with 8 groups stores just 8, with 4 query heads sharing each KV pair. The attention math is identical; only the storage changes. That’s a 4x cache reduction with near-identical quality. GQA with G=1 is MQA; with G equal to the head count, it’s full MHA. Every major production model converged on GQA: Meta first adopted it for Llama 2 (July 2023), kept it in Llama 3, and Mistral 7B, Gemma 2/3, Qwen3, and DeepSeek R1 all ship with it.</p><p><strong>Multi-Head Latent Attention (MLA)</strong> is DeepSeek’s contribution, introduced in DeepSeek-V2 and carried into V3. Instead of reducing the number of K/V pairs, MLA compresses the K/V tensors into a low-dimensional latent vector using a down-projection matrix, then recovers the full K/V at query time via up-projection. Only the tiny latent vector is stored in the cache. The results are striking: <strong>93.3% reduction in KV cache size</strong> compared to their previous 67B dense model, with benchmark accuracy that <em>exceeds</em> standard MHA, not a tradeoff, but a strict improvement.</p><p>To make the memory savings concrete, let’s return to our 6-token sentence. With MHA using 32 heads, the model stores 32 separate key-value pairs per layer. MQA collapses that to just 1. GQA with 8 groups stores 8. MLA stores a single compressed latent vector that’s even smaller than MQA’s single pair, because the compression captures the essential information in fewer dimensions. The trend is clear: each generation finds ways to preserve attention quality while storing dramatically less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0sjRhiXN7rM6nioRRL1xA.png" /><figcaption>Query heads vs KV Storage per layer</figcaption></figure><h3>Flash Attention: The Enemy Is IO, Not Compute</h3><p>Even with GQA reducing cache size, computing attention on a GPU is I/O bound, not compute bound. To understand why, you need to know about two types of memory on a GPU. <strong>HBM</strong> (High Bandwidth Memory) is the large but slower off-chip memory, think of it like your computer’s hard drive. It can hold a lot, but accessing it takes time. <strong>SRAM</strong> (Static Random-Access Memory) is the tiny but very fast on-chip memory, think of it like your CPU’s L1 cache. It’s blazing fast but extremely limited in size. When attention computes the full N x N matrix, it doesn’t fit in SRAM, so the GPU has to continuously read and write to HBM. Most of the available <strong>TFLOPS</strong> (Tera Floating Point Operations Per Second, the measure of a GPU’s raw compute power) go to waste waiting on memory transfers.</p><p><strong>FlashAttention</strong> (<a href="https://arxiv.org/abs/2205.14135">Tri Dao, 2022</a>) reframed this as an IO problem and solved it by tiling. Instead of materializing the full attention matrix in HBM, it breaks the computation into SRAM-sized blocks and fuses the softmax and matmul steps so they happen entirely in fast on-chip memory. The algorithmic complexity is still O(n²), the math is identical to standard attention. Only the memory access pattern changes. The result: 2–4x speedup with no accuracy loss. FlashAttention proved the bottleneck was never the math, it was where the data was read from and written to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky68NplBW-d9TOV-lavg5g.png" /><figcaption>Naive attention vs FlashAttention: IO memory hierarchy comparison</figcaption></figure><h3>KV Cache: The Bottleneck That Keeps Growing</h3><p>GQA and MLA reduce what you need to cache per request. PagedAttention solves a separate, equally painful problem: <em>how that cache is allocated across requests</em>.</p><p>Before <strong>PagedAttention</strong> (Berkeley, 2023, the engine inside vLLM), KV cache memory was reserved contiguously at the maximum sequence length per request. Without PagedAttention, serving 1,000 concurrent requests each with a 128K context reserve would lock up 128,000 memory slots per request, even if most of those slots go unused. A request using 10K tokens out of a reserved 128K window still locked all 128K of memory. The result: <strong>60–80% of KV cache memory wasted</strong> across typical production workloads.</p><p>PagedAttention, borrowed directly from operating system virtual memory, breaks the cache into small fixed-size blocks that can be stored non-contiguously across GPU memory. Different requests sharing the same system prompt can reuse cached blocks. The practical outcome: <strong>under 4% memory waste</strong>, <strong>2–4x throughput improvement</strong> over naive implementations, and up to 24x compared to naive baselines like HuggingFace Transformers on LLaMA-13B (3.5x over production-grade serving systems like TGI).</p><p><strong>Sliding Window Attention</strong> takes a different approach to bounding cache size: instead of attending to all past tokens, each layer attends to a fixed window (e.g., 4096 tokens). Think of reading a long essay. Sliding window attention means the model can only directly reference the last N tokens, roughly like only being able to look back at the last few pages while reading. Context from earlier in the document still influences the model through earlier layers, but the direct connection weakens over distance. As the window slides forward, information from two pages ago becomes increasingly indirect, captured only through the compressed representations passed between layers rather than through direct token-to-token attention. Mistral 7B shipped with this in production. It’s a practical ceiling on how large the KV cache can grow, which matters in memory-constrained serving environments.</p><h3>Mixture of Experts: Only Activate What You Need</h3><p>All the techniques above optimize how attention and memory are handled. <strong>Mixture of Experts</strong> (MoE) takes a fundamentally different angle: instead of making every parameter cheaper to run, just don’t run most of them.</p><p>MoE models split the model’s feedforward layers into many “expert” sub-networks. For each token, a learned routing layer selects only a small subset of active experts out of potentially dozens or hundreds. The model has many total parameters, but only uses a fraction of them per token, keeping compute roughly constant even as total parameter count scales up.</p><p>The numbers make this concrete. DeepSeek-V3 uses 256 experts with 8 active per token. Mixtral 8x7B uses 8 experts with 2 active. A MoE model like Mixtral 8x7B has 46B total parameters but costs about the same to run as a 13B dense model per token, because only roughly 13B parameters are active at any time. You get the knowledge capacity of a much larger model at the inference cost of a much smaller one.</p><p>MoE helps both sides of the cost equation. During training, fewer FLOPs per token means you can train larger models on the same compute budget. During inference, fewer active parameters means faster forward passes and lower memory bandwidth requirements. This is why MoE has become a default architecture choice for frontier models: it’s one of the few techniques that improves both training efficiency and serving cost simultaneously.</p><h3>Speculative Decoding: Parallelize the Verification</h3><p>The previous layers addressed memory, how much you’re caching and how efficiently it’s organized. But there’s a separate bottleneck in how tokens are generated. Autoregressive generation is inherently serial: each token requires a full forward pass through the model. Speculative decoding breaks this constraint.</p><p>Think of it like a junior assistant and a senior expert reviewing a document together. The junior assistant (a small, fast model) drafts several likely next words in sequence. The expert (the large LLM) then reads all of them at once and marks which ones they’d approve. Since verification is parallel, the expert can check all N candidates in one pass, you get the output of multiple expert decisions at roughly the cost of one. The catch: the junior assistant has to be good enough that the expert approves most of the suggestions.</p><p>That’s the core mechanism. A small, fast “draft” model generates N tokens speculatively in one shot. The large target model then verifies all N tokens in a single parallel forward pass, because checking whether the model <em>would have</em> generated each token is batchable in a way that generation isn’t. If k tokens are accepted, you’ve produced k tokens at the cost of roughly one large-model forward pass.</p><p>Acceptance rate drives everything. For predictable outputs, like code, structured data, and instruction-following, acceptance is high and speedups are large. For open-ended creative generation, acceptance drops and the gains shrink.</p><p>Recent work like <strong>EAGLE-3</strong> (<a href="https://arxiv.org/html/2503.01840v1">NeurIPS 2025</a>) shows how far speculative decoding can go when the draft model is trained for direct token prediction rather than feature matching. Reported results are <strong>~3–6.5x lower-latency generation</strong> vs vanilla autoregressive decoding and <strong>~1.4x</strong> over EAGLE-2. In practice, all speculative decoding methods see diminishing returns at high batch sizes, where the target model becomes compute-bound rather than memory-bound, so this is primarily a <strong>low-latency</strong> optimization, not a high-throughput one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0i6irSQTW0WsDTlpdqDqtA.png" /><figcaption>Speculative decoding pipeline: standard autoregressive vs draft-then-verify</figcaption></figure><h3>RoPE: How Context Windows Got So Big</h3><p>All of the above optimizes serving long contexts. But how did models get those long contexts in the first place? The answer is largely <strong>Rotary Position Embedding</strong> (RoPE) (<a href="https://arxiv.org/abs/2104.09864">Su et al., 2021</a>).</p><p>Original transformers used fixed sinusoidal absolute position embeddings, baking the position into the token representation directly. The problem: those embeddings are fixed at training time and don’t generalize beyond the training sequence length. A model trained on 8K tokens has no useful positional signal for token 9,000.</p><p>RoPE encodes position by rotating the vectors used in attention by an amount that depends on where each token sits in the sequence. The key insight: when computing attention between two tokens, only the difference in their rotations matters, which encodes relative distance, not absolute position. A model trained on sequences up to 8K tokens learns that “token A is 500 positions before token B.” That relationship holds at 128K tokens too.</p><p>The practical payoff is length generalization. Because RoPE captures relative distance, you can extend a model trained on 8K tokens to 128K, or even 1M, through techniques like <strong>YaRN</strong> (which adjusts the rotational frequencies at inference time) and <strong>NTK-aware scaling</strong> (which shifts the embedding base to avoid frequency aliasing at long range). This is how Llama 3.1’s 128K context works: the architecture is RoPE, and the extension is YaRN applied at inference time.</p><p>From a serving perspective, RoPE matters because it’s the reason the KV cache scaling problem keeps getting harder. Every 2x increase in context length doubles the cache requirements, and context windows have grown from 4K to 1M in under three years.</p><h3>Closing Thoughts</h3><p>The production stack today is a composition of several of these techniques, not a choice between them. GQA in the architecture, FlashAttention-3 if you’re on H100, PagedAttention in the serving layer, MoE for parameter efficiency, RoPE + YaRN for context extension, speculative decoding for latency-sensitive workloads. These compose, and each contributes its layer of efficiency independently. I covered the quantization side of this equation in <a href="https://sidparmar.ca/blog/making-llms-efficient-in-production">Making LLMs Efficient in Production</a>; add quantization on top and you have the full production picture.</p><p>Several of these techniques are not inference-only either. FlashAttention is used in training, where it reduces memory and speeds up the forward pass. GQA reduces training memory. MoE reduces training FLOPs per token. The efficiency gains compound in both directions, making models cheaper to build and cheaper to run.</p><p>The rate of improvement has been faster than most predicted, and the techniques driving it have mostly been algorithmic, not hardware-driven. That suggests the ceiling isn’t hardware. It’s how many more classical ideas we haven’t yet tried at scale.</p><p>All of the above still takes the transformer as a given and optimizes around it. There’s a more radical set of questions worth exploring: what if you replace attention itself? State space models, hybrid architectures, and research like Log-Linear Attention are pushing in exactly that direction. That’s what I’ll cover next.</p><p><em>Sources: </em><a href="https://arxiv.org/abs/1911.02150"><em>MQA paper</em></a><em> (Shazeer, 2019), </em><a href="https://arxiv.org/abs/2305.13245"><em>GQA paper</em></a><em> (Ainslie et al., 2023), </em><a href="https://arxiv.org/abs/2205.14135"><em>FlashAttention paper</em></a><em> (Tri Dao, 2022), </em><a href="https://arxiv.org/abs/2309.06180"><em>PagedAttention / vLLM</em></a><em>, </em><a href="https://arxiv.org/html/2412.19437v1"><em>DeepSeek-V2 MLA</em></a><em>, </em><a href="https://arxiv.org/html/2503.01840v1"><em>EAGLE-3</em></a><em> (NeurIPS 2025), </em><a href="https://arxiv.org/abs/2104.09864"><em>RoPE paper</em></a><em> (Su et al., 2021).</em></p><p><em>Further reading: AI But Simple </em><a href="https://www.aibutsimple.com/"><em>Issue #85</em></a><em> (MHA/GQA/KV cache visuals) and </em><a href="https://www.aibutsimple.com/"><em>Issue #86</em></a><em> (RoPE deep-dive) for thorough illustrated breakdowns of these mechanisms.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467d1dfd4675" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents, MCP Tools, and Skills: Toward Smarter Workflows]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@siddharthparmar7/ai-agents-mcp-tools-and-skills-toward-smarter-workflows-d2078b8accae?source=rss-366e770aced0------2"><img src="https://cdn-images-1.medium.com/max/1200/1*fqMOKopQECPaL-gM1TyM4w.png" width="1200"></a></p><p class="medium-feed-snippet">Why naive MCP usage breaks at scale, how code execution fixes context bloat, and how skills turn agent workflows into reusable building&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@siddharthparmar7/ai-agents-mcp-tools-and-skills-toward-smarter-workflows-d2078b8accae?source=rss-366e770aced0------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@siddharthparmar7/ai-agents-mcp-tools-and-skills-toward-smarter-workflows-d2078b8accae?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2078b8accae</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai-agent-tools]]></category>
            <category><![CDATA[agent-skills]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 15:11:01 GMT</pubDate>
            <atom:updated>2026-02-11T15:11:01.129Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Making LLMs Efficient in Production]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@siddharthparmar7/making-llms-efficient-in-production-350fe3851f07?source=rss-366e770aced0------2"><img src="https://cdn-images-1.medium.com/max/826/1*kvQVGNNpPlKnMcIcZWH8pg.png" width="826"></a></p><p class="medium-feed-snippet">A practical journey to deploy faster, cheaper LLM/transformer models using distillation, quantization, and ONNX Runtime&#x200A;&#x2014;&#x200A;no PhD required.</p><p class="medium-feed-link"><a href="https://medium.com/@siddharthparmar7/making-llms-efficient-in-production-350fe3851f07?source=rss-366e770aced0------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@siddharthparmar7/making-llms-efficient-in-production-350fe3851f07?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/350fe3851f07</guid>
            <category><![CDATA[model-distillation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[distillation]]></category>
            <category><![CDATA[quantization]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 13:01:51 GMT</pubDate>
            <atom:updated>2025-10-23T13:01:51.135Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Perfect Prompts to Perfect Ingredients]]></title>
            <link>https://medium.com/@siddharthparmar7/from-perfect-prompts-to-perfect-ingredients-b80489a47e84?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b80489a47e84</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[context-engineering]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 14:01:05 GMT</pubDate>
            <atom:updated>2025-10-16T14:01:05.061Z</atom:updated>
            <content:encoded><![CDATA[<p>How Anyone Can Guide AI Without Being a Techie.</p><p>A few weeks ago, I wrote about how my own engineering workflow shifted from prompt phrasing to context-first systems: <a href="https://sidparmar.ca/blog/the-days-of-prompt-engineering-are-over">https://sidparmar.ca/blog/the-days-of-prompt-engineering-are-over</a>. This follow-up is for non-technical readers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhY_DEVpVi3O2b-Qc8gl4A.png" /><figcaption>The shift: From Prompt engineering to Context engineering</figcaption></figure><p><strong>Intro:</strong> Imagine you’re trying to get an AI tool to help you at work or school. In the old days, you had to find just the right way to ask so it wouldn’t get confused. It felt like playing 20 Questions with a robot. A little frustrating, right?</p><p><strong>The Old Way: Prompt Engineering</strong> We used to rely on “prompt engineering.” You had to phrase every request in a super-specific way. If you changed one word, the answer might change a lot. It’s like giving someone step-by-step instructions for making coffee every single time, instead of just saying, “Can you make a cup of coffee?”</p><p>We also had to add <em>guardrails</em> into every prompt — telling the AI exactly what <strong>not</strong> to do (“don’t make it sound robotic,” “avoid long paragraphs,” “don’t mention prices”) and what to do instead (“keep it friendly,” “use short bullets,” “make it sound human”). The early models needed constant reminders because they didn’t truly understand tone, limits, or nuance. Every prompt felt like micromanagement — you had to steer it word by word.</p><p><strong>The New Way: Context Engineering</strong> Now the better approach is “context engineering.” Instead of hunting for magic words, you give the AI the <strong>right background</strong> up front — like a short FAQ, a one-pager, or a screenshot. Think of it like training a new teammate with a quick starter pack: once they have the essentials, they can handle more on their own.</p><p><a href="https://sidparmar.ca/blog/from-perfect-prompts-to-perfect-ingredients">Read the full article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b80489a47e84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers: Simple Yet Wildly Versatile]]></title>
            <link>https://medium.com/@siddharthparmar7/transformers-simple-yet-wildly-versatile-898acb0888ce?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/898acb0888ce</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 21:47:41 GMT</pubDate>
            <atom:updated>2025-10-08T21:47:41.375Z</atom:updated>
            <content:encoded><![CDATA[<p>How a simple attention-only architecture scaled from translation to language, vision, code, and diffusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuaDwwd0f7uqfs3_GDBw8Q.png" /><figcaption>Evolution of the Transformer</figcaption></figure><p>When the Transformer arrived in 2017, it was built for one thing: sequence-to-sequence translation. A clean, attention-only neural architecture that skipped recurrence and convolutions, yet outperformed state-of-the-art machine translation. The original paper, <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a>, turned out to be the gateway to much more than translation.</p><p>Fast forward to today, and that same blueprint is everywhere. It writes essays, fixes code, understands images, and even conjures photo-realistic media — images, audio, video — from pure noise. The leap wasn’t about tearing up the blueprint and starting over. It was about <strong>small architectural tweaks, combined with clever retraining on new data</strong>. Each reinterpretation of what counts as a “token” stretched the Transformer into a new world.</p><h3><a href="https://sidparmar.ca/blog/transformers-simple-yet-wildly-versatile#language-first-next-token-prediction">Language First: Next-Token Prediction</a></h3><p>At its core, a Transformer is a probabilistic machine: given a sequence, it predicts what comes next. “Deep learning is…” → “transforming”, “changing”, “everywhere.”</p><p>The breakthrough was <strong>self-attention</strong>, letting each word weigh every other word. Unlike RNNs, which only remembered the recent past, Transformers could see the whole sentence at once.</p><p>From this base came influential variants:</p><ul><li><strong>BERT (2018)</strong> for masked-language pretraining, enabling stronger understanding.</li><li><strong>RoBERTa (2019)</strong> for better scaling and training.</li><li><strong>T5 (2019)</strong> reframing every NLP task as text-to-text.</li></ul><p>These tweaks turned the Transformer from a translation engine into the foundation for today’s language models.</p><p><a href="https://sidparmar.ca/blog/transformers-simple-yet-wildly-versatile">Read the full article</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898acb0888ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Days of Prompt Engineering Are Over]]></title>
            <link>https://medium.com/@siddharthparmar7/the-days-of-prompt-engineering-are-over-50b6b129596e?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/50b6b129596e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 16:35:57 GMT</pubDate>
            <atom:updated>2025-09-29T16:35:57.279Z</atom:updated>
            <content:encoded><![CDATA[<p><em>My day-to-day shifted from prompt phrasing to context-first workflows — feeding the model code, docs, and tickets to drive reliable results.</em></p><p>When large language models first arrived, <strong>prompt engineering</strong> became the new craft. If you wanted a model to reason step by step, you told it explicitly. If you wanted structured output, you begged in natural language. Everything depended on phrasing: <em>“Let’s think step by step.”</em> <em>“Return only JSON.”</em> <em>“Answer in exactly three bullets.”</em></p><p>It worked — but it was brittle. A single word change could break the output. The model wasn’t really following rules; it was pattern-matching against instructions.</p><p>As models matured, their capabilities expanded. Context windows grew from a few thousand tokens to <strong>hundreds of thousands — up to around a million, depending on the model</strong>. Tool use and structured outputs became native. With that, a subtle but profound shift began for me: I no longer tell the model <em>how</em> to perform a task — I show it <em>what to work with</em> and give it clear rails.</p><p>That’s context engineering.</p><h3><a href="https://sidparmar.ca/blog/the-days-of-prompt-engineering-are-over#why-the-shift-happened">Why the Shift Happened</a></h3><p>The journey from prompt engineering to context engineering is really a story of <strong>model evolution</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHoiyRwKHHudENc6u67M7g.png" /><figcaption>Model evolution -&gt; workflow evolution with context engineering</figcaption></figure><p>As models gained longer context, tool use, and schema-constrained outputs, the bottleneck stopped being clever phrasing. It became <strong>curating the right context</strong> — the smallest set of files, artifacts, and constraints that makes the task obvious to the model.</p><h3><a href="https://sidparmar.ca/blog/the-days-of-prompt-engineering-are-over#what-changed-in-my-daily-flow">What Changed in My Daily Flow</a></h3><p>I default to modern, long-context, tool-using models (often in Cursor) because they balance fast edit — run loops with reliability on multi-file refactors. They also tolerate larger, messier inputs without derailing, which means I can feed real code instead of toy snippets.</p><p><a href="https://sidparmar.ca/blog/the-days-of-prompt-engineering-are-over">Read the full story here for free</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50b6b129596e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Unified Orchestrator for Agentic Flow with A2A + MCP]]></title>
            <link>https://medium.com/@siddharthparmar7/building-a-unified-orchestrator-for-agentic-flow-with-a2a-mcp-acb946bd3b16?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb946bd3b16</guid>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai-agnets]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[a2a-protocol]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 16:31:57 GMT</pubDate>
            <atom:updated>2025-09-29T16:31:57.951Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Architecture notes on bridging A2A and MCP toolchains through a single streaming orchestrator.</em></p><p>Modern AI applications rarely live in isolation. They need to delegate work to other agents, call external tools, and stream progress back to users in real time — keeping humans in the loop on what the agent is doing in the background. This post walks you through a practical proof‑of‑concept architecture that does exactly that: a unified orchestrator that fronts a React frontend, plans execution of user queries, and bridges two ecosystems — Agent‑to‑Agent (A2A) protocol servers and Model Context Protocol (MCP) servers — while streaming live updates end to end.</p><h3><a href="https://sidparmar.ca/blog/building-a-unified-orchestrator-for-agentic-flow#why-unify-a2a-and-mcp">Why unify A2A and MCP?</a></h3><ul><li><strong>Broader tool surface</strong>: A2A servers expose agent capabilities via JSON‑RPC and stream updates with SSE; MCP servers expose typed tools and schema‑driven calls. Together, they unlock both agent collaboration and structured tool execution from a single orchestrator.</li><li><strong>One client contract</strong>: The frontend speaks only WebSocket to the orchestrator. Everything else — planning, routing, streaming, and auth — happens behind the scenes.</li><li><strong>Zero‑friction expansion</strong>: Add new A2A agents by publishing an agent.json; add new MCP servers via a URL. The orchestrator discovers and registers tools at startup.</li><li><strong>Scaling philosophies</strong>: A2A scales <em>horizontally</em> — one agent, one job — while MCP scales <em>vertically</em> by adding more tools to a server. Together they represent two different ideologies of scaling, yet the orchestrator lets them complement each other.</li></ul><h3><a href="https://sidparmar.ca/blog/building-a-unified-orchestrator-for-agentic-flow#the-high-level-architecture">The high-level architecture</a></h3><ul><li><strong>React frontend</strong>: Connects to the orchestrator over WebSocket and sends tasks as simple JSON payloads with an optional bearer token.</li></ul><p><strong>Unified orchestrator</strong>:</p><ul><li>Maintains chat history per connection.</li><li>Initializes a dispatcher agent (LLM) with tools discovered from A2A and MCP.</li><li>Plans execution: decides whether a query is simple (single tool), complex (multi‑step), or compound (requiring multiple tools/agents).</li><li>Routes to the right A2A agent or MCP tool, or executes a multi‑step plan.</li><li>Bridges streaming from tools/agents back to the UI in real time.</li></ul><p><strong>A2A agents</strong>: Receive JSON‑RPC task requests; stream execution events via SSE.</p><p><strong>MCP servers</strong>: Provide tool catalogs over SSE; the orchestrator executes them directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JJEWNP37ZBJXYE0e52M7w.png" /><figcaption>A Unified Orchestrator for Agentic Flow with A2A + MCP</figcaption></figure><p><a href="https://sidparmar.ca/blog/building-a-unified-orchestrator-for-agentic-flow">Read the complete story here for free</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb946bd3b16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[async-react: A React component to simplify data fetching]]></title>
            <link>https://medium.com/dev-red/async-react-a-react-asyncawait-component-to-simplify-data-fetching-548d99a24814?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/548d99a24814</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Tue, 11 Sep 2018 20:39:05 GMT</pubDate>
            <atom:updated>2025-09-29T16:37:05.416Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simplify Data Fetching Using Async-React</h3><p>In this post, I am going to talk about a new JavaScript library that I created. It is called <a href="https://github.com/redacademy/async-react"><strong>async-react</strong></a>.</p><p>I think my library solves a problem of writing async code to grab data from an API especially when it comes to handling loading and error state.</p><p>Since I built this library using React, you can use it for your React apps or for your ReactNative apps. It works for both! 😃</p><h3>The Magic of <a href="https://github.com/redacademy/async-react">Async-React</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ii1ZQQKmpmEFOFCY5VkTxA.jpeg" /><figcaption>Magic!</figcaption></figure><p>To use my library in your project you can install it from NPM as usual.</p><p><strong>Install:</strong></p><p>npm install --save async-react</p><p><strong>Usage:</strong></p><p>I took inspiration from React’s new context API and &lt;Query /&gt; component from react-apolloas you can see in the example.</p><pre>&lt;AsyncAwait path=&quot;https://jsonplaceholder.typicode.com/posts&quot;&gt;<br>        {({ loading, error, data }) =&gt; {<br>          if (error) return &lt;h2&gt;{error}&lt;/h2&gt;;<br>          if (loading) return &lt;h2&gt;Loading...&lt;/h2&gt;;<br>          if (data) return &lt;MyComponent data={data} /&gt;;<br>        }}<br>&lt;/AsyncAwait&gt;</pre><p>I used Promise.all internally so that I can take in an array of different URLs for <em>path</em> prop and return results in the same way.</p><pre>&lt;AsyncAwait<br>  path={[<br>    &#39;https://jsonplaceholder.typicode.com/posts&#39;,<br>    &#39;https://jsonplaceholder.typicode.com/users&#39;<br>  ]}<br>&gt;<br>  {({ loading, error, data }) =&gt; {<br>    if (error) return &lt;h2&gt;{error}&lt;/h2&gt;;<br>    if (loading) return &lt;h2&gt;Loading...&lt;/h2&gt;;<br>    if (data) return &lt;MyComponent posts={data[0]} users={data[1]}/&gt;;<br>  }}<br>&lt;/AsyncAwait&gt;</pre><p>I thought I should add a feature to accept a base URL when the app starts. I prefer less typing 😜.</p><pre>// App.js</pre><pre>&lt;AsyncAwaitProvider baseUrl=&quot;https://jsonplaceholder.typicode.com&quot;&gt;<br>     &lt;AnotherComponent /&gt;<br>&lt;/AsyncAwaitProvider&gt;</pre><pre>// AnotherComponent.js<br>&lt;AsyncAwait path={[&#39;/posts&#39;, &#39;/users&#39;]}&gt;<br>        {({ loading, error, data }) =&gt; {<br>          if (error) return &lt;h2&gt;{error}&lt;/h2&gt;;<br>          if (loading) return &lt;h2&gt;Loading...&lt;/h2&gt;;<br>          if (data) <br>             return &lt;MyComponent posts={data[0]} users=data[1]} /&gt;;<br>        }}<br>&lt;/AsyncAwait&gt;</pre><p>&lt;AsyncAwaitProvider&gt; uses React’s context API internally. That’s how I was able to pull in the<em> baseURL </em>from the provider component. This component receives only one prop: <em>baseUrl,</em> as a string.</p><p>Just as shown in the first example, you can do path=&#39;/post&#39; or even you can do path={[&#39;/post&#39;]}. The <em>path</em> prop accepts both, array and string.</p><h3>Cheatsheet for async-react:</h3><ul><li><strong>imports</strong> : <strong>import</strong> AsyncAwaitProvider, {AsyncAwait} <strong>from</strong> ‘async-react’;</li><li><strong>AsyncAwaitProvider</strong>: Top level wrapper that has only one prop, baseUrl of type string. Use this if you would like to configure your endpoint’s absolute URL once and omit it elsewhere.</li><li><strong>AsyncAwait</strong>: It works like the&lt;Query /&gt; component from react-apollo. It takes in only one prop: <em>path,</em> of type either string or an Array.</li></ul><p>That’s it. I hope you enjoyed reading my blog. Here is a link to the package source <a href="https://github.com/redacademy/async-react">https://github.com/redacademy/async-react</a>. Feel free to create any issues or pull requests on github. Thank you for reading! 😄</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=548d99a24814" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-red/async-react-a-react-asyncawait-component-to-simplify-data-fetching-548d99a24814">async-react: A React component to simplify data fetching</a> was originally published in <a href="https://medium.com/dev-red">dev@red</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Build an App with ReasonReact]]></title>
            <link>https://medium.com/dev-red/tutorial-build-an-app-with-reasonreact-84f82782ef83?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/84f82782ef83</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[reasonreact]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 16:38:43 GMT</pubDate>
            <atom:updated>2018-08-17T16:40:35.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2—Creating the To-do App</h4><p>In my <a href="https://medium.com/dev-red/reasonreact-future-of-react-db141e15265e">previous post</a>, we explored why ReasonReact is awesome. In this post, we’ll roll up our sleeves and basic to-do app with it.</p><p>For this project, we will be using these technologies I mentioned previously:</p><ul><li><a href="https://reasonml.github.io/reason-react/en/">ReasonReact</a></li><li><a href="https://reactjs.org/">React</a></li><li><a href="https://bucklescript.github.io/">BuckleScript</a></li><li><a href="https://reasonml.github.io/en/">ReasonML</a></li><li><a href="https://ocaml.org/">OCaml</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIpKpxfe_GfyRQaqHlc1mw.png" /></figure><h3>InstallFest!</h3><p>Before we start coding you’ll need to install a few packages, if you haven’t done so already, including the <a href="https://github.com/reasonml/reason-cli">Reason CLI</a>. Follow the instructions for your specific platform:</p><ul><li><strong>Mac users:</strong> yarn global add reason-cli@latest-macos</li><li><strong>Linux users:</strong> yarn global add reason-cli@latest-linux</li><li><strong>Windows user:</strong> <a href="https://github.com/reasonml/reasonml.github.io/issues/195">Please see this issue thread on GitHub for instructions</a></li></ul><p>Next, we’ll install <a href="https://github.com/BuckleScript/bucklescript">BuckleScript</a>. Run npm install -g bs-platform to install BuckleScript globally.</p><p>We’ll be using <a href="https://github.com/reasonml-community/reason-scripts">Reason Scripts</a> so we can work in a way that will feel more familiar to React developers like us.</p><p>To scaffold your ReasonReact project, run:</p><pre>yarn create react-app reason-react-todo --scripts-version reason-scripts</pre><p>Let’s jump in and explore our new project:</p><pre>cd reason-react-todo &amp;&amp; yarn start</pre><p>It should look something like this. Looks familiar, doesn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxM7k72uRdkz0NzZV-1CsQ.png" /><figcaption>Your “Hello, World!” ReasonReact App</figcaption></figure><h3>What’s Inside?</h3><p>Exploring what’s in the boilerplate project, the familiar files and directories to notice here are package.json, .gitignore, README.md, yarn.lock, public/, and node_modules/.</p><p>Additionally, you will find:</p><ul><li>.merlin: <strong>You should not touch this file</strong>. This file is created by the build system and contains absolute paths for <a href="https://github.com/ocaml/merlin/wiki">Merlin</a> to understand the project layout and provide editor tooling.</li><li>bsconfig.json: This is a necessary file used by BuckleScript’s build system, bsb. You can find more details about it <a href="https://bucklescript.github.io/docs/en/build-configuration.html">here</a>.</li><li>.re files: These are the Reason files. <strong>We will be writing our code in these files.</strong> BuckleScript will convert these files into .bs.js files, automatically.</li></ul><p>In App.re file, we see these lines of code:</p><pre>[%bs.raw {|require(&#39;./App.css&#39;)|}];<br>[<a href="http://twitter.com/bs">@bs</a>.module] external logo : string = &quot;./logo.svg&quot;;</pre><p>That’s how BuckleScript imports the CSS file and the logo file. You can read more on imports and exports with BuckleScript <a href="https://bucklescript.github.io/docs/en/import-export.html#docsNav">here</a>.</p><p>ReasonReact does not use classes. All we have to do to create a component is:</p><pre>let component = ReasonReact.statelessComponent(&quot;MyApp&quot;);</pre><p>Next, we use a make function to return the component we just created. In that function, we can override a few fields like the render, and initialState. The render field is where we write our JSX:</p><pre>let component = ReasonReact.statelessComponent(&quot;MyApp&quot;);</pre><pre>let make = (~name, _children) =&gt; {<br>  ...component, // spread the template&#39;s other defaults into here</pre><pre>  render: _self =&gt; &lt;div&gt; {ReasonReact.string(name)} &lt;/div&gt;<br>};</pre><p>We can see above that the last prop in a make function is children. If you don’t need to use the children prop in your component, you can call it either_ or _children to avoid compiler warnings.</p><p>You may also notice that we’re not using this. In ReasonReact, we don’t have access to JavaScript’s this, but rather we use self which is equivalent to this for our purposes.</p><p>Finally, we use ReasonReact.string to print strings. ReasonReact.string takes in a string and returns a reactElement.</p><h3>The TodoApp Component</h3><p>Now that we understand the basic syntax of a ReasonReact component, we’re ready to create our to-do app’s outer-most component:</p><pre>[%bs.raw {|require(&#39;./App.css&#39;)|}];<br>[<a href="http://twitter.com/bs">@bs</a>.module] external logo : string = &quot;./logo.svg&quot;;</pre><pre>let component = ReasonReact.statelessComponent(&quot;App&quot;);</pre><pre>let make = (~message, _children) =&gt; {<br>  ...component,<br>  render: _self =&gt;<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;div className=&quot;App-header&quot;&gt;<br>        &lt;img src=logo className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>        &lt;h2&gt; (ReasonReact.string(message)) &lt;/h2&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;App-intro&quot;&gt; &lt;TodoApp /&gt; &lt;/div&gt;<br>    &lt;/div&gt;,<br>};</pre><p>Notice that we’re rendering a TodoApp component above, but we haven’t created this yet. Let’s create a components sub-directory in src directory and create a file in it called TodoApp.re. This will be our stateful component.</p><p>In ReasonReact, typically, a stateful component includes actions, a reducer, and state (just like Redux—but don’t worry, we’re not going to use Redux in this app).</p><p>As we know, a state is tracked in an object in React. In Reason, we have two choices do the same, <em>Record</em>, and <em>Object</em>. We will be creating a <em>Record</em> in our app. Let’s see how we can create a <em>Record</em> and how declaring an <em>object</em> is a little different than how we do it in JavaScript. In Reason, we can define an <em>object type</em>.</p><p><strong>Note:</strong> In ReasonML, there are two types of objects. There are “open” object types (which can contain other values and objects beyond what’s in its type declaration) and “closed” object types (where the object must have the same shape as the declared type). For more information, <a href="https://reasonml.github.io/docs/en/object.html#type-declaration">check the docs</a>.</p><p>Since we’re going to use this <em>Record</em> throughout our app, let’s put it in a separate file in the components directory called TodoModel.re</p><pre>type item = {<br>  id: int,<br>  title: string,<br>  completed: bool,<br>};</pre><p>Back in TodoApp.re we define the state for our app:</p><pre>type state = {<br>  items: list(TodoModel.item), // list of Todo items<br>  inputText: string, <br>  // we will use this when we will take input from a user<br>};</pre><p>Now, let’s create a stateful component:</p><pre>// state declaration here</pre><pre>let component = ReasonReact.reducerComponent(&quot;TodoLists&quot;);</pre><pre>let str = ReasonReact.string;</pre><pre>let make = _children =&gt; {<br>    ...component,<br>    initialState: () =&gt; {<br>      items: [{id: 0, title: &quot;milk&quot;, completed: false}],<br>      inputText: &quot;&quot;,<br>    },<br>    reducer: ((), _) =&gt; ReasonReact.NoUpdate, <br>    // we will come back to this when we have actions. <br>    // Currently, we do not want our state to change since we just<br>    // want to print data on screen.</pre><pre>    render: self =&gt; {<br>      let {items, inputText} = self.state; // destructure the state<br>      &lt;div className=&quot;app&quot;&gt;<br>        &lt;div className=&quot;list&quot;&gt;<br>          (<br>            ReasonReact.array( <br>            // converts an array into a react element<br>              Array.of_list( <br>              // returns a fresh array containing elements of a list<br>                List.map( <br>                // returns a new list<br>                  (item: TodoModel.item) =&gt;<br>                    &lt;TodoItem<br>                      key=(string_of_int(item.id)) <br>                      // converts int id into string id<br>                      item<br>                    /&gt;,<br>                  items,<br>                ),<br>              ),<br>            )<br>          )<br>        &lt;/div&gt;<br>      &lt;/div&gt;;<br>    },<br>}</pre><p>Finally we’ll build theTodoItem component. It is going to be a stateless component because its job is to display data.</p><p>Write the follow in in a new file calledTodoItem.re</p><pre>let str = ReasonReact.string;</pre><pre>let component = ReasonReact.statelessComponent(&quot;TodoItem&quot;);</pre><pre>let make = (~item: TodoModel.item,  _children) =&gt; {<br>  ...component,<br>  render: _self =&gt;<br>    &lt;div className=&quot;item&quot;&gt;<br>      &lt;input<br>        _type=&quot;checkbox&quot;<br>        checked=item.completed<br>      /&gt;<br>      &lt;p&gt; (str(item.title)) &lt;/p&gt;<br>    &lt;/div&gt;,<br>};</pre><p>To let BuckleScript access our .re files and convert them into .bs.js files, we need to edit our bsconfig.js file.</p><pre>&quot;sources&quot;: [&quot;src&quot;, &quot;src/components&quot;]</pre><p>stop the server, run the command bsb at the root of the project dir and start the project again withyarn start and we should be able to see the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYCUYStl3mRZQDI6C2oBtw.png" /><figcaption>ReasonReact Todo app List item</figcaption></figure><p>It works! Woohoo! Congratulations! That’s the basics of how to write stateless and stateful components in ReasonReact.</p><p>We can also add a header component to our app by creating a TodoHeader.refile and adding the following code:</p><pre>let component = ReasonReact.statelessComponent(&quot;TodoHeader&quot;);</pre><pre>let make = _children =&gt; {<br>  ...component,<br>  render: _self =&gt;<br>    &lt;div className=&quot;app-header&quot;&gt;<br>      &lt;div className=&quot;title&quot;&gt; <br>           (ReasonReact.string(&quot;Todo List&quot;))<br>      &lt;/div&gt;<br>    &lt;/div&gt;,<br>};</pre><p>Include TodoHeader component in TodoApp.re</p><pre>// ...<br>render: self =&gt; {<br>      let {items, inputText} = self.state;<br>      &lt;div className=&quot;app&quot;&gt;<br>        //  add this line<br>        &lt;TodoHeader /&gt;<br>        ...</pre><pre>      &lt;/div&gt;<br>}<br>// ...</pre><p>Nice, we can see our App Header now.</p><p>Now, let’s make our app more interactive by adding 2 things:</p><ul><li>A checkbox toggle</li><li>A button to remove a particular to-do item</li></ul><pre>type action =<br>  | Toggle(int)<br>  | RemoveItem(int);</pre><pre><br>let make = _children =&gt; {<br>    ...component,<br>    initialState: () =&gt; {<br>      items: [{id: 0, title: &quot;milk&quot;, completed: false}],<br>      inputText: &quot;&quot;,<br>    },<br>    reducer: action =&gt;<br>      switch (action) {<br>      | Toggle(id) =&gt; (<br>          state =&gt;<br>            ReasonReact.Update({<br>              ...state,<br>              items:<br>                List.map(<br>                  (item: TodoModel.item) =&gt;<br>                    item.id == id ?<br>                      {<br>                        ...item,<br>                     TodoModel.completed:!TodoModel(item.completed),<br>                      } :<br>                      item,<br>                  state.items,<br>                ),<br>            })<br>        )<br>     | RemoveItem(id) =&gt; (<br>          state =&gt;<br>            ReasonReact.Update({<br>              ...state,<br>              items:<br>                List.filter(<br>                  (item: TodoModel.item) =&gt; item.id !== id,<br>                  state.items,<br>                ),<br>            })<br>        )<br>   }, <br>   render: self =&gt; {<br>        ...<br>        &lt;div className=&quot;list&quot;&gt;<br>          (<br>            ReasonReact.array(<br>              Array.of_list(<br>                List.map(<br>                  (item: TodoModel.item) =&gt;<br>                    &lt;TodoItem<br>                      key=(string_of_int(item.id))<br>                      item<br>                      onRemove=(id =&gt; self.send(RemoveItem(id)))<br>                      onToggle=(id =&gt; self.send(Toggle(id)))<br>                    /&gt;,<br>                  items,<br>                ),<br>              ),<br>            )<br>          )<br>        &lt;/div&gt;<br>}</pre><p>This is our first step towards <em>actions and reducers.</em></p><p>Now, refactor TodoItem.re</p><pre>let str = ReasonReact.string;<br>let component = ReasonReact.statelessComponent(&quot;TodoItem&quot;);<br>let make = (~item: TodoModel.item, ~onRemove, ~onToggle, _children) =&gt; {<br>  ...component,<br>  render: _self =&gt;<br>    &lt;div className=&quot;item&quot;&gt;<br>      &lt;input<br>        _type=&quot;checkbox&quot;<br>        checked=item.completed<br>        onChange=((_) =&gt; onToggle(item.id))<br>      /&gt;<br>      &lt;p&gt; (str(item.title)) &lt;/p&gt;<br>      &lt;button onClick=((_) =&gt; onRemove(item.id))&gt; <br>        (str(&quot;Remove&quot;))<br>      &lt;/button&gt;<br>    &lt;/div&gt;,<br>};</pre><p>This code enables us to change our app’s state using a checkbox or a remove button attached to each todo item.</p><p><strong>Challenge Round</strong>: Create a TodoFooter component that can show a total number of items, has a button to remove all the items and has another button to remove completed items. At the end it should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4qxMPPE19YjgKR7jw7X2w.png" /><figcaption>ReasonReact Todo App — added footer</figcaption></figure><p>You can find code for the complete project here: <a href="https://github.com/redacademy/reason-react-todo">https://github.com/redacademy/reason-react-todo</a>).</p><p>Did you finish the challenge? Nice work!</p><p>Moving on, we have to create an input component so our user can add todos. Refactor TodoApp.re</p><pre>type action =<br>  | InputText(string)<br>  | Toggle(int)<br>  | RemoveAll<br>  | RemoveItem(int)<br>  | RemoveCompleted<br>  | Submit;</pre><pre>let component = ReasonReact.reducerComponent(&quot;TodoApp&quot;);</pre><pre>let str = ReasonReact.string;</pre><pre>let make = _children =&gt; {<br>  let handleSubmit = state =&gt; {<br>    let newId: int = List.length(state.items);<br>    let newItem: TodoModel.item = {<br>      id: newId,<br>      title: state.inputText,<br>      completed: false,<br>    };<br>    let newList = [newItem, ...state.items];<br>    ReasonReact.Update({items: newList, inputText: &quot;&quot;});<br>  };<br>  {<br>    ...<br>  reducer: action =&gt;<br>      switch (action) {<br>      | InputText(newText) =&gt; (<br>          state =&gt; ReasonReact.Update({...state, inputText:newText})<br>        )<br>     | Submit =&gt; (state =&gt; handleSubmit(state))<br>  },<br>  render: self =&gt; {<br>      let {items, inputText} = self.state;<br>      &lt;div className=&quot;app&quot;&gt;<br>        &lt;TodoHeader /&gt;<br>        &lt;AddTodo<br>          submit=((_) =&gt; self.send(Submit))<br>          value=inputText<br>          onInputText=(text =&gt; self.send(InputText(text)))<br>        /&gt;<br>        ...<br>      &lt;/div&gt;<br>  }</pre><p>You might have noticed that we do not have an AddTodo component yet. Let’s create that component in a file called AddTodo.re</p><pre>let str = ReasonReact.string;</pre><pre>let component = ReasonReact.statelessComponent(&quot;AddTodo&quot;);</pre><pre>let make = (~value, ~onInputText, ~submit, _children) =&gt; {<br>  ...component,<br>  render: _self =&gt;<br>    &lt;div className=&quot;input&quot;&gt;<br>      &lt;input<br>        value<br>        placeholder=&quot;add item&quot;<br>        onChange=(<br>          event =&gt;<br>            onInputText( ReactDOMRe.domElementToObj(ReactEventRe.Form.target(event))##value,<br>            )<br>        )<br>      /&gt;<br>      &lt;button onClick=((_) =&gt; submit())&gt; (str(&quot;Add&quot;)) &lt;/button&gt;<br>    &lt;/div&gt;,<br>};</pre><p>What is ReactDomRe?</p><p>ReactDomRe is ReasonReact’s React-DOM module. ReactDOMRe.domElementToObj(ReactEventRe.Form.target(event))##value is the same as event.target.value in JavaScript.</p><p>You can find out more about theReactDomRe module here: (<a href="https://reasonml.github.io/reason-react/docs/en/dom.html#reactdom">https://reasonml.github.io/reason-react/docs/en/dom.html#reactdom</a>)</p><p>We’re finished! In the end, our app looks like this. If you’re project is not working, you can have a look at the <a href="https://github.com/redacademy/reason-react-todo">GitHub repo for this projec</a>t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cY3iLWrOk0CKM3iD0vlQIQ.png" /><figcaption>ReasonReact Todo App</figcaption></figure><p><em>If you liked this post and want to keep learning about </em><a href="https://redacademy.com/programs/"><em>web and app development</em></a><em> with RED Academy, be sure to follow us on Medium or check out </em><a href="https://redacademy.com/"><em>our website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84f82782ef83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-red/tutorial-build-an-app-with-reasonreact-84f82782ef83">Tutorial: Build an App with ReasonReact</a> was originally published in <a href="https://medium.com/dev-red">dev@red</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Build an App with ReasonReact]]></title>
            <link>https://medium.com/dev-red/reasonreact-future-of-react-db141e15265e?source=rss-366e770aced0------2</link>
            <guid isPermaLink="false">https://medium.com/p/db141e15265e</guid>
            <category><![CDATA[reasonreact]]></category>
            <category><![CDATA[reasonml]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Siddharth Parmar (Sid)]]></dc:creator>
            <pubDate>Tue, 24 Jul 2018 17:34:06 GMT</pubDate>
            <atom:updated>2018-08-17T16:41:47.318Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tutorial: Build a Todo App with ReasonReact</h3><h4>Part 1—Future of React? ReasonReact!</h4><p>In this post, we’re going to explore <a href="https://reasonml.github.io/reason-react/">ReasonReact</a>— a new-ish tool from Facebook for building React applications. We’ll cover the basics of what ReactReason is, and in a future post, build a basic to-do app using it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y69OxEaZO75PXNBqK5GGLQ.png" /></figure><h3>What is Reason?</h3><p>Reason isn’t a new language, but rather a new syntax and toolchain powered by <a href="https://ocaml.org/">OCaml</a> that’s intended for JavaScript developers. Reason eliminates the need to write traditional OCaml, but still provides all the benefits of the language.</p><p>OCaml can be compiled into bytecode, native code, and JavaScript. To compile to JavaScript, we’ll need to use <a href="https://bucklescript.github.io/">BuckleScript</a>. With BuckleScript in place, we can use yarn or npm with any ReasonReact project.</p><p>Here’s a diagram to better illustrate the flow from Reason/OCaml to JavaScript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VfY3hsrelLZGyZjMpAewUQ.png" /><figcaption>ReasonML to JavaScript diagram.</figcaption></figure><h3><strong>Why Use Reason?</strong></h3><p>Since Reason is based on OCaml, it leverages all of the advantages of OCaml.<br>For example, Reason is a statically typed with full support for object orientation and mutable support.</p><p>When we use Reason, our code ends up looking a lot like the JavaScript code that we’re used to. However, based on my own experience, when you use Reason you can eliminate ESLint from your project because of its type system.</p><p>Code can be compiled quickly and efficiently from Reason, and Reason team is working hard to improve error message.</p><p>Ultimately, the best way to appreciate the advantages of Reason is to give it a try, so let’s get set up to do that!</p><h3><strong>Reason + React = ReasonReact</strong></h3><p>Using Reason with your React project is easy thanks to the <a href="https://reasonml.github.io/reason-react/">ReasonReact</a> library. It has all the great features of Reason <em>and</em> also provides us with a way to build the React apps that we’re used to, but with an API that is safe, clean, and statically-typed.</p><p>Can’t wait to see what this looks like? <a href="https://reasonml.github.io/en/try">Try ReasonReact in a browser here.</a></p><p>To use ReasonReact to build a real app, you’ll need to start by installing BuckleScript’s bsb build system:</p><pre>npm install -g bs-platform</pre><p>Once that’s installed, there are two ways to create a ReasonReact app.</p><p>The <a href="https://reasonml.github.io/reason-react/docs/en/installation#bsb">first option</a> is a lighter-weight approach, that compiles your Reason code to straightforward JS files, so you can actually open index.html directly from the file system if you wanted to:</p><pre>$ bsb -init &lt;app-name&gt; -theme react<br>$ cd &lt;app-name&gt; &amp;&amp; npm install &amp;&amp; npm start<br><em># in another tab<br></em>$ npm run webpack</pre><p>The <a href="https://reasonml.github.io/reason-react/docs/en/installation#reason-scripts-aka-create-react-app">second option</a> is to use Reason Script with Create React App:</p><pre>$ npx create-react-app &lt;app-name&gt; --scripts-version reason-scripts<br>$ cd &lt;app-name&gt;<br>$ npm start</pre><p>Once you’ve scaffolded your app, you’re ready to give ReasonReact a try. Here’s an example of you would create a stateless component using ReasonReact:</p><pre>let component = ReasonReact.statelessComponent(“App”);</pre><pre>let make = (~message, _children) =&gt; {<br> …component,<br> render: _self =&gt;<br> &lt;div className=”App”&gt;<br>     &lt;img src=logo className=”App-logo” alt=”logo” /&gt;<br>     &lt;h2&gt; (ReasonReact.string(message)) &lt;/h2&gt;<br> &lt;/div&gt;,<br>};</pre><p>If you’re still not convinced and would like to learn more about the Reason Project, check out this talk by Cheng Lou at React Conf 2017:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_0T5OSSzxms%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_0T5OSSzxms&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_0T5OSSzxms%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/327e31ce3f9f329f65a83fd7550b5a14/href">https://medium.com/media/327e31ce3f9f329f65a83fd7550b5a14/href</a></iframe><p>In the next post, we’ll roll up our sleeves and dive into ReasonReact to create the following to-do app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cY3iLWrOk0CKM3iD0vlQIQ.png" /><figcaption>ReasonReact Todo App</figcaption></figure><p>Great. We’ll finish the todo app in <a href="https://medium.com/dev-red/tutorial-build-an-app-with-reasonreact-84f82782ef83">Part 2 here</a>!</p><p><em>If you liked this post and want to keep learning about </em><a href="https://redacademy.com/programs/"><em>web and app development</em></a><em> with RED Academy, be sure to follow us on Medium or check out </em><a href="https://redacademy.com/"><em>our website</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db141e15265e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-red/reasonreact-future-of-react-db141e15265e">Tutorial: Build an App with ReasonReact</a> was originally published in <a href="https://medium.com/dev-red">dev@red</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>