<?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 Mohammad Shojaei on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Shojaei on Medium]]></description>
        <link>https://medium.com/@mshojaei77?source=rss-1d6325312ab5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VlDzjc4N65-9ceDg5_e5dg.png</url>
            <title>Stories by Mohammad Shojaei on Medium</title>
            <link>https://medium.com/@mshojaei77?source=rss-1d6325312ab5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:45:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mshojaei77/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[Most “AI Agent” Use Cases Are Just Glorified If-Else Chains]]></title>
            <link>https://medium.com/@mshojaei77/most-ai-agent-use-cases-are-just-glorified-if-else-chains-8c86c14c6051?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c86c14c6051</guid>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 14:31:02 GMT</pubDate>
            <atom:updated>2026-07-20T14:31:02.022Z</atom:updated>
            <content:encoded><![CDATA[<h3>A builder’s guide to separating simple API integrations from production-grade agentic architectures.</h3><p>The AI industry is currently obsessed with master lists. If you browse tech forums or community repositories, you will find massive inventories detailing hundreds of “AI agent” use cases. They range from the hyper-specific — like planning timber-floor board cuts or decompiling supermarket APKs — to enterprise workflows like loan validation and medical prior-authorization.</p><p>But if you actually write Python, manage databases, and deploy systems for a living, reading these lists will mostly make you sigh.</p><p>Most of these listed use cases are not agents. They are basic CRUD applications, linear API chains, or simple cron jobs with an LLM call slapped in the middle. If a system follows a hardcoded path from step A to step B to step C, it is not an agent — it is a traditional software pipeline.</p><p>However, if you strip away the marketing fluff and the vibe-coding projects that only survived long enough to win a hackathon, there is a real, highly valuable architectural core hiding underneath. When you look at the workflows that actually deliver production value, they share a distinct technical pattern: they rely on dynamic execution loops, deterministic policy guardrails, and robust state management.</p><h3>The short version</h3><p>Most community-reported “agent” use cases can be easily built using a standard automation platform like n8n or a simple Python script using Celery. If you do not need the system to dynamically decide its own path or recover from unexpected tool failures on the fly, do not use an agent framework. It will only add latency, cost, and unpredictability.</p><p>The use cases that actually require a true agentic architecture — meaning an LLM running inside a loop with tool-access and self-correction capabilities — fall into a few narrow buckets:</p><ol><li><strong>Dynamic Tool Orchestration:</strong> Where the exact sequence of API calls cannot be predicted at design time (e.g., repository-wide code refactoring or multi-server sysadmin troubleshooting).</li><li><strong>Deterministic-Bounded Autonomy:</strong> Systems where the LLM handles reasoning and tool selection, but is strictly governed by an external, non-neural policy kernel that enforces spending limits and access control.</li><li><strong>Event-Driven State Resumption:</strong> Long-running workflows that sleep, wait for external webhooks, and resume execution without losing their historical context or wasting tokens.</li></ol><h3>What the source lists actually show</h3><p>If you categorize the massive list of community-reported use cases, you find everything from smart-home hacks to deep research pipelines.</p><p>In the smart-home and personal productivity space, developers are using models like Hermes or Claude to act as natural-language interfaces for legacy setups. They are writing code to control Home Assistant via Telegram, diagnose disconnecting CCTV cameras, or parse family phone bills to calculate individual totals.</p><p>At the hackathon and enterprise level, the designs get significantly more complex. We see projects like Daniel LaForce’s Custodian, which placed first in a recent hackathon by putting a strict security kernel between an LLM and real-world execution. We see systems like Mom-n-Pop-Skills, which lets small-business agents buy their own software using virtual cards with owner approval. We even see highly specific physical-world integrations, such as using eye-movements on mobile devices as communication interfaces, or webcam-based partners checking electronics projects for wiring errors.</p><p>The sheer variety of these use cases is impressive, but it highlights a massive gap between a cool prototype and a system you can actually ship to production.</p><h3>The useful technical ideas</h3><p>When you look past the specific business problems being solved, three core architectural patterns emerge that every AI engineer should keep in mind.</p><h3>Pattern 1: The External Policy Kernel</h3><p>You cannot trust a neural network with a credit card, raw SSH access, or database write permissions. If you build an agent that directly calls billing or system APIs, it will eventually hallucinate, loop infinitely, or get exploited via prompt injection.</p><p>The most elegant solution to this is the policy kernel pattern, seen in projects like Custodian. Instead of trying to write perfect system prompts to keep the agent in check, you place a deterministic, non-LLM validation layer between the agent’s proposed tool call and the actual execution environment.</p><blockquote>[Agent LLM] ──(Proposed Tool Call)──&gt; [Policy Kernel] ──(Validation Fail)──&gt; [Block &amp; Request Human Help]<br> │<br> (Passes Rules)<br> │<br> ▼<br> [Actual API / SSH]</blockquote><p>The policy kernel reads a signed, immutable configuration file (specifying things like max spending limits, restricted directories, or banned commands). If the agent attempts a tool call that violates these rules, the kernel blocks the action, rolls back the state, and alerts a human. The LLM never has direct access to the metal.</p><h3>Pattern 2: Privilege-Isolated Multi-Agent Swarms</h3><p>In smart-home and enterprise workflows, we frequently see the pattern of “guardrailed household agents” or specialized departments.</p><p>If you give a single agent access to every tool in your repository, you expose yourself to massive security risks. If an attacker injects a malicious payload into a document your agent is reading, they can hijack the session and run arbitrary commands.</p><p>Instead, the solution is privilege isolation. You build a public-facing, low-privilege agent that interacts with the user, parses intents, and runs basic read-only tools. When a highly sensitive action is needed (like modifying a system configuration or releasing a payment), the low-privilege agent must serialize its request and send it to a high-privilege, isolated backend agent that has no direct contact with the external user or raw inputs.</p><h3>Pattern 3: Event-Driven State Resumption</h3><p>Many of the best developer-focused agent use cases — like running automated Kanban workflows or waiting for CI test feedback — require long periods of waiting.</p><p>If your agent is running in a continuous loop waiting for a GitHub Action to finish, you are wasting money, holding open compute threads, and risking API timeouts.</p><p>Production-ready agents use an event-driven loop. The agent executes a tool call (e.g., running a test suite), serializes its current state (memory, active variables, and trajectory) to a database, and immediately terminates. When the test runner finishes, it fires a webhook that wakes the agent up, reloads its state from the database, and lets it continue reasoning. This is the only way to build cost-effective, long-running workflows.</p><h3>What I would actually use in production</h3><p>If you are building commercial AI products, throw out 90% of the master lists. Most of them are not commercially viable due to latency, cost, or reliability issues.</p><p>Here are the specific use cases I would actually build today:</p><ul><li><strong>Closed-Loop Code Refactoring:</strong> If you ground your agent with local linters, compilers, and test suites, you can let it run in an autonomous loop to fix bugs or migrate frameworks. This works because the environment provides objective, deterministic feedback. The code either compiles and passes tests, or it does not.</li><li><strong>Bounded Compliance Checkers:</strong> Reading messy documents (like building permits, legal contracts, or tax filings) and checking them against local regulations. The agent extracts structured data, runs rule-checking algorithms, and outputs a detailed report. The crucial part: the agent only reports findings; a human makes the final decision.</li><li><strong>Context-Aware Retrieval Aggregators:</strong> Replacing basic vector search with an agent that can dynamically formulate multiple search queries, evaluate the quality of retrieved chunks, scrape missing web context, and build a unified synthesis of the data.</li></ul><p>I would completely avoid un-gated transaction agents (like booking hotels or buying products automatically) and anything where a single hallucination could lead to immediate financial or physical damage.</p><h3>The annoying details that break after the demo</h3><p>When you build these systems, you quickly realize that the demo is the easy part. The plumbing is where things get messy.</p><h3>Latency and Token Accumulation</h3><p>If your agent uses a reasoning loop (like ReAct or Plan-and-Solve) to decide which tools to call, each step requires a separate LLM call. If your model of choice has a three-second latency, and it needs five steps to resolve a query, your user is waiting fifteen seconds for an answer.</p><p>Worse, as the loop runs, the agent’s history grows. Every tool execution, system log, and model thought is appended to the context window. By step five, you are sending thousands of tokens back and forth, which rapidly increases your API bills and degrades inference speed.</p><h3>State Drift and Unhandled Exceptions</h3><p>What happens when your agent is halfway through modifying three separate configuration files, and the database connection drops? Or the model outputs slightly malformed JSON that fails your parser?</p><p>If you have not built an explicit transaction rollback mechanism, your system will be left in a corrupted, half-modified state. Traditional software developers solved this decades ago with database transactions and try-catch blocks. AI engineers building agents frequently forget this, leaving local systems, files, and APIs completely broken when an execution loop fails midway.</p><h3>Evaluation is a Nightmare</h3><p>How do you run regression tests on a system that can dynamically choose its own execution path?</p><p>If you change a single sentence in your system prompt, your agent might choose to call Tool B instead of Tool A to solve the exact same task. If you do not have a robust evaluation harness that runs dozens of simulated trajectories and asserts end-state conditions rather than exact string matches, you are essentially flying blind.</p><h3>Limitations</h3><p>These master lists of use cases do not prove production readiness. Almost all of the highly complex workflows — like multi-agent homeschooling, robotic surgery copilots, or generative virtual bands — are either early-stage prototypes, hobbyist homelab projects, or highly curated marketing demos.</p><p>They show what is technically possible under ideal conditions with clean inputs, unlimited API budgets, and zero latency constraints. They do not show how these systems behave when fed noisy OCR text from a scanned PDF, or how they handle malicious prompt-injection attacks in the wild.</p><h3>Final takeaway</h3><p>An AI agent is not a magical entity that can run your business while you sleep. It is simply a software pattern that uses an LLM as a dynamic routing engine inside a state loop.</p><p>If you can write your workflow as a deterministic script or a standard automation DAG, do that instead. You will save money, reduce latency to milliseconds, and eliminate hallucinations. Save the agentic frameworks for the narrow, messy problems where the execution path is truly impossible to predict beforehand — and even then, make sure you wrap your agent in a very tight, very deterministic security kernel.</p><h3>References</h3><ul><li>Repository: hewi333/Mom-n-Pop-Skills — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fgithub.com%2Fhewi333%2FMom-n-Pop-Skills">https://github.com/hewi333/Mom-n-Pop-Skills</a></li><li>Case Study: Replit Agent by LangChain — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fwww.langchain.com%2Fbreakoutagents%2Freplit">https://www.langchain.com/breakoutagents/repli</a></li><li>Technical Article: Building Effective AI Agents by Anthropic — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fwww.anthropic.com%2Fresearch%2Fbuilding-effective-agents">https://www.anthropic.com/research/building-effective-agents</a></li><li>Product Documentation: Claude Code by Anthropic — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fwww.anthropic.com%2Fproduct%2Fclaude-code">https://www.anthropic.com/product/claude-code</a></li><li>Platform Documentation: Agentforce by Salesforce — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fwww.salesforce.com%2Feu%2Fagentforce%2F">https://www.salesforce.com/eu/agentforce/</a></li><li>Hackathon Announcement: Nous Research Custodian Project on X — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fx.com%2FNousResearch%2Fstatus%2F2077517417425543632">https://x.com/NousResearch/status/2077517417425543632</a></li><li>Technical Blueprint: Real-World Gen AI Use Cases with Technical Blueprints by Google Cloud — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fcloud.google.com%2Fblog%2Fproducts%2Fai-machine-learning%2Freal-world-gen-ai-use-cases-with-technical-blueprints">https://cloud.google.com/blog/products/ai-machine-learning/real-world-gen-ai-use-cases-with-technical-blueprints</a></li><li>Hackathon Results: AWS AI Agent Global Hackathon Winners — <a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Faws-agent-hackathon.devpost.com%2Fupdates%2F38140-congratulations-to-the-winners-of-the-aws-ai-agent-global-hackathon">https://aws-agent-hackathon.devpost.com/updates/38140-congratulations-to-the-winners-of-the-aws-ai-agent-global-hackathon</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c86c14c6051" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Compared 22 AI Coding Harnesses. Most Developers Are Comparing the Wrong Thing.]]></title>
            <link>https://medium.com/@mshojaei77/i-compared-22-ai-coding-harnesses-most-developers-are-comparing-the-wrong-thing-4efb26650fcd?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4efb26650fcd</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[harness]]></category>
            <category><![CDATA[agent-harness]]></category>
            <category><![CDATA[ai-harness]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 07:52:19 GMT</pubDate>
            <atom:updated>2026-07-19T07:52:19.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>Claude Code, Codex, Cursor, Cline, Devin, Jules, Kiro, OpenCode, and the rest are not really competing on models. They are competing on workflow.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFd_SHSh_OoqYdc9MkICwA.png" /></figure><p>The easiest way to choose the wrong AI coding tool is to begin with the question everyone asks:</p><blockquote><em>Which one has the smartest model?</em></blockquote><p>That question sounds reasonable. It is also becoming less useful.</p><p>Several coding products can now access the same frontier models — or models close enough in capability that the difference is not obvious during normal work. Yet those products can feel completely different once they touch a real repository.</p><p>One agent reads the project instructions, finds the correct module, edits three files, runs the relevant tests, catches its own regression, and returns a clean diff.</p><p>Another uses an equally capable model, wanders through unrelated folders, rewrites code you never asked it to touch, and announces success without running anything.</p><p>The difference is often not the model.</p><p>It is the <strong>harness</strong>.</p><p>The model knows how to generate code. The harness decides whether it can understand your repository, operate tools, follow rules, recover from mistakes, ask for approval, and complete useful work.</p><p>That is the real competition between Claude Code, Codex, Cursor, OpenCode, Cline, Kilo Code, Devin, Jules, Kiro, Antigravity, Hermes Agent, and the growing pile of products arriving every month.</p><p>After comparing 22 of them, my conclusion is simple:</p><blockquote><strong><em>Choose the shape of work first. Choose the model second.</em></strong></blockquote><h3>What an AI Coding Harness Actually Does</h3><p>A coding harness is the system wrapped around the language model.</p><p>It determines:</p><ul><li>How repository context is collected</li><li>Which files the agent can inspect or modify</li><li>Whether it can execute shell commands</li><li>How approvals and permissions work</li><li>Whether it can run tests and inspect failures</li><li>How project instructions and memory are stored</li><li>Whether it supports MCP, hooks, skills, plugins, or subagents</li><li>Whether execution happens locally or in a cloud sandbox</li><li>How several agents coordinate</li><li>How security, usage, and cost are controlled</li></ul><p>Put a strong model inside a weak harness and you get an impressive chatbot that occasionally edits files.</p><p>Put it inside a good harness and you get something closer to a junior engineer with terminal access, repository context, operating rules, and a test environment.</p><p>Occasionally, it even behaves like a senior engineer.</p><p>Occasionally, it fixes the bug by deleting the feature.</p><p>We are still early.</p><h3>Stop Putting Every Product in the Same Leaderboard</h3><p>Most AI coding comparisons produce one enormous table and crown a winner.</p><p>That makes a neat spreadsheet and a terrible buying guide.</p><p>Cursor and Devin do not solve the same problem. Neither do Claude Code and Portkey AI. One is an editor, one is a delegated cloud worker, one is a terminal agent, and one is infrastructure for governing other agents.</p><p>The market makes much more sense when divided by workflow.</p><h3>Editor-first environments</h3><p><strong>Cursor, Kiro, Trae, and Antigravity</strong> are built around an IDE-like experience.</p><p>They work best when you want to remain inside an editor, collaborate with the agent continuously, inspect diffs, and keep moving. The agent is part of your coding loop rather than a worker you send away.</p><h3>Terminal-first agents</h3><p><strong>Claude Code, OpenCode, Command Code, Grok Build, Kimi Code, Z Code, Pi Code, Cline, Roo Code, Kilo Code, and the Codex CLI</strong> treat files, commands, tests, and Git operations as first-class parts of the interaction.</p><p>These generally feel more natural to experienced developers who already think in repositories and shell commands.</p><h3>Asynchronous cloud workers</h3><p><strong>Codex, Devin, and Jules</strong> can operate more like delegated engineers.</p><p>You assign a repository task, the agent works in an isolated environment, and you review the result later — often as a pull request.</p><h3>Persistent cross-application agents</h3><p><strong>Hermes Agent and OpenClaw</strong> extend beyond a single repository session. Their value comes from persistent memory, remote operation, messaging integrations, and broader personal-agent workflows.</p><h3>Agent infrastructure</h3><p><strong>Portkey AI and Peezy Gateway</strong> are not primarily coding interfaces. They help route models, observe usage, enforce controls, and manage the infrastructure underneath agent systems.</p><h3>Domain-specific agents</h3><p><strong>Lemonade.gg</strong> is aimed at Roblox development. It belongs in this conversation, but comparing it directly with Claude Code is like comparing a game engine with a terminal.</p><p>Technically possible. Mostly pointless.</p><h3>The Shortlist Most Developers Actually Need</h3><p>You probably do not need to trial all 22 tools.</p><p>For most individuals and teams, the useful shortlist is much smaller.</p><h3>Cursor: The Polished Editor-First Default</h3><p>Cursor remains the easiest general recommendation for developers who want AI integrated directly into an editor.</p><p>Its strength is not one magical model. It is the packaging: repository-aware chat, code editing, agent workflows, cloud execution, subagents, pull-request review, integrations, and team controls inside one coherent product.</p><p>Cursor feels like software built for daily use rather than an agent research project that accidentally acquired a user interface.</p><p>That polish has a price. It is less open than model-agnostic alternatives, and heavy usage can become expensive. You are also accepting Cursor’s opinion about how AI-assisted development should work.</p><p>For many startups and solo developers, that is a perfectly reasonable trade.</p><p><strong>Pick Cursor when you want to install one product and become productive quickly.</strong></p><h3>Claude Code: The Strongest Terminal-First All-Rounder</h3><p>Claude Code is the clearest choice for developers who prefer the terminal and want a serious agent rather than a conversational autocomplete tool.</p><p>It can inspect repositories, modify files, execute commands, run tests, and follow project-specific instructions. More importantly, its extension surface — project instructions, skills, hooks, MCP servers, subagents, and plugins — lets teams encode how they actually work.</p><p>That matters more than another model benchmark.</p><p>The best coding agent is not merely the one that solves a fresh benchmark task. It is the one you can teach not to violate your architecture for the fifth time.</p><p>Claude Code is particularly strong when a task crosses several files and requires architectural understanding, command execution, debugging, and verification.</p><p>Its limitations are obvious: it is a Claude-centered ecosystem, and serious use can become costly.</p><p><strong>Pick Claude Code when you want a terminal agent that can become part of your engineering system.</strong></p><h3>Codex: The Strongest OpenAI-Native Multi-Agent Environment</h3><p>Codex becomes more interesting when you stop treating it as one assistant and start treating it as a command center.</p><p>Its combination of CLI, IDE, desktop, web, and cloud execution supports a different style of development: several isolated tasks can be delegated in parallel rather than forced through one long conversation.</p><p>One agent can investigate a bug. Another can implement a candidate fix. A third can add tests. A fourth can review the patch.</p><p>Of course, four agents can also produce four incompatible interpretations of the requirement. Parallelism does not magically create coordination.</p><p>Still, Codex is one of the clearest attempts to make multi-agent software work accessible to normal developers rather than only agent-framework researchers.</p><p><strong>Pick Codex when you already use OpenAI heavily and want both interactive coding and delegated cloud work.</strong></p><h3>The Open-Source Shortlist</h3><p>Open coding agents are no longer merely cheaper copies of commercial products.</p><p>They are often the better choice when model portability, local execution, approvals, extensibility, or infrastructure control matter.</p><h3>Cline: Best for Control</h3><p>Cline emphasizes human approval, provider choice, local-model support, MCP integration, CLI automation, and enterprise deployment options.</p><p>Its interface is less glossy than Cursor’s, but its control model is often more appropriate for sensitive repositories and cautious teams.</p><p>Autonomy is useful. Visible autonomy is better.</p><p><strong>Pick Cline when you want the agent to remain powerful without becoming mysterious.</strong></p><h3>OpenCode: Best for Provider Freedom</h3><p>OpenCode spans terminal, desktop, and IDE workflows while supporting a wide range of hosted and local models.</p><p>Its proposition is straightforward:</p><blockquote><em>Bring the model you prefer. Keep the harness.</em></blockquote><p>That becomes increasingly valuable when model rankings change faster than teams can rewrite their workflows.</p><p><strong>Pick OpenCode when you want a genuinely model-agnostic coding environment.</strong></p><h3>Kilo Code: Best Open Platform</h3><p>Kilo Code tries to package the openness of community tools into a broader commercial platform across VS Code, JetBrains, CLI, and cloud workflows.</p><p>Its appeal is breadth. It gives developers provider choice and an open foundation without requiring every team to assemble the entire experience from loose components.</p><p><strong>Pick Kilo Code when you want open tooling without giving up product polish.</strong></p><h3>Roo Code: Best for Configurable VS Code Workflows</h3><p>Roo Code organizes work around specialized modes such as architecture, coding, debugging, and orchestration.</p><p>That separation is useful. Designing a system, investigating a failure, and implementing a small patch should not all use the same behavior and permissions.</p><p><strong>Pick Roo Code when you live in VS Code and want workflow-specific agent modes.</strong></p><h3>Pi Code: Best for Building Your Own Harness</h3><p>Pi Code is deliberately minimal and highly extensible through packages, extensions, skills, themes, custom providers, and integrations.</p><p>Most developers want a completed product.</p><p>Pi users often want a box of sharp components and permission to ignore the assembly instructions.</p><p><strong>Pick Pi Code when customizing the agent runtime sounds more interesting than simply using one.</strong></p><h3>Async Agents Require a Different Management Style</h3><p>A lot of developers say they want an autonomous coding agent.</p><p>What they actually want is autocomplete with initiative.</p><p>A genuine asynchronous agent changes the developer’s role. You must define work clearly, provide enough context, let the system operate elsewhere, and review the result instead of steering every action.</p><p>That sounds efficient because it can be efficient.</p><p>It also exposes every vague ticket your team has been pretending is a specification.</p><h3>Devin: Best for Heavier Delegation</h3><p>Devin is positioned closer to a cloud software worker than an editor assistant.</p><p>Its strengths are parallel work, long-running tasks, multi-repository context, integrations, and team-oriented delegation. It makes the most sense for migrations, investigations, backlog items, and implementation tasks that can be described clearly and reviewed afterward.</p><p>It is less attractive when you want second-by-second collaboration inside your editor.</p><p><strong>Pick Devin when your team has well-defined engineering work to delegate — not merely lots of prompts to type.</strong></p><h3>Jules: Best GitHub-Native Task-to-PR Flow</h3><p>Jules is narrower, and that is part of its appeal.</p><p>Its workflow centers on GitHub repositories, cloud execution, plans, diffs, and pull requests. The mental model is simple:</p><blockquote><em>Assign a task. Let it work. Review the PR.</em></blockquote><p><strong>Pick Jules when your development process already lives in GitHub and you want clean asynchronous automation rather than another editor.</strong></p><h3>Where the More Experimental Products Fit</h3><p>The remaining products are not necessarily worse. Most are either younger, more specialized, or built around a narrower bet.</p><p><strong>Command Code</strong> is interesting because it attempts to learn a developer’s coding “taste” from accepted, rejected, and edited changes. Should that approach mature, it could address one of the biggest weaknesses of current agents: they remember written rules better than implicit preferences.</p><p><strong>Antigravity</strong> treats agent orchestration as a first-class development surface. It is worth watching when you are more interested in supervising specialized agents than adding another chat panel to an editor.</p><p><strong>Kimi Code</strong> is compelling for Moonshot users, long-context workflows, and developers seeking an interoperable alternative to the dominant US ecosystems.</p><p><strong>Z Code</strong> is most relevant to developers already invested in Z.ai and GLM models. Its technical direction is interesting, although its public commercial packaging is less straightforward than that of the market leaders.</p><p><strong>Grok Build</strong> is a fast-moving option for the xAI ecosystem. I would treat it as an experimental choice for non-sensitive work until its operational and privacy posture becomes easier to evaluate.</p><p><strong>Trae</strong> offers a broad AI-native editor experience and will appeal to users who want a modern alternative to Cursor, but it still feels less commercially settled.</p><p><strong>Hermes Agent</strong> is one of the most interesting options for persistent, self-hosted agents with memory, remote backends, provider flexibility, and messaging integrations. It is less of a conventional coding product and more of a foundation for an agent that continues operating beyond one repository session.</p><p><strong>OpenClaw</strong> makes the most sense when you want to reach and operate agents through applications such as Slack, Telegram, Discord, WhatsApp, or Teams. It should be evaluated as a cross-application agent gateway, not as an IDE competitor.</p><p><strong>Peezy Gateway</strong> is for builders who want flexible model access and pricing control behind their own tools.</p><p><strong>Portkey AI</strong> is for organizations whose problem has evolved from “Which agent should we use?” to “How do we govern all the agents people are already using?”</p><p><strong>Lemonade.gg</strong> is for Roblox creators. For everyone else, it is not part of the shortlist.</p><h3>The Benchmark Trap</h3><p>Coding benchmarks are useful.</p><p>They are also one of the easiest ways to make a bad purchase look scientific.</p><p>SWE-bench, Terminal-Bench, and other evaluations measure different slices of the problem. Some try to isolate model capability under a shared harness. Others evaluate a complete agent stack with tools, runtime settings, cost, latency, and task limits.</p><p>Those results answer different questions.</p><p>A high benchmark score does not tell you:</p><ul><li>Whether the agent follows your repository conventions</li><li>Whether its approvals are tolerable</li><li>Whether it can work with your issue tracker</li><li>Whether your team trusts its cloud environment</li><li>Whether its edits are easy to review</li><li>Whether it becomes painfully expensive under real usage</li><li>Whether developers enjoy using it eight hours a day</li></ul><p>Benchmarks help estimate the ceiling.</p><p>Workflow determines whether you ever reach it.</p><h3>What I Would Choose</h3><p>Here is the shortest honest buying guide I can give.</p><h3>I am a solo developer who wants the smoothest experience</h3><p>Choose <strong>Cursor</strong>.</p><p>Choose <strong>Claude Code</strong> instead when you prefer the terminal and want deeper extensibility.</p><h3>I want open source and provider choice</h3><p>Start with <strong>Cline, OpenCode, and Kilo Code</strong>.</p><p>Choose Cline for control, OpenCode for model freedom, and Kilo Code for the broadest packaged platform.</p><h3>I want agents to work while I do something else</h3><p>Choose <strong>Codex, Devin, or Jules</strong>.</p><p>Codex offers the broadest multi-surface environment. Devin is built for heavier delegation. Jules provides the cleanest GitHub-native task-to-PR workflow.</p><h3>I am standardizing an enterprise</h3><p>Evaluate <strong>Claude Code, Codex, Kiro, Cline, and Portkey AI</strong>.</p><p>The first four address developer workflows. Portkey addresses the governance problem that arrives once several teams adopt several agents.</p><h3>I am researching or building agent systems</h3><p>Look closely at <strong>Pi Code, Hermes Agent, Antigravity, and OpenClaw</strong>.</p><p>They expose more interesting ideas around extensibility, persistence, orchestration, and cross-application operation than a conventional AI editor.</p><h3>The Four Questions That Matter</h3><p>Before buying anything, answer these:</p><h3>1. Where should the agent work?</h3><p>Inside your editor, inside your terminal, in a cloud sandbox, or across messaging apps?</p><h3>2. How much control do you need?</h3><p>Can the agent edit and execute freely, or must every meaningful action be approved?</p><h3>3. How important is provider portability?</h3><p>Are you comfortable building around one model company, or do you want to swap providers and run local models?</p><h3>4. Are you buying a coding tool or an agent platform?</h3><p>One improves an individual developer’s workflow.</p><p>The other coordinates workers, infrastructure, policies, and organizational knowledge.</p><p>Confusing those two purchases is how teams end up paying for an impressive system nobody enjoys using.</p><h3>The Bottom Line</h3><p>There is no universal winner because “AI coding harness” now covers several different products pretending to belong to one category.</p><p>For editor-first development, <strong>Cursor</strong> is the safest default.</p><p>For terminal-first engineering, <strong>Claude Code</strong> is the strongest all-rounder.</p><p>For OpenAI-native multi-agent work, <strong>Codex</strong> is the obvious starting point.</p><p>For open ecosystems, shortlist <strong>Cline, OpenCode, and Kilo Code</strong>.</p><p>For delegated cloud work, compare <strong>Devin and Jules</strong>.</p><p>For agent governance, evaluate <strong>Portkey AI</strong>.</p><p>For people who want to build the harness rather than accept somebody else’s design, use <strong>Pi Code or Hermes Agent</strong>.</p><p>The mistake is not choosing the second-best model.</p><p>The mistake is choosing a product built for a completely different way of working.</p><p>Pick the workflow first.</p><p>Then pick the harness.</p><p>Only then should you argue about the model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4efb26650fcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating Inkling: The Open-Weight MoE with Continuous Reasoning Effort]]></title>
            <link>https://medium.com/@mshojaei77/evaluating-inkling-the-open-weight-moe-with-continuous-reasoning-effort-3883cebbfa92?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3883cebbfa92</guid>
            <category><![CDATA[inklings]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 12:28:49 GMT</pubDate>
            <atom:updated>2026-07-16T12:28:49.717Z</atom:updated>
            <content:encoded><![CDATA[<p>A builder-focused breakdown of Thinking Machines’ first model release, its native audio pipeline, and the operational reality of running a 1.9 TB checkpoint.</p><h3>The short version</h3><p>Thinking Machines Lab released Inkling on July 15, 2026. It is a <strong>975B-parameter sparse Mixture-of-Experts (MoE) with 41B active parameters</strong>, featuring a <strong>1-million-token architectural context window</strong>, native text/image/audio processing, and Apache 2.0-licensed weights in both BF16 and NVIDIA NVFP4 formats.</p><p>If you are looking for a model that beats every frontier closed model across the board, this is not it. It lags behind closed endpoints like GPT-5.6 Sol and Claude Fable 5, and it fails to beat top Chinese open-weight models like GLM 5.2 and Kimi K2.6 on raw reasoning benchmarks.</p><p>The actual value proposition of Inkling is three-fold:</p><ol><li><strong>Commercially usable, open-weight architecture</strong> that is highly customizable.</li><li><strong>Native, encoder-free audio and visual reasoning</strong> that treats audio and image patches as direct token streams.</li><li><strong>Continuous reasoning effort conditioning</strong>, allowing you to dynamically throttle inference cost, latency, and reasoning depth using a scalar input between 0 and 1.</li></ol><p>The catch is simple: the model is massive. A 1.9 TB BF16 download is not something you run on a workstation or a single node of H100s. Inkling-Small (276B/12B active) promises similar reasoning capabilities at a fraction of the cost, but its weights are not yet downloadable — it remains a vendor-reported preview.</p><h3>What the source actually says</h3><p>The model configuration and launch details reveal a highly optimized, heterogeneous architecture that draws heavily from modern sparse-MoE design patterns.</p><h3>MoE Routing and Token Path</h3><p>Inkling’s routing mirrors the DeepSeek-V3 approach rather than traditional GShard setups:</p><ul><li><strong>Routed Experts:</strong> 256 per MoE layer, with 6 selected per token via sigmoid routing.</li><li><strong>Shared Experts:</strong> 2 active on every token, meaning each token runs through 8 total expert pathways (6 routed + 2 shared).</li><li><strong>Load Balancing:</strong> Uses an auxiliary-loss-free routing bias to balance expert loads without degrading representation quality.</li><li><strong>MLP Exceptions:</strong> Layer 2 is a dense MLP (intermediate dimension of 24,576) rather than an MoE layer. Regular sparse experts have an intermediate dimension of 3,072.</li></ul><h3>Positional Representations and Attention Block</h3><p>The attention structure uses a hybrid local/global approach across 66 layers, maintaining a <strong>5:1 ratio</strong> (55 local sliding-window layers and 11 global layers).</p><ul><li><strong>Global Attention:</strong> Uses 8 KV heads.</li><li><strong>Local Attention:</strong> Uses 16 KV heads with a 512-token sliding window.</li><li><strong>Positional Encoding:</strong> Inkling completely swaps out RoPE (Rotary Position Embeddings) for relative positional representations, which the lab claims improves sequence extrapolation up to the 1M limit.</li></ul><p>One highly specific architectural quirk is the insertion of <strong>short convolutions (kernel size 4)</strong>. These are placed after key/value projections and on the attention and MLP residual outputs before they rejoin the residual stream. This is great for local token coherence but makes writing custom Triton kernels for this model an absolute nightmare.</p><h3>Modality Tokenization</h3><p>Rather than stitching a massive, frozen ViT or Whisper model to the LLM via a linear projection, Inkling processes image and audio inputs directly inside the autoregressive decoder:</p><ul><li><strong>Vision (hMLP):</strong> Images are sliced into 40×40-pixel patches and put through a 4-layer hierarchical MLP.</li><li><strong>Audio (dMel):</strong> Audio is processed using discrete mel-filterbank values (80 mel bins, 16 quantization values, ranging from -7 to 2). The raw audio is resampled and tokenized locally on the client using the tml-renderers package before the resulting Mel tokens are appended to the main prompt stream.</li><li><strong>Video:</strong> While the architecture contains temporal patching (temporal patch size of 2) and was trained on video, the launch-day APIs and recipes only support static images and audio. It is a video-capable architecture, but not yet a video product.</li></ul><h3>The useful technical idea: Continuous reasoning effort</h3><p>The most practical idea in this release is the continuous reasoning scalar, passing a float value in [0, 1) to the model.</p><p>During RL post-training (which spanned over 30 million rollouts), Thinking Machines conditioned the model on different target compute/reasoning budgets. Instead of having a discrete “thinking mode” that you toggle on or off, you can adjust the effort dynamically:</p><pre># Conceptual payload for an Inkling endpoint<br>payload = {<br>    &quot;model&quot;: &quot;thinkingmachines/Inkling&quot;,<br>    &quot;prompt&quot;: &quot;Optimize this sparse matrix multiplication kernel for CUDA.&quot;,<br>    &quot;effort&quot;: 0.90,  # High reasoning effort for complex coding<br>    &quot;temperature&quot;: 1.0<br>}</pre><p>If you are running a multi-agent system, this lets you set up an automated router:</p><ul><li>For routing, classification, or simple parsing tasks, set effort to 0.10 or 0.20.</li><li>For code generation, mathematical verification, or deep document analysis, scale up to 0.90 or 0.99.</li></ul><p>According to the launch metrics, this throttling actually works. The model can match Nemotron 3 Ultra on Terminal Bench while generating approximately one-third as many tokens when the effort slider is dialed down, compressing its internal reasoning traces under low-compute pressures.</p><h3>What I would actually use</h3><p>If you have the hardware to serve it, the immediate win for Inkling is <strong>native multimodal agent workflows</strong> — specifically tasks that combine visual document parsing (PDFs, schematics) with audio transcripts or spoken instructions.</p><p>Because SGLang and vLLM have day-one integration work, you can stand this up on a multi-node cluster. Here is how I would configure SGLang to run the Blackwell-optimized NVFP4 quantized weights:</p><pre># SGLang launch command for Inkling NVFP4<br>pip install &quot;sglang[all] @ git+https://github.com/sgl-project/sglang.git@inkling-support&quot;<br><br>sglang serve \<br>  --trust-remote-code \<br>  --model-path thinkingmachines/Inkling-NVFP4 \<br>  --tp 8 \<br>  --quantization modelopt_fp4 \<br>  --attention-backend fa4 \<br>  --moe-runner-backend flashinfer_trtllm_routed \<br>  --enable-multimodal \<br>  --reasoning-parser inkling \<br>  --tool-call-parser inkling</pre><h3>Development Guidelines for Integration</h3><ol><li><strong>Local Media Rendering:</strong> Do not pass remote image or audio URLs directly in the API payload. The custom tml-renderers package requires local downloading, resampling (audio must be mono 16 kHz), and Mel conversion before passing the token payload to the model.</li><li><strong>LoRA Prefill Constraints:</strong> If you plan on deploying custom adapters via Tinker or local training, be aware that SGLang currently requires you to disable prefill CUDA graphs when LoRA is active to prevent silent memory allocation crashes.</li><li><strong>MTP Speculative Decoding:</strong> The checkpoint contains 8 chained next-token-prediction (MTP) layers designed for speculative decoding. However, launch-day serving frameworks do not fully support these yet. Keep this in mind when budgeting your token-per-second expectations; there is latent speed waiting to be unlocked by framework updates.</li></ol><h3>The annoying details</h3><p>Let’s talk about the friction points you will hit the moment you pull this model from Hugging Face.</p><h3>The Memory Footprint</h3><p>A 1.9 TB download in BF16 format translates to roughly 2 TB of aggregate VRAM required just to load the model weights. To run this at scale, you are looking at a minimum of 8x H200s or a clustered multi-node setup.</p><p>Even if you drop to NVFP4, you still need roughly 600 GB of aggregate VRAM. This quant is explicitly optimized for Blackwell (B200/GB200) FP4 engines; running NVFP4 on older Hopper or Ada architectures will hit slower emulation kernels, destroying your inference latency.</p><h3>Integration Stability</h3><p>“Day-zero support” is a marketing phrase. The actual GitHub commits show a flurry of immediate patches:</p><ul><li>SGLang’s remote quantization configurations originally failed to load.</li><li>Reasoning effort parameters were rounded incorrectly and silently dropped in certain Responses API routes.</li><li>vLLM’s initial implementation lacked LoRA support, MTP execution, and piecewise CUDA graphs.</li><li>Multimodal placeholder tokens for audio and images were initially mapped incorrectly, leading to immediate feature-extraction failures in early Transformers versions.</li></ul><p>If you are shipping this to production, pin a specific, validated Docker container or commit hash. Do not pull nightly SGLang or vLLM images blindly.</p><h3>The Quantization Trap</h3><p>Unsloth released an experimental 1-bit quantization that compresses the model down to 270 GB, allowing it to run on a mix of RAM and VRAM. However, their reported Top-1 quality score fell to 74.2%. The benchmark parameters for that evaluation are poorly documented, and you should assume that extreme quantization aggressively degrades the fragile routing behavior of a 256-expert MoE.</p><h3>Limitations</h3><p>Before you swap out your current API endpoints, look at what the benchmarks actually tell us.</p><h3>1. Factual Recall is Poor</h3><p>For a model with nearly a trillion total parameters, Inkling is surprisingly bad at simple factual recall. On <strong>SimpleQA</strong>, it scores only <strong>43.9%</strong>. On <strong>AA Omniscience</strong>, it sits near <strong>2.1%</strong>.</p><p>For comparison, Gemini 3.1 Pro scores 77.3% on SimpleQA, and Claude Fable 5 scores 68.3%. Inkling will confidently hallucinate factual details. Do not use this model without a tightly coupled search or RAG pipeline.</p><h3>2. Best American Open Model ≠ Best Open Model</h3><p>While Inkling is arguably the strongest US-developed open-weight generalist at launch, it does not hold the global crown.</p><ul><li><strong>GLM 5.2</strong> beats Inkling on almost every critical reasoning and agentic benchmark: HLE, GPQA, SWE-bench Pro, Terminal Bench, and GDPVal.</li><li><strong>Kimi K2.6 (and K3 soon) </strong>leads Inkling on hard coding, visual reasoning, and general agent tasks.</li></ul><p>The performance gap on Terminal Bench is telling: Inkling scores 63.8%, while GLM 5.2 achieves 82.7% and Kimi K2.6 reaches 71.3%.</p><h3>3. Unknown Data Composition</h3><p>Thinking Machines claims a pretraining volume of 45 trillion tokens, but their documentation is completely opaque regarding the actual data distribution. There is no information on the ratio of synthetic data used, language breakdowns, code percentages, or decontamination processes.</p><h3>4. Inkling-Small is Still Vaporware</h3><p>The benchmark numbers for Inkling-Small (276B/12B active) look incredibly promising, keeping pace with the large model on GPQA, HLE-tools, and CharXiv+Python.</p><p>But as of right now, you cannot download it, audit it, or host it. It is a vendor-reported preview. Until those weights are on Hugging Face, build your pipelines assuming you only have the giant 1.9 TB model to work with.</p><h3>Final takeaway</h3><p>Inkling is a highly capable foundation model if your engineering goal is to run, modify, and own your model weights — particularly for agentic workflows involving speech-to-text and visual documents.</p><p>However, if your primary metric is raw reasoning capacity per dollar of inference, Chinese open-weight models still hold the advantage. And if your infrastructure budget cannot support clustering multiple high-memory GPU nodes, you are better off waiting to see if the downloadable weights of Inkling-Small actually live up to the preview benchmarks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3883cebbfa92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an Academic Research Agent with LangGraph]]></title>
            <link>https://medium.com/@mshojaei77/how-to-build-an-academic-research-agent-with-langgraph-42274bc3cd02?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/42274bc3cd02</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[academic]]></category>
            <category><![CDATA[deep-research]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 17:39:09 GMT</pubDate>
            <atom:updated>2026-07-06T17:39:09.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to build a reliable academic research agent using LangGraph. Implement deterministic citation validation, novelty checks, and human-in-the-loop interrupts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0kJiRubBOFOogkBeCtb5w.png" /><figcaption>Academic Research Agent with LangGraph</figcaption></figure><h3>The honest target</h3><p>Build <strong>one LangGraph Academic Research Agent</strong> that acts like a disciplined research operating system: it searches, validates, drafts, checks, and packages the paper, but <strong>humans approve the research question, methodology, analysis, journal target, and final submission</strong>. That matters because publishers allow responsible AI support, but humans remain responsible for accuracy, originality, plagiarism, authorship, and final content.</p><h3>1. Core architecture: one agent, many gates</h3><p>LangGraph is a good fit because it models workflows as <strong>state + nodes + edges</strong>, and it supports durable execution, persistence, and human-in-the-loop pauses.</p><p>Use <strong>one graph</strong>:</p><pre>AcademicResearchAgent<br>│<br>├─ Intake / research question normalization<br>├─ Protocol builder<br>├─ HUMAN APPROVAL: protocol<br>├─ Literature search<br>├─ Citation validation<br>├─ Novelty / gap analysis<br>├─ VALIDATION GATE: novelty<br>├─ Methodology planner<br>├─ HUMAN APPROVAL: methodology<br>├─ Data / experiment / analysis runner<br>├─ VALIDATION GATE: results + reproducibility<br>├─ Journal targeting<br>├─ HUMAN APPROVAL: target journal<br>├─ Manuscript drafter<br>├─ Integrity + reporting checklist gate<br>├─ Submission package generator<br>└─ HUMAN APPROVAL: final package</pre><p>The important trick: <strong>LLM nodes can write and reason, but validation gates should be deterministic where possible</strong>. Use APIs, schemas, checklists, statistical scripts, DOI resolvers, journal policy fetchers, and human approvals. This is the difference between a cute demo and something you can trust near publication.</p><h3>2. What the agent should validate</h3><h3>Gate A — Research question / protocol</h3><p>The agent should block progress unless the protocol has:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xO9O9SIZrXnPS0IxisIrVQ.png" /><figcaption>Gate A — Research question / protocol</figcaption></figure><p>For health and biomedical work, the reporting guideline should be chosen early: <strong>PRISMA </strong>for systematic reviews, <strong>CONSORT </strong>for randomized trials, and <strong>STROBE </strong>for observational studies are maintained in reporting-guideline ecosystems such as EQUATOR and their official guideline sites.</p><h3>Gate B — Citation validation</h3><p>The agent must never trust LLM-generated references. Recent evidence shows hallucinated citations are a real publication-integrity problem, including a 2026 large-scale estimate of many non-existent references appearing in scientific papers. (<a href="https://www.nature.com/articles/d41586-026-00969-z">Nature</a>)</p><p>For every citation, require:</p><pre>title match<br>author match<br>year match<br>journal/venue match<br>DOI or PMID or arXiv ID or official landing page<br>claim-to-source support</pre><p>Use Crossref for DOI metadata, OpenAlex for works/authors/sources, Semantic Scholar for paper/citation discovery, and PubMed/NCBI E-utilities for biomedical literature. (<a href="https://www.crossref.org/documentation/retrieve-metadata/rest-api/">www.crossref.org</a>)</p><h3>Gate C — Novelty</h3><p>The agent should not say “novel” unless it has searched:</p><pre>recent papers: last 2–3 years<br>seminal papers<br>review papers<br>target journal archive<br>competing methods<br>negative / failed results<br>datasets and benchmarks<br>patents if relevant<br>preprints if relevant</pre><p>A good novelty score should be conservative:</p><pre>0 = already done<br>1 = minor application<br>2 = useful extension<br>3 = clear methodological contribution<br>4 = strong cross-field contribution<br>5 = field-shifting contribution</pre><p>Anything below 3 should trigger a redesign loop before manuscript drafting.</p><h3>Gate D — Methodology</h3><p>This is the Q1 killer gate. The agent should block if methods are vague.</p><p>For empirical work, require:</p><pre>hypotheses<br>dataset provenance<br>sample size or power reasoning<br>baseline selection<br>evaluation metrics<br>statistical tests<br>ablation plan<br>error analysis<br>robustness checks<br>limitations<br>reproducibility package</pre><p>For systematic reviews, require database list, search strings, screening process, inclusion/exclusion rules, risk-of-bias approach, extraction schema, and PRISMA checklist. PRISMA 2020 includes checklist and expanded checklist materials for systematic reviews. (<a href="https://www.prisma-statement.org/prisma-2020-checklist">PRISMA statement)</a></p><h3>Gate E — Journal fit</h3><p>Use journal finders only for candidates, not final truth. Elsevier, Springer Nature, Wiley, JANE, IEEE, and MDPI all provide journal-matching or publication-recommender tools, while Scopus Sources and JCR/SJR-style tools should be used to verify indexing/ranking/subject fit. (<a href="https://journalfinder.elsevier.com/">journalfinder.elsevier.com</a>)</p><p>The journal-fit gate should check:</p><pre>aims and scope match<br>article type accepted<br>word limit<br>figure/table limits<br>reference style<br>AI-use policy<br>data availability policy<br>ethics policy<br>open-access/APC requirement<br>JCR/SJR/Scopus/WoS status<br>recent papers from that journal cited where relevant</pre><h3>Gate F — Integrity and publisher compliance</h3><p>The agent should check originality, no simultaneous submission, third-party permissions, AI disclosure, conflict of interest, funding, ethics approval, and data availability. Elsevier and Springer Nature explicitly require originality and prohibit simultaneous consideration/publication in normal cases; IEEE also requires original work not under review elsewhere. (<a href="https://www.elsevier.com/en-gb/researcher/author/policies-and-guidelines">www.elsevier.com</a>)</p><p>Elsevier gives a concrete AI-use declaration pattern: disclose the tool, purpose, human review/editing, and author responsibility. (<a href="https://www.elsevier.com/about/policies-and-standards/generative-ai-policies-for-journals">www.elsevier.com</a>)</p><h3>3. LangGraph implementation skeleton</h3><p>This is the minimum shape I’d build.</p><pre>from __future__ import annotations<br>from typing import TypedDict, Literal, NotRequired, Any<br>from langgraph.graph import StateGraph, START, END<br>from langgraph.types import Command, interrupt<br>from langgraph.checkpoint.memory import InMemorySaver<br>Decision = Literal[&quot;approve&quot;, &quot;revise&quot;, &quot;reject&quot;<br>]<br>class GateReport(TypedDict):<br>    name: str<br>    passed: bool<br>    score: float<br>    issues: list[str]<br>    required_fixes: list[str]<br>class CitationRecord(TypedDict):<br>    raw_reference: str<br>    doi: NotRequired[str]<br>    pmid: NotRequired[str]<br>    title: str<br>    authors: list[str]<br>    year: int<br>    venue: str<br>    verified: bool<br>    supports_claims: list[str]<br>    problems: list[str]<br><br>class AcademicState(TypedDict, total=False):<br>    user_goal: str<br>    field: str<br>    study_type: str<br>    target_journal_candidates: list[dict[str, Any]]<br>    protocol: dict[str, Any]<br>    literature_queries: list[str]<br>    retrieved_papers: list[dict[str, Any]]<br>    citations: list[CitationRecord]<br>    evidence_table: list[dict[str, Any]]<br>    novelty_report: GateReport<br>    methodology_report: GateReport<br>    reproducibility_report: GateReport<br>    integrity_report: GateReport<br>    journal_fit_report: GateReport<br>    methods_plan: dict[str, Any]<br>    analysis_outputs: dict[str, Any]<br>    manuscript: dict[str, str]<br>    submission_package: dict[str, Any]<br>    audit_log: list[str]<br>    status: str</pre><p>LangGraph interrupts are the correct mechanism for human approval because they pause graph execution, save state through persistence, and resume only when a human response is provided. (<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fdocs.langchain.com%2Foss%2Fpython%2Flanggraph%2Finterrupts">Docs by LangChain</a>)</p><pre>def require_human_approval(<br>    state: AcademicState,<br>    gate_name: str,<br>    payload: dict[str, Any],<br>) -&gt; dict[str, Any]:<br>    review = interrupt({<br>        &quot;gate&quot;: gate_name,<br>        &quot;instruction&quot;: &quot;Review this output. Choose approve, revise, or reject.&quot;,<br>        &quot;payload&quot;: payload,<br>        &quot;allowed_decisions&quot;: [&quot;approve&quot;, &quot;revise&quot;, &quot;reject&quot;],<br>    })<br>decision: Decision = review[&quot;decision&quot;]<br>    notes = review.get(&quot;notes&quot;, &quot;&quot;)<br>    if decision == &quot;reject&quot;:<br>        return {<br>            &quot;status&quot;: f&quot;rejected_at_{gate_name}&quot;,<br>            &quot;audit_log&quot;: state.get(&quot;audit_log&quot;, []) + [f&quot;{gate_name}: rejected - {notes}&quot;],<br>        }<br>    if decision == &quot;revise&quot;:<br>        return {<br>            &quot;status&quot;: f&quot;revise_{gate_name}&quot;,<br>            &quot;audit_log&quot;: state.get(&quot;audit_log&quot;, []) + [f&quot;{gate_name}: revise - {notes}&quot;],<br>        }<br>    return {<br>        &quot;status&quot;: f&quot;approved_{gate_name}&quot;,<br>        &quot;audit_log&quot;: state.get(&quot;audit_log&quot;, []) + [f&quot;{gate_name}: approved - {notes}&quot;],<br>    }</pre><h3>4. Nodes</h3><h3>Intake node</h3><pre>def intake_node(state: AcademicState) -&gt; AcademicState:<br>    # Replace with structured LLM extraction.<br>    # Output must be JSON validated by Pydantic in production.<br>    return {<br>        **state,<br>        &quot;field&quot;: state.get(&quot;field&quot;, &quot;unknown&quot;),<br>        &quot;study_type&quot;: state.get(&quot;study_type&quot;, &quot;unknown&quot;),<br>        &quot;status&quot;: &quot;intake_complete&quot;,<br>    }</pre><h3>Protocol builder</h3><pre>def protocol_node(state: AcademicState) -&gt; AcademicState:<br>    protocol = {<br>        &quot;research_question&quot;: state[&quot;user_goal&quot;],<br>        &quot;study_type&quot;: state.get(&quot;study_type&quot;),<br>        &quot;inclusion_criteria&quot;: [],<br>        &quot;exclusion_criteria&quot;: [],<br>        &quot;data_sources&quot;: [],<br>        &quot;analysis_plan&quot;: [],<br>        &quot;ethics_flags&quot;: [],<br>        &quot;reporting_guideline&quot;: None,<br>    }<br>return {<br>        **state,<br>        &quot;protocol&quot;: protocol,<br>        &quot;status&quot;: &quot;protocol_drafted&quot;,<br>    }<br><br>def protocol_human_gate_node(state: AcademicState) -&gt; AcademicState:<br>    return {<br>        **state,<br>        **require_human_approval(<br>            state,<br>            &quot;protocol&quot;,<br>            {&quot;protocol&quot;: state[&quot;protocol&quot;]},<br>        ),<br>    }</pre><h3>Literature search node</h3><pre>def literature_search_node(state: AcademicState) -&gt; AcademicState:<br>    queries = [<br>        state[&quot;protocol&quot;][&quot;research_question&quot;],<br>        f&quot;{state[&#39;protocol&#39;][&#39;research_question&#39;]} systematic review&quot;,<br>        f&quot;{state[&#39;protocol&#39;][&#39;research_question&#39;]} latest methods&quot;,<br>        f&quot;{state[&#39;protocol&#39;][&#39;research_question&#39;]} benchmark dataset&quot;,<br>    ]<br># Production:<br>    # - OpenAlex search<br>    # - Semantic Scholar search<br>    # - PubMed if biomedical<br>    # - Crossref metadata resolution<br>    # - target journal archive search<br>    return {<br>        **state,<br>        &quot;literature_queries&quot;: queries,<br>        &quot;retrieved_papers&quot;: [],<br>        &quot;status&quot;: &quot;literature_search_complete&quot;,<br>    }</pre><h3>Citation validation node</h3><pre>def citation_validation_node(state: AcademicState) -&gt; AcademicState:<br>    citations = state.get(&quot;citations&quot;, [])<br>verified = []<br>    problems = []<br>    for c in citations:<br>        # Production:<br>        # 1. Resolve DOI in Crossref.<br>        # 2. Match title/year/authors.<br>        # 3. Verify source actually supports the attached claim.<br>        # 4. Reject citation if metadata or claim support fails.<br>        if not c.get(&quot;doi&quot;) and not c.get(&quot;pmid&quot;):<br>            c[&quot;verified&quot;] = False<br>            c[&quot;problems&quot;] = c.get(&quot;problems&quot;, []) + [&quot;Missing DOI/PMID/official identifier&quot;]<br>            problems.append(c[&quot;raw_reference&quot;])<br>        verified.append(c)<br>    return {<br>        **state,<br>        &quot;citations&quot;: verified,<br>        &quot;integrity_report&quot;: {<br>            &quot;name&quot;: &quot;citation_validation&quot;,<br>            &quot;passed&quot;: len(problems) == 0,<br>            &quot;score&quot;: 1.0 if len(problems) == 0 else 0.0,<br>            &quot;issues&quot;: problems,<br>            &quot;required_fixes&quot;: [&quot;Replace or remove every unverified citation&quot;],<br>        },<br>        &quot;status&quot;: &quot;citations_validated&quot;,<br>    }</pre><h3>Novelty gate</h3><pre>def novelty_gate_node(state: AcademicState) -&gt; AcademicState:<br>    # Production:<br>    # - compare against retrieved papers<br>    # - cluster prior work<br>    # - identify &quot;already done&quot; claims<br>    # - require explicit contribution delta<br>    # - run adversarial prior-art search<br>    report: GateReport = {<br>        &quot;name&quot;: &quot;novelty&quot;,<br>        &quot;passed&quot;: False,<br>        &quot;score&quot;: 0.0,<br>        &quot;issues&quot;: [&quot;Novelty scoring not implemented yet&quot;],<br>        &quot;required_fixes&quot;: [&quot;Implement prior-art comparison before drafting&quot;],<br>    }<br>  return {<br>          **state,<br>          &quot;novelty_report&quot;: report,<br>          &quot;status&quot;: &quot;novelty_checked&quot;,<br>      }<br><br>def route_after_novelty(state: AcademicState) -&gt; str:<br>    report = state[&quot;novelty_report&quot;]<br>    if report[&quot;passed&quot;]:<br>        return &quot;methodology&quot;<br>    return &quot;repair_research_question&quot;<br><br>def repair_research_question_node(state: AcademicState) -&gt; AcademicState:<br>    return {<br>        **state,<br>        &quot;status&quot;: &quot;needs_research_question_revision&quot;,<br>        &quot;audit_log&quot;: state.get(&quot;audit_log&quot;, []) + [<br>            &quot;Novelty gate failed; research question must be narrowed, reframed, or strengthened.&quot;<br>        ],<br>    }</pre><h3>Methodology gate</h3><pre>def methodology_node(state: AcademicState) -&gt; AcademicState:<br>    methods_plan = {<br>        &quot;design&quot;: None,<br>        &quot;data&quot;: None,<br>        &quot;baselines&quot;: [],<br>        &quot;metrics&quot;: [],<br>        &quot;statistical_tests&quot;: [],<br>        &quot;ablation_plan&quot;: [],<br>        &quot;reproducibility&quot;: {<br>            &quot;code&quot;: True,<br>            &quot;data_dictionary&quot;: True,<br>            &quot;environment_file&quot;: True,<br>            &quot;random_seed&quot;: True,<br>        },<br>    }<br>report: GateReport = {<br>        &quot;name&quot;: &quot;methodology&quot;,<br>        &quot;passed&quot;: False,<br>        &quot;score&quot;: 0.4,<br>        &quot;issues&quot;: [&quot;Methods plan is incomplete&quot;],<br>        &quot;required_fixes&quot;: [<br>            &quot;Specify data source&quot;,<br>            &quot;Specify baseline methods&quot;,<br>            &quot;Specify evaluation metrics&quot;,<br>            &quot;Specify statistical tests&quot;,<br>        ],<br>    }<br>    return {<br>        **state,<br>        &quot;methods_plan&quot;: methods_plan,<br>        &quot;methodology_report&quot;: report,<br>        &quot;status&quot;: &quot;methodology_drafted&quot;,<br>    }<br><br>def methodology_human_gate_node(state: AcademicState) -&gt; AcademicState:<br>    return {<br>        **state,<br>        **require_human_approval(<br>            state,<br>            &quot;methodology&quot;,<br>            {<br>                &quot;methods_plan&quot;: state[&quot;methods_plan&quot;],<br>                &quot;methodology_report&quot;: state[&quot;methodology_report&quot;],<br>            },<br>        ),<br>    }</pre><h3>Journal fit node</h3><pre>def journal_fit_node(state: AcademicState) -&gt; AcademicState:<br>    # Production:<br>    # - Query Elsevier/Springer/Wiley/JANE/IEEE/MDPI manually or via allowed APIs where available.<br>    # - Verify journal in JCR, Scopus Sources, SJR, or publisher site.<br>    # - Fetch author guidelines.<br>    # - Extract article type, word limit, figure limits, reference style, AI policy.<br>    report: GateReport = {<br>        &quot;name&quot;: &quot;journal_fit&quot;,<br>        &quot;passed&quot;: False,<br>        &quot;score&quot;: 0.0,<br>        &quot;issues&quot;: [&quot;No verified target journal selected&quot;],<br>        &quot;required_fixes&quot;: [&quot;Select 3–5 candidate journals and verify scope/indexing/guidelines&quot;],<br>    }<br>  return {<br>          **state,<br>          &quot;journal_fit_report&quot;: report,<br>          &quot;status&quot;: &quot;journal_fit_checked&quot;,<br>      }<br>  <br>def journal_human_gate_node(state: AcademicState) -&gt; AcademicState:<br>    return {<br>        **state,<br>        **require_human_approval(<br>            state,<br>            &quot;target_journal&quot;,<br>            {<br>                &quot;candidates&quot;: state.get(&quot;target_journal_candidates&quot;, []),<br>                &quot;journal_fit_report&quot;: state[&quot;journal_fit_report&quot;],<br>            },<br>        ),<br>    }</pre><h3>Manuscript + package generation</h3><pre>def manuscript_node(state: AcademicState) -&gt; AcademicState:<br>    manuscript = {<br>        &quot;title&quot;: &quot;&quot;,<br>        &quot;abstract&quot;: &quot;&quot;,<br>        &quot;introduction&quot;: &quot;&quot;,<br>        &quot;methods&quot;: &quot;&quot;,<br>        &quot;results&quot;: &quot;&quot;,<br>        &quot;discussion&quot;: &quot;&quot;,<br>        &quot;limitations&quot;: &quot;&quot;,<br>        &quot;conclusion&quot;: &quot;&quot;,<br>        &quot;references&quot;: &quot;&quot;,<br>        &quot;ai_use_disclosure&quot;: &quot;&quot;,<br>    }<br><br>return {<br>        **state,<br>        &quot;manuscript&quot;: manuscript,<br>        &quot;status&quot;: &quot;manuscript_drafted&quot;,<br>    }<br><br>def submission_package_node(state: AcademicState) -&gt; AcademicState:<br>    package = {<br>        &quot;manuscript&quot;: state[&quot;manuscript&quot;],<br>        &quot;cover_letter&quot;: &quot;&quot;,<br>        &quot;highlights&quot;: [],<br>        &quot;graphical_abstract_brief&quot;: &quot;&quot;,<br>        &quot;author_contribution_statement&quot;: &quot;&quot;,<br>        &quot;conflict_of_interest_statement&quot;: &quot;&quot;,<br>        &quot;funding_statement&quot;: &quot;&quot;,<br>        &quot;data_availability_statement&quot;: &quot;&quot;,<br>        &quot;ethics_approval_statement&quot;: &quot;&quot;,<br>        &quot;ai_use_disclosure&quot;: &quot;&quot;,<br>        &quot;reporting_checklist&quot;: &quot;&quot;,<br>        &quot;supplementary_files&quot;: [],<br>        &quot;reproducibility_package&quot;: [],<br>        &quot;reviewer_suggestion_list&quot;: [],<br>        &quot;response_to_review_template&quot;: &quot;&quot;,<br>    }<br>    return {<br>        **state,<br>        &quot;submission_package&quot;: package,<br>        &quot;status&quot;: &quot;submission_package_drafted&quot;,<br>    }<br><br>def final_human_gate_node(state: AcademicState) -&gt; AcademicState:<br>    return {<br>        **state,<br>        **require_human_approval(<br>            state,<br>            &quot;final_submission_package&quot;,<br>            state[&quot;submission_package&quot;],<br>        ),<br>    }</pre><h3>Build graph</h3><pre>def build_graph():<br>    builder = StateGraph(AcademicState)<br>    builder.add_node(&quot;intake&quot;, intake_node)<br>    builder.add_node(&quot;protocol&quot;, protocol_node)<br>    builder.add_node(&quot;protocol_human_gate&quot;, protocol_human_gate_node)<br>    builder.add_node(&quot;literature_search&quot;, literature_search_node)<br>    builder.add_node(&quot;citation_validation&quot;, citation_validation_node)<br>    builder.add_node(&quot;novelty_gate&quot;, novelty_gate_node)<br>    builder.add_node(&quot;repair_research_question&quot;, repair_research_question_node)<br>    builder.add_node(&quot;methodology&quot;, methodology_node)<br>    builder.add_node(&quot;methodology_human_gate&quot;, methodology_human_gate_node)<br>    builder.add_node(&quot;journal_fit&quot;, journal_fit_node)<br>    builder.add_node(&quot;journal_human_gate&quot;, journal_human_gate_node)<br>    builder.add_node(&quot;manuscript&quot;, manuscript_node)<br>    builder.add_node(&quot;submission_package&quot;, submission_package_node)<br>    builder.add_node(&quot;final_human_gate&quot;, final_human_gate_node)<br>    builder.add_edge(START, &quot;intake&quot;)<br>    builder.add_edge(&quot;intake&quot;, &quot;protocol&quot;)<br>    builder.add_edge(&quot;protocol&quot;, &quot;protocol_human_gate&quot;)<br>    builder.add_edge(&quot;protocol_human_gate&quot;, &quot;literature_search&quot;)<br>    builder.add_edge(&quot;literature_search&quot;, &quot;citation_validation&quot;)<br>    builder.add_edge(&quot;citation_validation&quot;, &quot;novelty_gate&quot;)<br>    builder.add_conditional_edges(<br>        &quot;novelty_gate&quot;,<br>        route_after_novelty,<br>        {<br>            &quot;methodology&quot;: &quot;methodology&quot;,<br>            &quot;repair_research_question&quot;: &quot;repair_research_question&quot;,<br>        },<br>    )<br>    builder.add_edge(&quot;repair_research_question&quot;, END)<br>    builder.add_edge(&quot;methodology&quot;, &quot;methodology_human_gate&quot;)<br>    builder.add_edge(&quot;methodology_human_gate&quot;, &quot;journal_fit&quot;)<br>    builder.add_edge(&quot;journal_fit&quot;, &quot;journal_human_gate&quot;)<br>    builder.add_edge(&quot;journal_human_gate&quot;, &quot;manuscript&quot;)<br>    builder.add_edge(&quot;manuscript&quot;, &quot;submission_package&quot;)<br>    builder.add_edge(&quot;submission_package&quot;, &quot;final_human_gate&quot;)<br>    builder.add_edge(&quot;final_human_gate&quot;, END)<br>    checkpointer = InMemorySaver()  # Replace with durable storage in production.<br>    return builder.compile(checkpointer=checkpointer)</pre><p>LangGraph requires the same thread ID when resuming interrupted execution, and Command(resume=…) passes the human response back into the paused node.</p><pre>from langgraph.types import Command<br>graph = build_graph()<br>config = {&quot;configurable&quot;: {&quot;thread_id&quot;: &quot;paper-001&quot;}}<br>stream = graph.stream_events(<br>    {<br>        &quot;user_goal&quot;: &quot;Develop a publishable systematic review on X&quot;,<br>        &quot;field&quot;: &quot;medicine&quot;,<br>        &quot;study_type&quot;: &quot;systematic_review&quot;,<br>    },<br>    config=config,<br>    version=&quot;v3&quot;,<br>)<br>_ = stream.output<br>if stream.interrupted:<br>    print(stream.interrupts[0].value)<br>    # Example human approval:<br>    resumed = graph.stream_events(<br>        Command(resume={<br>            &quot;decision&quot;: &quot;approve&quot;,<br>            &quot;notes&quot;: &quot;Protocol approved; add Scopus and Web of Science to search sources.&quot;,<br>        }),<br>        config=config,<br>        version=&quot;v3&quot;,<br>    )<br>    final_state = resumed.output</pre><h3>5. Submission package output schema</h3><p>Make the final output machine-checkable:</p><pre>{<br>  &quot;manuscript&quot;: {<br>    &quot;title&quot;: &quot;...&quot;,<br>    &quot;abstract&quot;: &quot;...&quot;,<br>    &quot;keywords&quot;: [],<br>    &quot;main_text&quot;: &quot;...&quot;,<br>    &quot;references&quot;: []<br>  },<br>  &quot;cover_letter&quot;: &quot;...&quot;,<br>  &quot;highlights&quot;: [],<br>  &quot;graphical_abstract_brief&quot;: &quot;...&quot;,<br>  &quot;author_contribution_statement&quot;: &quot;...&quot;,<br>  &quot;conflict_of_interest_statement&quot;: &quot;...&quot;,<br>  &quot;funding_statement&quot;: &quot;...&quot;,<br>  &quot;data_availability_statement&quot;: &quot;...&quot;,<br>  &quot;ethics_approval_statement&quot;: &quot;...&quot;,<br>  &quot;ai_use_disclosure&quot;: &quot;...&quot;,<br>  &quot;reporting_checklist&quot;: {<br>    &quot;type&quot;: &quot;PRISMA | CONSORT | STROBE | other&quot;,<br>    &quot;items&quot;: []<br>  },<br>  &quot;supplementary_files&quot;: [],<br>  &quot;reproducibility_package&quot;: {<br>    &quot;code&quot;: [],<br>    &quot;data&quot;: [],<br>    &quot;environment&quot;: [],<br>    &quot;random_seed&quot;: null,<br>    &quot;run_instructions&quot;: &quot;&quot;<br>  },<br>  &quot;reviewer_suggestions&quot;: [],<br>  &quot;response_to_review_template&quot;: &quot;...&quot;<br>}</pre><h3>6. The real “acceptance maximizer” logic</h3><p>Your agent should optimize for this:</p><pre>acceptance chance ↑ =<br>+ real contribution<br>+ strong prior-art positioning<br>+ verified citations<br>+ rigorous methods<br>+ reproducible analysis<br>+ correct journal fit<br>+ clean ethics declarations<br>+ correct reporting checklist<br>+ strong limitations section<br>+ polished academic English<br>+ complete submission package<br><br>acceptance chance ↓ =<br>- fake references<br>- shallow novelty<br>- wrong journal<br>- vague methods<br>- missing ethics approval<br>- unreported AI use<br>- weak statistics<br>- unsupported claims<br>- formatting mismatch<br>- overclaiming</pre><p>The agent can improve the <strong>discipline around the research</strong>, but it cannot manufacture novelty, ethical approval, data quality, or reviewer enthusiasm. That’s the line you should never cross.</p><h3>7. Best build order</h3><p>Start with this order:</p><ol><li><strong>Citation validator</strong> — Crossref/OpenAlex/Semantic Scholar/PubMed verification first.</li><li><strong>Protocol + human approval</strong> — no drafting before approved study design.</li><li><strong>Novelty gate</strong> — strict prior-art comparison.</li><li><strong>Methodology gate</strong> — force exact design, data, metrics, baselines, statistics.</li><li><strong>Journal-fit checker</strong> — target journal rules before writing.</li><li><strong>Manuscript generator</strong> — only after evidence and methods pass.</li><li><strong>Submission package generator</strong> — cover letter, declarations, checklist, supplementary files.</li><li><strong>Final human approval</strong> — nothing gets submitted automatically.</li></ol><p>For production, make the gates more boring than clever. Boring validators save papers. Clever LLMs sometimes invent beautiful garbage.</p><h3>The annoying details</h3><p>If you are trying to deploy this kind of system in a real production setting, several unglamorous issues will emerge immediately.</p><h3>State bloat and context window exhaust</h3><p>As the agent queries APIs, retrieves abstracts, and tracks citations, the state dictionary gets massive. If you pass the entire history of every retrieved document and API response directly into the context window, you will hit context limits and run up massive token bills. You must design a pruning mechanism. Summarize your evidence table into a dense structured schema early, and keep the raw papers out of the core state unless actively drafting.</p><h3>The “polite pool” and rate limits</h3><p>If you are repeatedly hitting Crossref or OpenAlex to verify citations at scale, you will quickly get rate-limited. For Crossref, you must pass an email header to join their “polite pool,” which guarantees better uptime. For OpenAlex, use an API key to bypass basic limits. Even with keys, implement a Redis-backed caching layer for citation verification so you do not query the exact same paper metadata on every run.</p><h3>The self-validation trap</h3><p>If you ask an LLM, <em>“Does this manuscript meet the PRISMA checklist requirements?”</em> it will almost always say yes. Do not rely on LLMs to self-evaluate complex reporting guidelines. Instead, build deterministic text processing parsers that scan the draft for mandatory structural elements (such as screening flowcharts or risk-of-bias tables) and force the human to review a generated mapping table.</p><h3>Chunk-by-chunk drafting</h3><p>Drafting a complete 5,000-word manuscript in a single model call is impossible without losing structural cohesion and technical depth. Your agent must draft section by section, feeding only the section-specific evidence table, the validated methodology, and the preceding section’s outline into the prompt.</p><h3>What this agent can and cannot do</h3><p>A clear line must be maintained between where AI helps and where humans are legally and ethically responsible.</p><h3>What the agent handles:</h3><ul><li><strong>Completeness checking</strong>: Ensuring declarations (Conflict of Interest, Funding, Ethics, AI Use) are present and formatted to the target journal’s specific guidelines.</li><li><strong>Citation verification</strong>: Checking DOIs and identifying phantom references before they make it to a draft.</li><li><strong>Structuring and outlines</strong>: Turning raw methodology notes and experiment scripts into standardized reporting guidelines (PRISMA, CONSORT, STROBE).</li></ul><h3>What the agent cannot do:</h3><ul><li><strong>Determine actual novelty</strong>: It can point out similar work, but it cannot tell you if your contribution represents a field-shifting insight.</li><li><strong>Validate logic</strong>: An LLM cannot prove that your experimental setup is genuinely free from confounding variables or that your statistical assertions are correct. It can check <em>if</em> a statistical test was run, but not if that test was fundamentally the right choice for your data distribution.</li><li><strong>Take authorship</strong>: Academic publishers (such as Elsevier, Springer Nature, and IEEE) have strict policies. AI tools cannot be listed as authors. Humans remain legally and professionally accountable for the originality, accuracy, and ethical compliance of the work.</li></ul><p>Boring, strict validation pipelines save papers from retraction. Keep your LLMs on a tight, human-controlled leash, and you might actually build something useful.</p><h3>References</h3><ul><li><a href="https://arxiv.org/abs/2605.07723">Paper: LLM hallucinations in the wild: Large-scale evidence from non-existent citations</a></li><li><a href="https://www.nature.com/articles/d41586-026-00969-z">Article: Hallucinated citations are polluting the scientific literature. What can be done?</a></li><li><a href="https://retractionwatch.com/2026/05/07/one-in-277-pubmed-indexed-papers-in-2026-shows-fabricated-references-says-analysis/">Article: One in 277 PubMed-indexed papers in 2026 shows fabricated references, says analysis</a></li><li><a href="https://docs.langchain.com/oss/python/langgraph/interrupts">Documentation: LangGraph Human-in-the-loop and Interrupts</a></li><li><a href="https://www.crossref.org/documentation/retrieve-metadata/rest-api/">Documentation: Crossref REST API</a></li><li><a href="https://www.elsevier.com/about/policies-and-standards/generative-ai-policies-for-journals">Publisher Policy: Elsevier Generative AI Policies for Journals</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42274bc3cd02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Deep Research Agents: Architecture, RL Rewards, and Context Management]]></title>
            <link>https://medium.com/@mshojaei77/building-deep-research-agents-architecture-rl-rewards-and-context-management-2ef1cf269dc3?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ef1cf269dc3</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[deep-research]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 05:44:31 GMT</pubDate>
            <atom:updated>2026-06-30T05:44:31.445Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build Deep Research Agents: Lessons from QUEST and S1-DeepResearch</h3><p>A practical look at why retrieval, context condensation, and structured rubrics matter more than raw model scale.</p><h3>The short version</h3><p>Most “deep research” systems in production are not actually doing deep research. They are just running deep search.</p><p>There is a massive practical difference between the two. Deep search is extractive; it’s about finding a specific hidden needle in a massive haystack of web pages or PDFs. Deep research is constructive; it’s about synthesizing conflicting evidence, following multi-dimensional constraints, handling messy file inputs, and writing a coherent, structured, and cited deliverable.</p><p>Building these systems is an engineering nightmare. If you rely on a vanilla LLM to browse the web for hours, your context window will overflow with HTML trash, your API bill will explode, your RL training pipeline will crash at 3 AM because a website rate-limited your scraper, and the agent will get trapped in infinite tool-use loops.</p><p>Two recent papers provide the blueprint to fix this: <strong>QUEST</strong> (from the Ohio State University and Amazon AGI SF Lab) and <strong>S1-DeepResearch</strong> (from XScience Lab and Wenge AI). Both projects released models, datasets, and training recipes that prove you do not need a trillion-parameter proprietary model to do frontier-level research. With the right training data, a 32B model can match or beat proprietary giants.</p><p>This post breaks down the architecture, the data pipelines, and the raw infrastructure engineering required to make these agents actually work in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlWxkHH9sQhYBRupz89iYg.png" /></figure><h3>What the papers actually say</h3><p>Both projects aim to transition LLMs from search-centric QA engines to long-horizon research agents. They do this by focusing heavily on high-quality synthetic trajectory generation and targeted post-training rather than raw parameter scaling.</p><h3>QUEST: Rubric trees and structured context management</h3><p>The QUEST paper introduces an open family of models (from 2B to 35B) trained on a curated synthetic dataset of only 8,000 tasks. The authors show that QUEST-35B matches or surpasses closed-source models on complex deep research benchmarks.</p><p>The QUEST recipe consists of:</p><ol><li><strong>Rubric Trees:</strong> Instead of evaluating responses using binary “correct/incorrect” checks, QUEST maps tasks to hierarchical constraint trees. Every leaf node represents an automatically verifiable condition, while internal nodes aggregate scores. This generalizes to both objective and open-ended tasks and provides a fine-grained, structured reward signal.</li><li><strong>Context Condenser:</strong> When the context window fills up, a dedicated model compresses the raw history into a structured JSON state. This state explicitly lists <em>trusted</em> facts, <em>untrusted</em> claims, and <em>uncertain</em> gaps requiring follow-up.</li><li><strong>Three-Stage Training:</strong> A pipeline consisting of mid-training (learning context summarization and web page info extraction), supervised fine-tuning (SFT) on trajectory sessions, and GRPO-style reinforcement learning (RL) optimized against the rubric-tree and fact-checking rewards.</li></ol><h3>S1-DeepResearch: Graph-grounded task evolution</h3><p>The S1-DeepResearch team released S1-DeepResearch-32B (built on Qwen3–32B) and S1-DeepResearch-15K, a collection of 15,000 high-quality agentic trajectories. Their system focuses heavily on satisfying multi-dimensional research constraints and handling complex, structured deliverables.</p><p>Their three-stage synthesis framework consists of:</p><ol><li><strong>Graph-Grounded Task Formulation:</strong> Initializing seed entity pools from Wikipedia/Wikidata, expanding them into directed acyclic graphs (DAGs) using web search, and injecting complex constraints across nine dimensions (e.g., source boundaries, argumentation guidelines, and formatting limits).</li><li><strong>Topology-Aware Filtering:</strong> They estimate task difficulty by analyzing the structural complexity of a task’s expected reasoning graph. They quantify this using metrics like Information Flow Complexity and Feedback Dependency Complexity (which identifies non-linear or cyclic reasoning dependencies) and keep only the top 30% most difficult tasks.</li><li><strong>AgentLoop Sandbox Rollout:</strong> They execute tasks inside a sandbox environment where the agent interacts with nine categories of atomic tools (including code execution, academic search, file parsing, and multimodal QA). Crucially, they apply scenario-specific post-processing to refine raw trajectories into polished, high-quality deliverables.</li></ol><h3>The useful technical ideas</h3><p>If you are building an agentic pipeline today, three core design patterns from these papers are immediately worth stealing.</p><h3>1. Rubric-tree rewards for reinforcement learning</h3><p>If you try to train an agent with RL on open-ended tasks (like writing a competitive analysis report), you will quickly run into a credit assignment wall. Pointwise scoring (asking an LLM to rate a report 1–10) suffers from severe score inflation, while pairwise comparison is notoriously unstable and expensive.</p><p>The rubric-tree framework solves this by decomposing evaluation into a strict, verifiable tree. For example, if you ask an agent to investigate a product recall:</p><ul><li>The root node aggregates the total score.</li><li>The next layer decomposes the task into <em>Comprehensiveness</em>, <em>Instruction Following</em>, and <em>Insight</em>.</li><li>The leaf nodes check highly specific, binary conditions: “Did the agent cite the primary recall notice URL?”, “Is the death toll reported as exactly 10?”, or “Is there a Markdown comparison table comparing Outbreak A and Outbreak B?”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nbt1iXzpFLDOrybBWHhYpA.png" /></figure><p>In this setup, critical nodes act as early-exit gatekeepers: if a critical node fails (e.g., the agent did not cite the source URL), the parent node’s score immediately drops to zero. This hierarchical, multi-dimensional verification provides a clean, stable reward signal for GRPO training without human-in-the-loop scoring.</p><h3>2. Structured Context State vs. Naive Truncation</h3><p>Most long-running agents break because their context window gets polluted. If you use a naive “keep-last-N-turns” or “discard-all” strategy, the model will forget verified facts, lose track of pending sub-goals, or endlessly repeat web searches it already completed.</p><p>The solution is to decouple the raw history from the agent’s working memory by using a structured JSON state:</p><pre>{<br>  &quot;search_queries&quot;: [<br>    { &quot;q&quot;: &quot;SME forensic accounting guidelines 2024&quot;, &quot;intent&quot;: &quot;locate warning indicators&quot; }<br>  ],<br>  &quot;visited_sources&quot;: [<br>    { &quot;url&quot;: &quot;https://example.com/report.pdf&quot;, &quot;note&quot;: &quot;Confirmed cash-flow metrics&quot; }<br>  ],<br>  &quot;information_state&quot;: {<br>    &quot;trusted&quot;: [<br>      { &quot;id&quot;: &quot;T1&quot;, &quot;claim&quot;: &quot;SME cash-flow threshold is $50k&quot;, &quot;sources&quot;: [&quot;https://example.com/report.pdf&quot;] }<br>    ],<br>    &quot;untrusted&quot;: [<br>      { &quot;id&quot;: &quot;U1&quot;, &quot;claim&quot;: &quot;SME cash-flow is unlimited&quot;, &quot;reason&quot;: &quot;Contradicted by T1&quot; }<br>    ],<br>    &quot;uncertain&quot;: [<br>      { &quot;id&quot;: &quot;C1&quot;, &quot;claim&quot;: &quot;Intervention strategies are required&quot;, &quot;need&quot;: &quot;visit https://example.com/guide.html&quot; }<br>    ]<br>  }<br>}</pre><p>When context window usage crosses a threshold (for example, 16K tokens), a Context Condenser model reads the history and updates this JSON state. The raw history is wiped, and the agent resumes in a fresh context window initialized only with this compact state.</p><p>Uncertain entries explicitly tell the agent what to search next, while trusted entries let it write the final report without wasting tokens on redundant tool calls.</p><h3>3. Knowing when to stop searching</h3><p>The S1-DeepResearch team highlights a fascinating metric: in search-centric datasets, unsuccessful agentic trajectories often contain <em>more</em> tool calls than successful ones.</p><p>When an agent lacks native synthesis capabilities, it gets stuck in infinite validation loops. It will search, visit a page, find slightly ambiguous text, search again, revisit the same page, and eventually crash or hit the turn limit.</p><p>A true research agent needs to balance search depth with structured output construction. The S1-DeepResearch SFT data forces the model to learn when it has gathered <em>sufficient</em> evidence to transition from information-seeking behavior to document generation. The results prove that structured deliverables (like DOCX, PDF, or HTML generation via a Python Interpreter tool) are best handled as a single, cohesive planning step once the information state is stable, rather than trying to write the document incrementally during web browsing.</p><h3>What I would actually use</h3><p>If you want to build this without a massive GPU cluster, here is how to implement the most practical parts of these architectures.</p><h3>1. Build a dual-cache system for your tools</h3><p>If you let your agents hit live search and scraping APIs during development or RL rollouts, your API bills will be astronomical, and your pipeline will run incredibly slowly.</p><p>You need a strict two-tier caching layer:</p><ul><li><strong>Exact-Match Cache:</strong> For any visit or parse_file tool call, key the cache by the exact URL or file hash. Return the cached markdown or HTML digest instantly.</li><li><strong>Semantic-Similarity Cache:</strong> For web searches, run an exact-match lookup first. If it misses, encode the query string and run a similarity search (e.g., using a local FAISS index) against previously cached queries. If a query matches with high cosine similarity (e.g., &gt; 0.92), serve the cached search results.</li></ul><p>In the QUEST project, this caching strategy intercepted up to 40% of external tool calls, drastically improving throughput and protecting the team from hitting live API rate limits.</p><h3>2. Session-level trajectory formatting</h3><p>If you try to train a model on an entire 100-step agent trajectory, you will hit a memory wall. Loading 150K tokens of history, tool inputs, and environment outputs into GPU memory is incredibly expensive, even on modern hardware.</p><p>Instead, adopt the session-level training pattern. Since the Context Condenser regularly compresses the history, you should segment your training trajectories into distinct, self-contained “sessions” bounded by condensation steps:</p><pre>[User Query + Prev State] -&gt; [Agent Steps 1-5] -&gt; [Next State]</pre><p>By training the model on these individual sessions rather than the entire long-horizon trajectory, you drastically reduce peak GPU memory requirements. This allows you to train on long-running tasks using standard consumer or mid-tier enterprise GPUs.</p><h3>3. Asynchronous evaluation pipelines</h3><p>If you are running RL training (like GRPO or PPO), your reward evaluation cannot run inline. Evaluating a deep research report using a rubric-tree judge or a citation verification model takes anywhere from 4 to 30 minutes. If your training loop stalls waiting for these evaluations, your GPUs will sit idle.</p><p>You must build a fully asynchronous evaluation harness:</p><ol><li>Rollout workers generate trajectories and immediately offload them to an asynchronous task queue (like a Ray actor pool).</li><li>The trainer continues executing parameters updates on a sliding window of already-scored samples.</li><li>Slower, long-tail evaluations are processed out-of-order and naturally absorbed back into the training queue as they complete.</li></ol><h3>The annoying details</h3><p>These papers are excellent, but if you try to replicate their findings in production, several broken abstractions and edge cases will immediately cause problems.</p><h3>1. Tool-augmented multimodal reasoning is a hack</h3><p>The S1-DeepResearch paper evaluates multimodal long-horizon reasoning benchmarks. However, because their base model (Qwen3–32B) is text-only, they obtain multimodal capabilities through tool calls like ask_question_about_image and ask_question_about_video.</p><p>This is a fragile setup. The agent has to look at a user query, realize there is an image attachment, call an image-QA tool with a textual question, receive a textual description, and then integrate that description into its planning loop.</p><p>This multi-step translation layers latency and adds points of failure. If the first tool call generates a generic or slightly misaligned description of the image, the entire reasoning path is permanently derailed. For true multimodal research tasks (like visual geo-localization or parsing complex diagrams in scientific PDFs), you will eventually need a native vision-language model as your agent core rather than relying on textual tool-use wrappers.</p><h3>2. The RL “Alignment Tax” on hard reasoning</h3><p>A highly subtle finding in the QUEST ablation studies is that while RL (optimizing for rubric satisfaction and citation verification) dramatically improves open-ended report generation, it actually <em>degrades</em> performance on raw reasoning benchmarks like HLE and GAIA.</p><p>Specializing an agent’s policy to write structured, readable, and highly cited reports forces it to prioritize format compliance and synthesis structure. This formatting alignment can act as an alignment tax, slightly weakening the model’s raw mathematical and logical derivation capabilities. If your core task is deep mathematical or scientific discovery, you may want to skip heavy report-writing RL and keep the policy closer to pure SFT or reasoning-focused RL.</p><h3>Limitations</h3><p>Before you commit to these architectures, keep these limitations in mind:</p><ul><li><strong>Coding tasks are ignored:</strong> Neither QUEST nor S1-DeepResearch focuses on software engineering. Coding agents require continuous execution-based debugging, repository-scale context parsing, and deep compiler-error feedback loops. The training datasets and evaluation rubrics presented here will not transfer well to building coding assistants.</li><li><strong>Deep dependence on a strong judge model:</strong> Generating synthetic trajectories and evaluating reports relies heavily on frontier models (like Claude Sonnet or GPT-5) acting as judges. If your evaluator model has formatting biases or fails to detect subtle factual hallucinations, your synthetic dataset will quickly degrade in quality.</li><li><strong>Messy real-world data:</strong> The graph-grounded evolution pipelines assume that your source material is clean and crawlable. In enterprise settings, you will be dealing with poorly OCR’ed PDFs, broken tables, and missing metadata. None of these benchmarks fully reflect the structural pain of parsing real-world enterprise documents.</li></ul><h3>Final takeaway</h3><p>The real lesson of QUEST and S1-DeepResearch is that the secret to deep research is not more context or a bigger model. The secret is structured engineering.</p><p>By shifting your architecture away from naive document retrieval toward a robust, cached, and context-condensed execution loop — and training your model to satisfy strict, multi-dimensional rubric trees — you can build an agent that actually produces useful, verifiable research, and do it on an academic budget.</p><h3>References</h3><ul><li><a href="https://arxiv.org/abs/2605.24218">Paper: QUEST: Training Frontier Deep Research Agents with Fully Synthetic Tasks</a></li><li><a href="https://arxiv.org/abs/2606.15367">Paper: S1-DeepResearch: Beyond Search, Toward Real-World Long-Horizon Research Agents</a></li><li><a href="https://huggingface.co/datasets/ScienceOne-AI/S1-DeepResearch-15k">Dataset: S1-DeepResearch-15k</a></li><li><a href="https://osu-nlp-group.github.io/QUEST">Repository: QUEST Project Page</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ef1cf269dc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Voice AI & Voice Agents: The Definitive 2025 State of the Art 
December 10, 2025 — The Year Voice…]]></title>
            <link>https://medium.com/@mshojaei77/voice-ai-voice-agents-the-definitive-2025-state-of-the-art-december-10-2025-the-year-voice-efcc40891a4d?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/efcc40891a4d</guid>
            <category><![CDATA[stt]]></category>
            <category><![CDATA[rsa]]></category>
            <category><![CDATA[voices]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[tts]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 07:32:55 GMT</pubDate>
            <atom:updated>2025-12-10T07:35:02.059Z</atom:updated>
            <content:encoded><![CDATA[<h3>Voice AI 2025 — The Year Voice Became Infrastructure</h3><p>2025 was the year voice AI stopped being a demo and became the fastest-growing applied AI category on the planet.</p><p>- Enterprises are deflecting 70–90 % of inbound calls and generating $20–40 k/month per agent <br>- Solo developers are shipping $30 k+/mo agencies with fully self-hosted stacks under $0.02/min <br>- Open-source full-duplex agents now run at sub-200 ms end-to-end on a single consumer GPU and sound indistinguishable from humans <br>- India is about to launch a 120 B sovereign voice LLM in February 2026 that will serve 500 M+ citizens in 22 official languages</p><p>This is the single most comprehensive, source-linked snapshot of the ecosystem as it exists today — 600+ X threads, 400+ Reddit posts, LinkedIn case studies, Hugging Face leaderboards, arXiv papers, and real production benchmarks scraped December 1–10, 2025.</p><h4><strong>1. Latency &amp; Cost Reality Check (Real Deployments — Dec 2025)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxtPIoI4oT9cjQz_tI-Emg.png" /></figure><p>→ Sub-200 ms open-source speech-to-speech is now real on a single L40S. <br>→ Hybrid still dominates production (65 % of deployments) because function calling and reasoning remains strongest in text-mode LLMs.</p><h4>2. The New King: Qwen3-Omni (September 2025)</h4><p>Alibaba’s Qwen3-Omni-30B (active 3 B MoE) is the first open-weight model that simultaneously:</p><p>- Beats GPT-4o reasoning benchmarks <br>- Runs full-duplex speech-to-speech at 195 ms on one GPU <br>- Supports 119 text + 19 speech-input + 10 speech-output languages <br>- Uses Thinker–Talker MoE + parallel token generation (5–10× faster than autoregressive S2S)</p><p>GitHub stars exploded from 0 → 42 k in one week. Reddit r/LocalLLaMA crowned it “the model that finally killed the STT→LLM→TTS tax.”</p><h4>3. Recommened Models</h4><h4><strong>Speech-to-Text (STT)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*638p4xTrPDH859N7W_3aUg.png" /></figure><p>Focus: Low WER (Word Error Rate, lower better), low latency (TTFT &lt;200ms ideal), multilingual (100+ langs preferred), noise robustness (low WER in noisy datasets like FLEURS), instruction following (N/A for pure STT, but context-aware if multimodal).</p><p><strong>1. NVIDIA Parakeet TDT 1.1B (Open Source) </strong><br> — Latency: 72ms TTFT <br> — Multilingual: 100+ languages <br> — Noise Robustness: Strong (WER 1.92% clean, robust in noisy via RNN-Transducer) <br> — Benchmarks: #1 on HF Open ASR Leaderboard (avg WER 5.2%), RTFx &gt;2,000 for speed.</p><p><strong>2. zai-org GLM-ASR-Nano-2512 (Open Source) </strong><br> — Latency: 98ms TTFT <br> — Multilingual: Strong in dialects (EN/CN/Cantonese focus, but extensible) <br> — Noise Robustness: Excels in quiet/noisy (WER 2.41% clean, 6.1% noisy) <br> — Benchmarks: Low WER on Mandarin/Cantonese, 45dB SQNR post-quantization.</p><p><strong>3. openai whisper-large-v3-turbo (Open Source) </strong><br> — Latency: ~200ms TTFT <br> — Multilingual: 99+ languages <br> — Noise Robustness: Good (WER 10–12% clean, robust in noisy via 680k hours training) <br> — Benchmarks: 10–20% error reduction vs. v2, strong on FLEURS/Common Voice.</p><p><strong>4. nvidia canary-1b-v2 (Open Source) </strong><br> — Latency: Not specified (high-throughput focus, ~200ms inferred) <br> — Multilingual: 25 European languages <br> — Noise Robustness: Robust (WER ~5.63% clean, multi-task AST/ASR) <br> — Benchmarks: SOTA on multilingual ASR/AST, 24-min segments in one pass.</p><p><strong>5. Deepgram Nova (Close Source) </strong><br> — Latency: 118ms TTFT <br> — Multilingual: 35+ languages <br> — Instruction Following: N/A <br> — Noise Robustness: Excellent (WER 4.1% clean, top in noisy via Nova-3) <br> — Benchmarks: 90%+ accuracy, sub-300ms in real-world noise.</p><p>6. IBM Granite Speech 3.3 8B</p><p>7. ElevenLabs Scribe v3</p><p>8. gpt-4o-transcribe</p><h4>LLMs for Voice</h4><p>Focus: Low TTFT (❤00ms), multilingual (100+ langs), instruction following, noise robustness (via context handling, not direct audio), open source.</p><p><strong>1. Qwen3 Next 80B A3B (Open Source) </strong><br> — Latency: Low (optimized for fast responses, ~200ms inferred) <br> — Multilingual: 119 languages <br> — Instruction Following: Excellent (outperforms Qwen3–32B on downstream) <br> — Noise Robustness: Robust (10% training cost reduction with noise handling) <br> — Benchmarks: 10x inference speedup vs. dense, strong agentic.</p><p><strong>2. **Llama 4 Maverick** (Open Source) </strong><br> — Latency: 238ms TTFT <br> — Multilingual: 200+ (via Llama base) <br> — Instruction Following: Strong (94.1% voice-tested) <br> — Noise Robustness: Moderate (multimodal robust) <br> — Benchmarks: Beats GPT-4.5/Claude 3.7 in some, 128K context.</p><p><strong>3. Gemini 2.5 Flash (Close Source ) </strong><br> — Latency: 192ms TTFT (text, audio capable) <br> — Multilingual: 45+ <br> — Instruction Following: 97.2% (voice-tested) <br> — Noise Robustness: Good (native audio) <br> — Benchmarks: Strong on SWE-Bench (73.3%), multimodal robust.</p><p>4. OpenAI GPT-4o</p><p>5. Anthropic Claude 4.5 Haiku</p><h4>Text-to-Speech (TTS)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*L5X4SgcHZg73ZPZGRBQGJA.png" /></figure><p>Focus: Low TTFB (&lt;200ms), high MOS (naturalness &gt;4.0), multilingual/dialects, instruction following (emotion control), noise robustness (N/A for TTS, but long-form stability), open source.</p><p><strong>1. Qwen Qwen3-TTS-Flash (Close Source) </strong><br> — Latency: 97ms TTFB <br> — Multilingual: 29+ dialects, 10 languages <br> — Instruction Following: Strong (multi-timbre/emotion) <br> — Noise Robustness: Good (robust long-form) <br> — Benchmarks: MOS 4.78, low first-packet latency.</p><p><strong>2. ElevenLabs Turbo (Close Source)</strong><br> — Latency: 138ms TTFB <br> — Multilingual: 32+ languages <br> — Instruction Following: Excellent (emotion, pronunciation control) <br> — Noise Robustness: High (real-world robust) <br> — Benchmarks: MOS 4.84, sub-200ms streaming.</p><p><strong>3. fishaudio fish-speech-1.5 (Open Source) </strong><br> — Latency: 200ms TTFB <br> — Multilingual: 13 languages <br> — Instruction Following: Good (emotion, 1M+ hours training) <br> — Noise Robustness: Strong (noise handling in training) <br> — Benchmarks: MOS 4.70, &lt;150ms with optimizations.</p><p><strong>4. microsoft VibeVoice-Realtime-0.5B (Open Source) </strong><br> — Latency: 182ms TTFB <br> — Multilingual: 41 languages <br> — Instruction Following: Moderate (streaming input) <br> — Noise Robustness: Good (robust long-form) <br> — Benchmarks: MOS 4.69, 300ms on CPU.</p><p><strong>5. Kokoro-82M (Open Source) </strong><br> — Latency: ~200ms TTFB <br> — Multilingual: Supported (comparable to larger models) <br> — Instruction Following: Good (customizable) <br> — Noise Robustness: Moderate <br> — Benchmarks: High Elo rating, efficient on low hardware.</p><p>6. GPT-4o mini TTS<br>7. Cartesia Sonic 2.5</p><h4><strong>Speech-to-Speech (S2S) / Full-Duplex</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*8V_KCQPtrHQiEISfD0QrHw.png" /></figure><p>Focus: Low latency (&lt;250ms), duplex support, multilingual, instruction following (reasoning), noise robustness, open source.</p><p><strong>1. Qwen3-Omni-30B-A3B </strong><br> — Latency: 234ms <br> — Multilingual: 119 text/19 speech <br> — Instruction Following: Strong (enhanced reasoning) <br> — Noise Robustness: High (SOTA on 32/36 audio benchmarks) <br> — Benchmarks: SOTA on 22/36 audio-visual, full-duplex.</p><p><strong>2. kyutai moshi</strong><br> — Latency: 160ms theoretical <br> — Multilingual: Multi (EN/FR focus, extensible) <br> — Instruction Following: Good (real-time dialogue) <br> — Noise Robustness: Strong (overlapping/noisy scenarios) <br> — Benchmarks: Clear speech in noise, 20k hours training.</p><p><strong>3. GLM-4-Voice-9B </strong><br> — Latency: Real-time (~200ms inferred) <br> — Multilingual: 26 languages <br> — Instruction Following: Excellent (end-to-end chat) <br> — Noise Robustness: Good (real-world audio) <br> — Benchmarks: Strong on VoiceAssistant-Eval (multi-turn/safety).</p><p><strong>4. Step-Audio 2 Mini 7B</strong><br> — Latency: Not specified (end-to-end focus, low inferred) <br> — Multilingual: Supported (multi-modal LLM) <br> — Instruction Following: Strong (speech conversation) <br> — Noise Robustness: High (industry-strength audio) <br> — Benchmarks: SOTA on MMAU (78% avg), robust paralinguistic.</p><p>5. Gemini Live 2.5</p><p>6. OpenAI GPT-4o Realtime v2</p><p>7. Amazon Nova 2 Sonic</p><h4>4.Turn Detection &amp; Interruption Handling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*SAVVdFL5YEdYs7hxyYkpsA.png" /></figure><h4>5. Frameworks — Market Share</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*bheSejIMgkGFYXneyPBY9A.png" /></figure><h4>6. Telephony = The Killer App</h4><p>- Self-hosted stacks (Parakeet + Qwen3-Flash + VibeVoice) now &lt;$0.012/min <br>- AI-to-AI calls exploding (logistics, healthcare, real-estate) growing 20× YoY <br>- Twilio/Telnyx + S2S = instant global scale with SIP warm transfers <br>- India’s 120 B sovereign voice LLM launches Feb 2026 → 500 M+ users</p><h4>8. Real-World Wins &amp; War Stories</h4><p>- Choco (foodservice) — voice agent upsells 26 % (LinkedIn case study) <br>- Traba — 50 k monthly interviews with Chatterbox v2 (LinkedIn) <br>- HealthifyMe Ria Voice — health coaching in 50+ languages <br>- Cresta — reduced latency from 5.4 s → 1.95 s with ONNX ASR <br>- $30 k/mo solo agencies on Reddit deflecting 70 %+ calls</p><h4>9. 2026 Consensus Predictions</h4><p>1. Sub-150 ms everywhere (Qwen3-TTS dialects + diffusion LLMs) <br>2. Open S2S maturity → Moshi-Lite 1B @ 100 ms on phones <br>3. LatentMAS becomes standard for multi-agent orgs <br>4. SLMs replace 70 % of LLM calls (NVIDIA paper) <br>5. Voice becomes the permissionless enterprise API (phone bypasses CRMs)</p><h4>Final Thought</h4><p>2025 turned voice AI from “cool demo” to “$30 k/mo deployable business”. <br>Open-source (Qwen3-Omni, VibeVoice, Pipecat, LatentMAS) + frameworks (LiveKit, Cloudflare Realtime Agents) have democratized sub-200 ms agents that run on laptops.</p><p>We are now in the “WebRTC for Voice” era: primitives are mature, but dialects, fine-tuning, and sovereign data remain the final frontiers.</p><p>The conversation isn’t coming — it’s already speaking.</p><blockquote>Sources: 600+ X threads, 400+ Reddit posts, LinkedIn case studies, Hugging Face leaderboards, arXiv (LatentMAS, Qwen3-Omni, PPP RL), Deepgram 2025 Report, Pipecat/LiveKit/Cloudflare GitHub activity, real earnings threads.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efcc40891a4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide to Merging LLMs: From Model Soups to Frankenmerges]]></title>
            <link>https://medium.com/@mshojaei77/the-ultimate-guide-to-merging-llms-from-model-soups-to-frankenmerges-e522344a3284?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e522344a3284</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[merge]]></category>
            <category><![CDATA[model-merging]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 13:33:51 GMT</pubDate>
            <atom:updated>2025-08-11T13:33:51.692Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wished you could combine the coding skills of one AI model with the creative writing prowess of another? Or maybe you’ve fine-tuned a model for two different tasks and want to create a single, multi-talented version? Welcome to the wild and wonderful world of Large Language Model (LLM) merging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9f00xJRhipIdlvLx" /><figcaption>Merging LLMs</figcaption></figure><p>Merging is a powerful technique that lets you combine multiple pre-trained or fine-tuned models into a single, hybrid powerhouse. Instead of retraining a model from scratch (which is incredibly expensive), you can leverage the unique strengths of existing models. It’s a fantastic way to improve performance, reduce inference costs, and create specialized AIs.</p><p>Tools like <strong>MergeKit</strong> have made this process more accessible than ever, offering a variety of techniques to average, interpolate, and even stack model parameters.</p><h3>Before You Start: Key Considerations</h3><p>Before you jump into creating your AI masterpiece, there are a few ground rules:</p><ul><li><strong>Compatibility is King</strong>: Merging works best when models share a similar architecture. Think of it like building with LEGOs — bricks from the same set (e.g., two Qwen models) fit together perfectly. Mixing sets (e.g., Qwen and Gemma) is possible but can be tricky and might lead to a wobbly final structure. At a minimum, they should have alignable parameters and ideally the same tokenizer.</li><li><strong>Know Your Scenario</strong>: What are you trying to achieve? Your goal will determine the best approach.</li><li><strong>Same Model, Different Fine-Tunes</strong> (e.g., Qwen3–4b for coding + Qwen3–4b for chat): Ideal for combining specialized skills.</li><li><strong>Same Family, Different Sizes</strong> (e.g., Qwen3–4b + Qwen3–32b): A great way to try and scale up capabilities.</li><li><strong>Different Families, Same Size</strong> (e.g., Qwen3–4b + Gemma3–4b): The goal here is cross-domain fusion, but you risk the models’ knowledge interfering with each other.</li><li><strong>Different Families, Different Sizes</strong> (e.g., Qwen3–4b + Gemma3–27b): This is the most challenging scenario, often requiring advanced techniques like layer stacking.</li></ul><p>In this guide, we’ll explore the practical methods supported by MergeKit, touch on some cutting-edge theoretical approaches, and give you a clear roadmap for choosing the right technique for your project.</p><h3>Your Toolkit: Practical LLM Merging Methods with MergeKit</h3><p>These are the core methods you can use right now with MergeKit. The example configs assume you’re using model paths from Hugging Face. You can run them with the command: mergekit-yaml config.yaml output_dir.</p><h4>1. Linear (Weighted Average or “Model Soup”)</h4><ul><li><strong>What it is</strong>: The simplest trick in the book. It calculates a weighted average of the parameters from each model. When you’re averaging several fine-tunes of the same base model, this is often called a “model soup.”</li><li><strong>When to Use</strong>: Perfect for combining very similar models or fine-tunes. It’s a great starting point for same-family merges.</li><li><strong>Pros</strong>: Simple, fast, and computationally cheap.</li><li><strong>Cons</strong>: Can dilute the unique strengths of each model if they are too different. It doesn’t resolve parameter conflicts intelligently.</li><li><strong>Example Config (Qwen3–4b + Qwen3–4b)</strong>:</li></ul><pre>merge_method: linear<br>dtype: bfloat16<br>models:<br>  - model: Qwen/Qwen3-4b-finetune1<br>    parameters:<br>      weight: 0.5<br>  - model: Qwen/Qwen3-4b-finetune2<br>    parameters:<br>      weight: 0.5</pre><h4>2. SLERP (Spherical Linear Interpolation)</h4><ul><li><strong>What it is</strong>: Instead of a simple average, SLERP interpolates between two models along the curve of a hypersphere. This does a better job of preserving the geometric relationship between parameters.</li><li><strong>When to Use</strong>: For a smooth blend between two similar models, especially when they come from different families but have the same size (e.g., Qwen3–4b + Gemma3–4b).</li><li><strong>Pros</strong>: Better at fusing directional knowledge than a simple linear average.</li><li><strong>Cons</strong>: Only works for two models and is more computationally intensive.</li><li><strong>Example Config (Qwen3–4b + Gemma3–4b)</strong>:</li></ul><pre>merge_method: slerp<br>base_model: Qwen/Qwen3-4b<br>dtype: bfloat16<br>models:<br>  - model: google/gemma3-4b<br>    parameters:<br>      t: 0.5  # Interpolation factor (0-1)</pre><h4>3. Task Arithmetic</h4><ul><li><strong>What it is</strong>: This clever method focuses only on what a fine-tune has <em>learned</em>. It calculates the “task vector” (the difference between the fine-tuned model and its original base model) and then adds these vectors together.</li><li><strong>When to Use</strong>: The go-to method for merging multiple fine-tunes of the <em>same base model</em>.</li><li><strong>Pros</strong>: Reduces interference from the base model’s parameters, focusing only on the new skills.</li><li><strong>Cons</strong>: Requires a shared base model for all fine-tunes.</li><li><strong>Example Config (Qwen3–4b + Qwen3–32b)</strong>:</li></ul><pre>merge_method: task_arithmetic<br>base_model: Qwen/Qwen3-4b<br>dtype: bfloat16<br>models:<br>  - model: Qwen/Qwen3-32b<br>    parameters:<br>      weight: 0.4</pre><h4>4. TIES-Merging</h4><ul><li><strong>What it is</strong>: A more sophisticated way to handle conflicts. It works in three steps: <strong>T</strong>rim low-magnitude changes, <strong>E</strong>lect the most dominant sign for each parameter, and average the rest <strong>D</strong>isjointly.</li><li><strong>When to Use</strong>: Excellent for merging multiple fine-tunes where you expect parameter conflicts. It’s more robust than a linear average.</li><li><strong>Pros</strong>: Actively mitigates parameter interference.</li><li><strong>Cons</strong>: You need to tune the density parameter, which can be tricky.</li><li><strong>Example Config (Qwen3–4b + Qwen3–4b)</strong>:</li></ul><pre>merge_method: ties<br>base_model: Qwen/Qwen3-4b<br>dtype: bfloat16<br>models:<br>  - model: Qwen/Qwen3-4b-finetune1<br>    parameters:<br>      density: 0.5<br>  - model: Qwen/Qwen3-4b-finetune2<br>    parameters:<br>      density: 0.5</pre><h4>5. DARE (Drop And REscale)</h4><ul><li><strong>What it is</strong>: DARE takes the task vectors (like in Task Arithmetic), randomly drops a fraction of the parameter changes, and then rescales the remaining ones. It’s often used with TIES or linear methods.</li><li><strong>When to Use</strong>: When you want to create a “sparser” merge, which can improve efficiency and reduce overfitting.</li><li><strong>Pros</strong>: Increases sparsity and can prevent the merged model from being too over-specialized.</li><li><strong>Cons</strong>: The random dropping might discard important knowledge.</li><li><strong>Example Config (Qwen3–4b + Qwen3–32b)</strong>:</li></ul><pre>merge_method: dare_ties<br>base_model: Qwen/Qwen3-4b<br>dtype: bfloat16<br>models:<br>  - model: Qwen/Qwen3-32b<br>    parameters:<br>      density: 0.6<br>      weight: 0.4</pre><h4>6. Passthrough (Layer Stacking or “Frankenmerging”)</h4><ul><li><strong>What it is</strong>: My personal favorite for the name alone. Instead of averaging parameters, you’re literally taking chunks of layers from different models and stacking them together.</li><li><strong>When to Use</strong>: The best option for merging models of different sizes or architectures (e.g., Qwen3–4b + Gemma3–27b). You can take the early layers from a smaller model and the later, more complex layers from a larger one.</li><li><strong>Pros</strong>: Preserves the full strength of the layers you select.</li><li><strong>Cons</strong>: High risk of creating an incoherent mess. Requires careful, manual selection.</li><li><strong>Example Config (Qwen3–4b + Gemma3–27b)</strong>:</li></ul><pre>merge_method: passthrough<br>dtype: bfloat16<br>slices:<br>  - sources:<br>    - model: Qwen/Qwen3-4b<br>      layer_range: [0, 16]  # First 16 layers from Qwen<br>  - sources:<br>    - model: google/gemma3-27b<br>      layer_range: [16, 32] # Later layers from Gemma</pre><h4>7. NuSLERP / Multi-SLERP &amp; Karcher Mean</h4><p>These are more advanced geometric methods. <strong>Multi-SLERP</strong> extends SLERP to more than two models, while <strong>Karcher Mean</strong> is a robust way to find the geometric mean. They are powerful but computationally heavy and still somewhat experimental in MergeKit.</p><h3>Into the Rabbit Hole: The Cutting-Edge &amp; Theoretical Methods</h3><p>These methods are mostly in the research phase and aren’t standard in MergeKit yet, but they show where the field is headed.</p><ol><li><strong>Evolutionary Optimization (e.g., Sakana AI’s EvoMerge)</strong>: Uses genetic algorithms — basically, survival of the fittest — to automatically discover the best merge recipes by testing generations of model combinations.</li><li><strong>Weight Disentanglement (WIDEN)</strong>: Aims to separate a model’s weights into “shared” and “unique” components before merging, which could dramatically reduce interference between different architectures.</li><li><strong>Mixture of Experts (MoE) Merging</strong>: Converts entire models into “experts” in an MoE architecture, where a router dynamically picks the best expert for a given task. MergeKit has experimental support for this.</li><li><strong>Other Research Areas</strong>: Methods like <strong>LAWA</strong> (aligning models before averaging) and <strong>DELLA</strong> (using distillation to refine merges) are pushing the boundaries of what’s possible.</li></ol><h3>How to Choose the Right Merge Method: A Practical Guide</h3><p>So, you have a few models you want to merge. Which tool do you pull from your new toolkit? Here’s a quick decision guide.</p><p><strong>Scenario 1: Merging Two Fine-Tunes of the Same Model (Qwen3–4b + Qwen3–4b)</strong></p><ul><li><strong>Top Picks</strong>: <strong>TIES</strong> or <strong>DARE</strong> to intelligently resolve conflicts between the fine-tunes.</li><li><strong>Simple Fallback</strong>: <strong>Linear</strong> averaging if you want something quick and easy.</li></ul><p><strong>Scenario 2: Merging Models of Different Sizes in the Same Family (Qwen3–4b + Qwen3–32b)</strong></p><ul><li><strong>Top Picks</strong>: <strong>Passthrough</strong> to stack layers and scale up. Alternatively, resize the smaller model and use <strong>Task Arithmetic</strong> or <strong>DARE</strong>.</li><li><strong>Advanced Option</strong>: An evolutionary approach could find the optimal weighting.</li></ul><p><strong>Scenario 3: Merging Different Families of the Same Size (Qwen3–4b + Gemma3–4b)</strong></p><ul><li><strong>Top Picks</strong>: <strong>SLERP</strong> or <strong>Multi-SLERP</strong> for a smooth interpolation, assuming the parameters are alignable. <strong>TIES</strong> can also provide a more robust merge.</li><li><strong>Warning</strong>: High risk of failure if the architectures are too different.</li></ul><p><strong>Scenario 4: Merging Different Families and Different Sizes (Qwen3–4b + Gemma3–27b)</strong></p><ul><li><strong>Top Picks</strong>: <strong>Passthrough</strong> is your main bet for creating a “Frankenmerge.” <strong>MoE</strong> is another powerful, though complex, option.</li><li><strong>Warning</strong>: This is expert-level territory. The result could be brilliant or a complete disaster. Test small first!</li></ul><h4>Some Golden Rules:</h4><ul><li><strong>Similar Models?</strong> Start with <strong>Linear</strong> or <strong>SLERP</strong>.</li><li><strong>Merging Fine-Tunes?</strong> Use <strong>TIES</strong>, <strong>DARE</strong>, or <strong>Task Arithmetic</strong>.</li><li><strong>Different Sizes/Architectures?</strong> Your best bet is <strong>Passthrough</strong> or <strong>MoE</strong>.</li><li><strong>Feeling Lost?</strong> If you have massive compute power, an <strong>Evolutionary</strong> method could automate the discovery process.</li><li><strong>If All Else Fails…</strong> You can always use the models as a simple ensemble (querying them separately) or use <strong>distillation </strong>to train a new model on their combined outputs.</li></ul><h3>At a Glance: The LLM Merging Cheat Sheet</h3><p>To wrap it all up, here’s a handy comparison chart to help you decide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xb8_XnDiGzEZvGiN-0kr-A.png" /></figure><h3>Final Thoughts</h3><p>The world of LLM merging is a bit like a mad scientist’s lab — full of exciting, sometimes unpredictable, experiments. It’s a field that’s moving incredibly fast, but with tools like MergeKit, the power to create custom, hybrid models is now in everyone’s hands.</p><p>Don’t be afraid to experiment, start with the simpler methods, and see what you can build.</p><p>What cool model hybrids are you planning to create? Let me know in the comments below</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e522344a3284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying GPT-OSS 120B on RunPod with vLLM]]></title>
            <link>https://medium.com/@mshojaei77/deploying-gpt-oss-120b-on-runpod-with-vllm-39be12d84ad8?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/39be12d84ad8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpt-oss]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[runpod]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 03:24:59 GMT</pubDate>
            <atom:updated>2025-08-11T03:24:59.816Z</atom:updated>
            <content:encoded><![CDATA[<p>This post explains how to deploy the GPT-OSS 120B model on RunPod using vLLM. The model uses MXFP4 quantization to fit on a single 80GB GPU. The setup involves a clean fork of the model, vLLM for inference, and RunPod for hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uSLIpgXJpvXocJE-" /><figcaption>Deploying GPT-OSS 120B with vLLM</figcaption></figure><p>The original model repository has extra folders that can cause download issues with vLLM. Using the fork <em>mshojaei77/gpt-oss-120b </em>avoids these problems, as it includes only the necessary 65GB of quantized weights.</p><p>This process takes about an hour to set up a working API.</p><h3>Tools and Components</h3><p>Here are the main parts of the setup and their roles.</p><ul><li><strong>Model: mshojaei77/gpt-oss-120b</strong><br>This fork of openai/gpt-oss-120b removes non-essential folders to prevent download errors. It contains the quantized model weights needed for deployment.</li><li><strong>Platform: RunPod</strong><br>RunPod offers access to GPUs like the NVIDIA H100. Persistent volumes are used to store the model and environment separately from the temporary container disk.</li><li><strong>GPU: 1x NVIDIA H100 80GB</strong><br>This GPU has 80GB of VRAM, which holds the quantized model and KV cache for a long context window.</li><li><strong>Serving Engine: vLLM</strong><br>vLLM handles LLM inference with features like PagedAttention for memory efficiency and optimized kernels for speed.</li></ul><h3>Step 1: Setting Up the RunPod Pod</h3><p>Start by configuring the pod correctly to avoid storage issues.</p><ol><li>From the RunPod dashboard, create a new pod.</li><li>Select an H100 80GB GPU.</li><li>Choose a PyTorch template, such as runpod/pytorch.</li><li>Set the disks:</li></ol><ul><li><strong>Container Disk:</strong> 30 GB. This is for the OS and is temporary.</li><li><strong>Volume Disk:</strong> 90 GB or more. This is persistent storage for the model and environment.</li><li><strong>Volume Mount Path:</strong> /workspace.</li></ul><blockquote><strong><em>Note on Disks</em></strong></blockquote><blockquote><em>The container disk is temporary and resets on restart. The volume disk at /workspace keeps data safe. Place all work, including the model and environment, in /workspace.</em></blockquote><p>Launch the pod and connect via web terminal or SSH or even Notebook.</p><h3>Step 2: Creating the Environment</h3><p>Set up a Python environment on the persistent volume.</p><pre># We are now inside the pod&#39;s terminal<br># 1. Install uv, a blazingly fast package installer<br>pip install uv<br><br># 2. Create and activate a virtual environment INSIDE our persistent storage<br># The --prompt makes your shell prompt clearly show you&#39;re in the venv<br>uv venv --python 3.12 --seed --prompt gpt-oss /workspace/.venv<br>source /workspace/.venv/bin/activate<br><br><br># 3. Install the specialized vLLM build for gpt-oss and hf_transfer<br># This specific version is required for the model&#39;s MXFP4 format.<br>uv pip install --pre &quot;vllm==0.10.1+gptoss&quot; \<br>  --extra-index-url https://wheels.vllm.ai/gpt-oss/ \<br>  --extra-index-url https://download.pytorch.org/whl/nightly/cu128 \<br>  --index-strategy unsafe-best-match<br><br>uv pip install hf_transfer</pre><blockquote><strong><em>Why this setup?</em></strong><em> Placing the virtual environment in /workspace keeps it persistent. On restart, activate it with source /workspace/.venv/bin/activate.</em></blockquote><h3>Step 3: Starting the Server</h3><p>Prepare the environment and run the server command.</p><pre># Activate your venv if you haven&#39;t already<br>source /workspace/.venv/bin/activate<br><br># Create our cache and temporary directories inside the persistent volume<br>mkdir -p /workspace/hf-cache /workspace/tmp<br># Point all Hugging Face and temporary operations to our 90GB volume<br>export HF_HOME=&quot;/workspace/hf-cache&quot;<br>export TMPDIR=&quot;/workspace/tmp&quot;<br># Force vLLM to use the highly optimized FlashAttention-3 kernel for the H100<br>export VLLM_FLASH_ATTN_VERSION=3</pre><p>Run the server. The first run downloads the 65GB model.</p><pre>vllm serve mshojaei77/gpt-oss-120b \<br>  --trust-remote-code \<br>  --dtype bfloat16 \<br>  --port 8000 \<br>  --gpu-memory-utilization 0.90 \<br>  --max-model-len 32768 \<br>  --max-num-seqs 16 \<br>  --download-dir /workspace/hf-cache</pre><p>The server is ready when it shows INFO: Application startup complete.</p><h3>Command Details</h3><ul><li>mshojaei77/gpt-oss-120b: Uses the clean fork for a 65GB download.</li><li>— dtype bfloat16: Suited for matrix operations on H100.</li><li>— gpu-memory-utilization 0.90: Allocates 90% of VRAM, with a buffer.</li><li>— max-model-len 32768: Sets a 32k context window.</li><li>— max-num-seqs 16: Handles batching for multiple requests.</li><li>— download-dir /workspace/hf-cache: Directs downloads to persistent storage.</li></ul><blockquote><strong><em>Note on KV Cache</em></strong></blockquote><blockquote><em>Avoid — kv-cache-dtype fp8 on this vLLM build with H100. It causes a dtype error on inference. The GPU handles 32k context in bfloat16 without it.</em></blockquote><h3>Step 4: Testing the API</h3><p>Test the server from inside the pod and locally.</p><h3>Testing Inside the Pod</h3><ul><li>Open a new terminal in the pod.</li><li>Create test_speed.py:</li></ul><pre># In your NEW terminal, create the file<br>cat &lt;&lt;EOF &gt; /workspace/test_speed.py<br>from openai import OpenAI<br>import time<br><br>client = OpenAI(base_url=&quot;http://localhost:8000/v1&quot;, api_key=&quot;EMPTY&quot;)<br>messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Reasoning: high&quot;}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain how a transformer model works in a few sentences.&quot;}]<br><br>print(&quot;--- 🚀 Sending request to the model ---&quot;)<br>t0 = time.perf_counter()<br>stream = client.chat.completions.create(model=&quot;mshojaei77/gpt-oss-120b&quot;, messages=messages, stream=True, max_tokens=256)<br><br>first_chunk = True<br>for chunk in stream:<br>    if first_chunk and chunk.choices[0].delta.content:<br>        ttft = (time.perf_counter() - t0) * 1000<br>        print(f&quot;⚡ Time to First Token: {ttft:.0f} ms ⚡\n&quot;)<br>        first_chunk = False<br>    print(chunk.choices[0].delta.content or &quot;&quot;, end=&quot;&quot;, flush=True)<br><br>print(&quot;\n\n--- ✅ Request complete ---&quot;)<br>EOF</pre><pre>source /workspace/.venv/bin/activate</pre><pre>python3 /workspace/test_speed.py</pre><ul><li>Expect a response with TTFT under 500ms.</li></ul><h3>Testing Locally</h3><ul><li>Get the public URL from RunPod’s ports section, like https://&lt;your-pod-id&gt;-8000.proxy.runpod.net.</li><li>Create test_runpod.py locally:</li></ul><pre># test_runpod.py - Run this on your local machine!<br>from openai import OpenAI<br><br># 🔽🔽🔽 REPLACE THIS WITH YOUR UNIQUE RUNPOD URL 🔽🔽🔽<br>RUNPOD_PROXY_URL = &quot;https://&lt;your-pod-id&gt;-8000.proxy.runpod.net/v1&quot;<br><br>client = OpenAI(<br>    base_url=RUNPOD_PROXY_URL,<br>    api_key=&quot;EMPTY&quot; # Or any dummy key<br>)<br><br>print(&quot;--- 🌍 Sending request from local machine to RunPod ---&quot;)<br>result = client.chat.completions.create(<br>    model=&quot;mshojaei77/gpt-oss-120b&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain what MXFP4 quantization is.&quot;}<br>    ]<br>)<br><br>print(&quot;✅ Response received:\n&quot;)<br>print(result.choices[0].message.content)</pre><ul><li>Run python test_runpod.py to see the response.</li></ul><h3>Managing the Pod</h3><p>To control costs:</p><ul><li>Stop the pod in the RunPod UI. Storage costs are low, and /workspace data remains.</li><li>To restart, start the pod, connect, and run Step 3 commands. The server starts quickly since the model is already downloaded.</li></ul><p>This setup provides a working API for the model using accessible tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39be12d84ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy Kimi K2 on vLLM]]></title>
            <link>https://medium.com/@mshojaei77/how-to-deploy-kimi-k2-on-vllm-0e63f36bdf3a?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e63f36bdf3a</guid>
            <category><![CDATA[kimi]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vllm]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 02:43:01 GMT</pubDate>
            <atom:updated>2025-07-21T02:43:01.277Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to squeeze Moonshot’s 1 T-parameter MoE into the smallest box you can get away with</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*DmTi9FtRMRoCd3Fc.png" /></figure><p>Kimi K2 is the first open-weight trillion-parameter Mixture-of-Experts model that genuinely competes with proprietary giants in coding, reasoning and long-context tool workflows. But the same MoE magic that keeps FLOPs low makes the model brutally <strong>memory-bound</strong> once you try to self-host it.</p><p>Below is a field-tested playbook — distilled from Moonshot’s own docs, RunPod production runs and dozens of community threads — for getting K2 into production on anything from eight H200s down to a single consumer GPU.</p><h3>Why it still hurts to host K2</h3><ul><li><strong>1 TB of FP8 weights</strong> have to stay resident so the expert router can hop between them. Even on an NVMe RAID, cold start is measured in minutes. (<a href="https://docs.unsloth.ai/basics/kimi-k2-how-to-run-locally?utm_source=chatgpt.com">Unsloth Docs</a>)</li><li><strong>KV-cache blow-up</strong>: Every extra 32 k tokens doubles per-token state across experts; a single 8 × H200 node stalls at ~7 tok/s with 64 k context. (<a href="https://huggingface.co/moonshotai/Kimi-K2-Instruct/discussions/25?utm_source=chatgpt.com">Hugging Face</a>)</li><li><strong>Memory bandwidth, not FLOPs, is the bottleneck</strong>: Reddit power-users see throughput almost double after moving from quad- to octa-channel DDR5 in a 3×3090 workstation while GPU utilisation stays flat. (<a href="https://www.reddit.com/r/LocalLLaMA/comments/1m0lyjn/kimi_has_impressive_coding_performance_even_deep/?utm_source=chatgpt.com">Reddit</a>)</li></ul><h3>Deployment tiers (fastest → cheapest)</h3><p><strong>Ultra speed</strong> — FP8 on 8×B200–192 GB</p><ul><li>32 k context, 60–65 tok/s, &lt; 120 ms first token</li></ul><p><strong>Full-context</strong> — FP8 on 16×H200</p><ul><li>128 k context, 40–45 tok/s, ~180 ms first token</li><li>Moonshot’s “smallest 128 k cluster” spec. (<a href="https://huggingface.co/moonshotai/Kimi-K2-Instruct/blob/main/docs/deploy_guidance.md">Hugging Face</a>)</li></ul><p><strong>Lean-prod</strong> — FP8 on <strong>8×H200</strong></p><ul><li>32 k context, 40–50 tok/s, ~140 ms first token</li><li>Most popular RunPod preset. (<a href="https://www.runpod.io/blog/guide-to-moonshotais-kimi-k2-on-runpod?utm_source=chatgpt.com">Runpod</a>)</li></ul><p><strong>Memory-savvy</strong> — Red Hat <strong>W4A16</strong> (4-bit weights / 16-bit acts) on 4×B200 or 8×A100–80G</p><ul><li>32 k context, ~30 tok/s, &lt; 0.1 % GSM8K drop vs FP8. (<a href="https://huggingface.co/RedHatAI/Kimi-K2-Instruct-quantized.w4a16?utm_source=chatgpt.com">Hugging Face</a>)</li></ul><p><strong>Budget lab</strong> — GPTQ “experts-only” 4-bit on 2×A100–80G</p><ul><li>8 k context, 16–18 tok/s, &lt; 200 ms first token</li></ul><p><strong>Hobby box</strong> — Unsloth <strong>Dynamic 2-bit</strong> (381 GB) on a single RTX 4090 + 256 GB RAM</p><ul><li>16 k context, ~5–6 tok/s. (<a href="https://docs.unsloth.ai/basics/kimi-k2-how-to-run-locally?utm_source=chatgpt.com">Unsloth Docs</a>)</li></ul><h3>The quantisation menu</h3><p><strong>FP8 E4M3</strong></p><ul><li>1.09 TB on disk, perfect accuracy, needs Hopper-class GPUs.</li></ul><p><strong>Red Hat W4A16</strong></p><ul><li>570 GB, activation-aware so latency stays low; sweet-spot for 4- or 8-GPU nodes. (<a href="https://huggingface.co/RedHatAI/Kimi-K2-Instruct-quantized.w4a16?utm_source=chatgpt.com">Hugging Face</a>)</li></ul><p><strong>GPTQ 4-bit (experts-only)</strong></p><ul><li>128 GB, still experimental but fits dual A100–80G rigs.</li></ul><p><strong>Unsloth Dynamic 2-bit</strong></p><ul><li>381 GB, 95 % of FP8 perplexity, runs in llama.cpp or ik_llama on consumer hardware. (<a href="https://docs.unsloth.ai/basics/kimi-k2-how-to-run-locally?utm_source=chatgpt.com">Unsloth Docs</a>)</li></ul><h3>Quick-start: dual A100–80 GB, 8 k context, GPTQ build</h3><pre># install vLLM nightlies (K2 parser merged 18 July)<br>pip install &quot;git+https://github.com/vllm-project/vllm.git#egg=vllm[ray]&quot;<br>pip install hf-transfer blobfile accelerate</pre><pre># pre-fetch 128 GB experts-only checkpoint<br>python - &lt;&lt;&#39;PY&#39;<br>from huggingface_hub import snapshot_download<br>snapshot_download(<br>  repo_id=&quot;daslab-testing/kimi-k2-instruct-gptq-128g-4bit-experts-only&quot;,<br>  local_dir=&quot;/srv/k2/k2-gptq&quot;,<br>  resume_download=True, max_workers=8)<br>PY</pre><pre># serve via OpenAI-compatible API<br>python -m vllm.entrypoints.openai.api_server \<br>  --model /srv/k2/k2-gptq \<br>  --quantization gptq \<br>  --tensor-parallel-size 2 \<br>  --max-model-len 8192 \<br>  --gpu-memory-utilization 0.95 \<br>  --swap-space 32 \<br>  --enable-tool \<br>  --tool-call-parser kimi_k2 \<br>  --distributed-executor-backend ray</pre><p><strong>Expected:</strong> cold-start ≈ 110 s, first token 180–220 ms, ~17 tok/s greedy decode.</p><h3>Tuning checklist</h3><ul><li>Drop --max-model-len to 16 k if you never need long chats; first-token latency falls noticeably.</li><li>Keep --gpu-memory-utilization around 0.90–0.95; go lower if you hit post-launch OOMs.</li><li>--max-num-seqs controls batch size: higher → more throughput, but tail-latency climbs.</li><li>Leave --enforce-eager <strong>false</strong> so vLLM can use CUDA Graphs unless you debug graph-capture issues.</li></ul><h3>Hardening for production</h3><ul><li>Put Nginx or Envoy in front of port 8000 for TLS termination and per-IP quotas.</li><li>Health probe with GET /v1/models; only mark a pod ready when the call returns 200.</li><li>Export Prometheus metrics vllm_gpu_cache_utilization, vllm_tokens_total, queue depth; alert when toks/s dips below your SLO.</li><li>Do rolling updates by spinning up a new replica, waiting for tokens_queued == 0 on the old one, then sending SIGTERM.</li><li>Warm the Hugging Face cache on fast local NVMe; restart time shrinks from ~8 min to ~90 s.</li></ul><h3>What real operators report</h3><ul><li><strong>Single H200 node stalls</strong> at ~7 tok/s past 32 k tokens; Moonshot engineers recommend at least two nodes so KV-cache fits. (<a href="https://huggingface.co/moonshotai/Kimi-K2-Instruct/discussions/25?utm_source=chatgpt.com">Hugging Face</a>)</li><li><strong>3090 enthusiasts</strong> running Unsloth UD-Q2_K_XL see 7 tok/s generation &amp; 144 tok/s prompt-fill at 128 k context — but only after maxing all eight memory channels. (<a href="https://www.reddit.com/r/LocalLLaMA/comments/1m0lyjn/kimi_has_impressive_coding_performance_even_deep/?utm_source=chatgpt.com">Reddit</a>)</li><li><strong>Red Hat W4A16</strong> keeps GSM8K within 0.1 % of FP8 while halving VRAM; load time is shorter than GPTQ. (<a href="https://huggingface.co/RedHatAI/Kimi-K2-Instruct-quantized.w4a16?utm_source=chatgpt.com">Hugging Face</a>)</li></ul><h3>Take-aways</h3><ul><li>MoE lowers <strong>compute</strong>, not <strong>memory</strong> — budget 1 TB (FP8) or 570 GB (W4A16) across VRAM + RAM + swap before worrying about FLOPs.</li><li>Memory-bandwidth wins: eight channels of DDR5 or HBM3X beats “just add another GPU” for many workloads.</li><li>W4A16 and 4-bit GPTQ deliver the best price-latency trade-off; go below 2-bit only if you’re RAM-rich and latency-tolerant.</li><li>With the recipe above, <strong>two A100s</strong> are enough to build a low-latency private Claude-class endpoint, and <strong>eight H200s</strong> give you 32 k-token, sub-150 ms chat at ~45 tok/s.</li></ul><p>Ship it — and let the trillion-parameter magic power your agents without the trillion-dollar bill.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e63f36bdf3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large Language Models — An Up‑to‑Date Pocket Guide]]></title>
            <link>https://medium.com/@mshojaei77/large-language-models-an-up-to-date-pocket-guide-b28df8b677e1?source=rss-1d6325312ab5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b28df8b677e1</guid>
            <category><![CDATA[lllm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Mohammad Shojaei]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 22:36:43 GMT</pubDate>
            <atom:updated>2025-07-15T22:36:43.133Z</atom:updated>
            <content:encoded><![CDATA[<h3>Large Language Models — An Up‑to‑Date Pocket Guide</h3><h4>Expanded summary of “A Comprehensive Overview of Large Language Models”</h4><figure><img alt="Everything an LLM touches is grouped into seven branches — Pre‑Training, Fine‑Tuning, Efficiency, Inference, Evaluation, Applications, and Challenges." src="https://cdn-images-1.medium.com/max/1024/0*QNnUH0JRBkMO76nN.png" /><figcaption>Everything an LLM touches is grouped into <strong>seven branches</strong> — <em>Pre‑Training, Fine‑Tuning, Efficiency, Inference, Evaluation, Applications,</em> and <em>Challenges</em>.</figcaption></figure><p>Have you ever wondered how ChatGPT, Gemini, or Claude can write an email, explain a complex topic, or even create a poem in seconds? The magic behind these tools is something called a <strong>Large Language Model</strong>, or <strong>LLM</strong>.</p><p>Think of an LLM as a brilliant student who has read almost the entire internet — every Wikipedia page, every book, every blog post. After reading all that, it hasn’t just memorized facts; it has learned the patterns of language, logic, and reasoning.</p><p>This article, based on the highly detailed research paper “<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Farxiv.org%2Fabs%2F2307.06435">A Comprehensive Overview of Large Language Models</a>,” will break down how these models work in simple terms. No background needed! We’ll walk through their journey from digital infants to the incredibly capable AI assistants we use today.</p><h3>The Building Blocks: What Are LLMs Made Of?</h3><p>Before an LLM can learn, it needs a brain and a way to understand language. Here are the core components that make it all possible.</p><h4>1. Tokenization: Breaking Language into Lego Bricks</h4><p>Computers don’t understand words and sentences the way we do. They need to break them down into numbers. The first step is <strong>Tokenization</strong>.</p><p>An LLM uses a “tokenizer” to split text into smaller pieces called <strong>tokens</strong>. A token can be a whole word, a part of a word, or even just a punctuation mark.</p><p>For example, the word “unforgettable” might be broken down into three tokens: un, forget, and able.</p><p>This is incredibly efficient. Instead of having to learn millions of individual words, the model can learn the meaning of these smaller building blocks and combine them in new ways.</p><h4>2. Architecture: The Blueprint of an LLM’s Brain</h4><p>Most modern LLMs are built on an architecture called the <strong>Transformer</strong>, introduced in 2017. The Transformer was revolutionary because of a special mechanism called <strong>attention</strong>.</p><p><strong>Attention is the LLM’s ability to focus on what matters.</strong> When you read the sentence, “The dog chased the ball across the park,” your brain automatically links “dog” with “chased” and “ball” with “chased.” The attention mechanism allows an LLM to do the same, weighing the importance of different words when generating a response.</p><p>LLM architectures generally come in a few flavors:</p><ul><li><strong>Encoder-Decoder:</strong> Think of this like a human translator. The <strong>encoder</strong> reads and understands the input text (e.g., an English sentence). The <strong>decoder</strong> then uses that understanding to generate the output (e.g., the same sentence in German).</li><li><strong>Decoder-Only (or Causal Decoder):</strong> This is the most common architecture for chatbots like ChatGPT. It’s a master of prediction. It reads text from left to right and its only job is to predict the very next word (or token). By doing this over and over, it can write entire essays.</li><li><strong>Mixture-of-Experts (MoE):</strong> Instead of one giant, monolithic brain, an MoE model is like a team of specialists. When it receives a prompt, a “router” sends the question to the most relevant “experts.” For a coding question, it might consult the programming experts; for a history question, the history experts. This makes the model faster and more efficient.</li></ul><h3>The Life of an LLM: From Birth to Graduation</h3><p>An LLM goes through several stages of training to become the powerful tool you interact with. We can think of it as a three-step educational journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*meg1ITV4Rx2mJJPg.png" /><figcaption><em>The training pipeline of an LLM, from pre-training to alignment. (A simplified version of Figure 6 from the paper)</em></figcaption></figure><h4>Step 1: Pre-training (Reading the Entire Library)</h4><p>This is the foundational stage where the LLM learns about the world. It’s fed a massive amount of text data — terabytes of it from the internet.</p><p>During pre-training, its goal is simple: <strong>predict the next word</strong>. It looks at a sentence like, “The cat sat on the…” and tries to guess the next word. At first, its guesses are random. But every time it’s wrong, it adjusts its internal connections. After doing this trillions of times, it develops an incredibly sophisticated understanding of grammar, facts, reasoning, and even style.</p><p>A pre-trained model is a powerful generalist but isn’t very good at following instructions. It’s like a brilliant student who knows everything but doesn’t know how to answer specific questions on a test.</p><h4>Step 2: Fine-Tuning (Learning to Be a Helpful Assistant)</h4><p>After pre-training, the model needs to learn how to be useful to humans. This is done through <strong>fine-tuning</strong>. There are two key types:</p><p><strong>A. Instruction-Tuning:</strong></p><p>Here, we teach the model to follow commands. We give it thousands of examples of instruction -&gt; desired output.</p><ul><li><strong>Instruction:</strong> “Summarize this article about photosynthesis.”</li><li><strong>Desired Output:</strong> “Photosynthesis is the process…”</li></ul><p>After seeing enough examples, the model learns the general pattern of how to respond to user requests, turning it from a simple text-predictor into a helpful assistant.</p><p><strong>B. Alignment Tuning (Making it Safe and Ethical):</strong></p><p>This is one of the most important steps. A pre-trained model might generate text that is unhelpful, biased, or harmful because it learned from the unfiltered internet. <strong>Alignment</strong> is the process of steering the model to be <strong>Helpful, Honest, and Harmless (HHH)</strong>.</p><p>The most common method for this is <strong>Reinforcement Learning from Human Feedback (RLHF)</strong>:</p><ol><li><strong>Collect Data:</strong> Developers prompt the model and get it to generate a few different answers.</li><li><strong>Rank Responses:</strong> Human reviewers rank these answers from best to worst.</li><li><strong>Train a Reward Model:</strong> This human ranking data is used to train another, smaller AI called a <strong>reward model</strong>. The reward model’s only job is to look at a response and give it a score for how “good” it is based on human preferences.</li><li><strong>Fine-Tune the LLM:</strong> The LLM is then fine-tuned further. It generates responses and gets “points” from the reward model. It learns to adjust its own behavior to maximize these points, effectively learning to behave in ways that humans prefer.</li></ol><h4>Step 3: Inference (Putting the LLM to Work)</h4><p>This is the final stage, where you, the user, interact with the fully trained LLM. When you type a question into ChatGPT, you are performing <strong>inference</strong>.</p><p>The text you provide is called a <strong>prompt</strong>. The art of writing good prompts is called <strong>prompt engineering</strong>. How you phrase your question can dramatically change the quality of the answer. Here are a few simple techniques:</p><ul><li><strong>Zero-Shot Prompting:</strong> Asking a question directly, with no examples. (e.g., “What is the capital of Australia?”)</li><li><strong>Few-Shot Prompting:</strong> Giving the model a few examples in your prompt to show it the format you want.</li><li><strong>Chain-of-Thought (CoT) Prompting:</strong> For complex problems, you can simply add “Think step-by-step” to your prompt. This encourages the model to break down its reasoning process, which often leads to a more accurate answer.</li></ul><h3>Giving LLMs Superpowers: RAG and Tool Use</h3><p>Even with all this training, LLMs have two major limitations: their knowledge is frozen in time, and they can’t interact with the outside world. To solve this, developers have given them “superpowers.”</p><h4>Retrieval-Augmented Generation (RAG): An Open-Book Exam</h4><p>An LLM’s knowledge is only as current as its training data. <strong>RAG</strong> solves this by connecting the LLM to a live, external knowledge source (like the internet or a company’s internal documents).</p><p>Here’s how it works:</p><ol><li>You ask a question (e.g., “What were the key announcements from Apple’s event last week?”).</li><li>The RAG system first <strong>retrieves</strong> relevant, up-to-date information from its connected database.</li><li>It then feeds this information to the LLM along with your original prompt.</li><li>The LLM uses this new context to <strong>generate</strong> a factually accurate and current answer.</li></ol><p><em>RAG gives an LLM access to external knowledge, making its answers more accurate and up-to-date. (Figure 12 from the paper)</em></p><h4>Tool Use: Giving LLMs Hands and Eyes</h4><p>LLMs live inside a computer and can only manipulate text. They can’t check the weather, book a flight, or perform a calculation. <strong>Tool use</strong> gives them the ability to call on other programs (or “tools”) to perform actions.</p><p>When you ask a tool-enabled LLM, “What’s the weather in London and can you add a reminder to my calendar to pack an umbrella?”</p><ul><li>The LLM identifies it needs two tools: a weather API and a calendar API.</li><li>It calls the weather tool for “London.”</li><li>It calls the calendar tool to create a reminder.</li><li>It then synthesizes the results into a single, helpful response for you.</li></ul><h3>The Road Ahead: Challenges and the Future</h3><p>Despite their incredible abilities, LLMs are not perfect. The research paper highlights several key challenges that developers are actively working to solve:</p><ul><li><strong>Hallucinations:</strong> Sometimes, LLMs confidently make things up.</li><li><strong>Bias:</strong> They can reflect the societal biases present in their vast training data.</li><li><strong>Cost:</strong> Training and running these models requires enormous computational power and is very expensive.</li><li><strong>Safety:</strong> Ensuring models are not used for harmful purposes is a constant battle.</li></ul><p>The field of LLMs is one of the fastest-moving areas in technology. Researchers are making breakthroughs every day to make these models smarter, safer, and more accessible. From a simple text-predictor to a world-knowledge reasoner, the journey of the LLM is a testament to the power of data and computation. And it’s only just beginning.</p><p>—</p><p><em>This article is a simplified, tutorial-style summary of the comprehensive research paper: </em><a href="https://arxiv.org/html/2307.06435v10"><em>Naveed, H., Khan, A. U., Qiu, S., et al. (2024). “A Comprehensive Overview of Large Language Models.”</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b28df8b677e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>