<?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 Arash Nicoomanesh on Medium]]></title>
        <description><![CDATA[Stories by Arash Nicoomanesh on Medium]]></description>
        <link>https://medium.com/@anicomanesh?source=rss-3b60b0dc5fe7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mAwQVHKzZ2TNsz_zy18kOQ.jpeg</url>
            <title>Stories by Arash Nicoomanesh on Medium</title>
            <link>https://medium.com/@anicomanesh?source=rss-3b60b0dc5fe7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:23:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anicomanesh/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[Agentic-AI Series Part 1: From Months to Minutes, Zero‑Shot Forecasting with Foundation Models and…]]></title>
            <link>https://medium.com/@anicomanesh/agentic-ai-series-part-1-from-months-to-minutes-zero-shot-forecasting-with-foundation-models-4374bc1868a2?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4374bc1868a2</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai-agent-tools]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[forecasting]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 13:01:42 GMT</pubDate>
            <atom:updated>2026-09-05T18:05:38.091Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>Agentic-AI Series </em>Part 1<em>: From Months to Minutes, Zero‑Shot Forecasting with Foundation Models and MCP Forecasting Agentic Skill</em></h3><p><em>How to Build a Production‑Ready MCP Forecasting Skill for Agentic AI Systems</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e5DgdUsBmxWiSvHR" /><figcaption>Photo by <a href="https://unsplash.com/@jakubzerdzicki?utm_source=medium&amp;utm_medium=referral">Jakub Żerdzicki</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>I. Introduction</h3><p>Last month, I was on a call with a friend who runs supply chain operations for a mid-size retail company. He pulled up his dashboard and pointed to a blinking red alert: a supplier in Vietnam had just delayed a shipment by three weeks, a TikTok trend had unexpectedly tripled demand for a product they were planning to phase out, and a port closure in Long Beach had left them scrambling for alternatives. He asked me a simple question: “Can your AI tell me how much stock I need next Thursday?”</p><p>I had to tell him no. Not because the models didn’t exist, but because getting from “business question” to “forecast” still took his team weeks of data gathering, feature engineering, and model retraining. By the time the forecast arrived, the business had already made an unguided decision, or market conditions had shifted, making the model obsolete before it ever saw production.</p><p>That conversation stuck with me. Last month, I set out to fix it.</p><h4>The Core Problem and Thesis</h4><p>The fundamental issue with traditional machine learning forecasting — whether based on LightGBM, XGBoost, or complex rolling-lag ensembles — is its reliance on manual feature engineering and continuous retraining. Every time a business introduces a new product, expands into a new region, or experiences a sudden promotional shift, data science teams must restart the pipeline: construct new features, backfill historical data, retrain models, and hope local dynamics are captured.</p><p>Worse, these models are inherently brittle. They learn patterns strictly from historical distributions and assume the future will mirror the past. But supply chains do not operate in a stationary environment. Sudden structural breaks — a port closure, factory outage, or viral demand spike — upend historical patterns overnight, leaving classical models to extrapolate from invalid assumptions.</p><p>The M5 forecasting competition illustrated this trade-off. The top-performing entries were not modular, interpretable models; they were monolithic ensembles comprising hundreds of individual learners stitched together with extensive feature engineering. They optimized purely for point-accuracy at the cost of simplicity, inference speed, operational adaptability, and system maintainability.</p><p>Instead of building another hyper-parameterized ensemble, I decided to try a different thesis:</p><blockquote><strong>Core Thesis:</strong> Eliminate model training entirely. A pre-trained time-series foundation model can read the statistical signature of an unseen historical series in-context — without backpropagation, gradient updates, or fine-tuning — to project future trajectories with calibrated uncertainty.</blockquote><h3>What This Article Covers</h3><ul><li>The operational architecture of a production-ready, zero-shot forecasting skill.</li><li>Deterministic routing and feature degradation between univariate and multivariate foundation models.</li><li>Strict symbolic boundary enforcement via Pydantic v2 for safe LLM consumption.</li><li>Model Context Protocol (MCP) integration via FastMCP for dynamic tool discovery.</li><li>Empirical benchmarks on the M5 Walmart and Corporación Favorita datasets.</li><li>Battle-tested production hardening mechanics (concurrency locks, isotonic quantile sanitation, circuit breakers, non-linear confidence metrics, and structured observability).</li></ul><p>Please refer to my <a href="https://github.com/arashnicoomanesh/zero-shot-demand-forecasting/tree/main">github repo </a>for full open source code review, currently the disscussion is open, here :</p><p><a href="https://github.com/arashnicoomanesh/zero-shot-demand-forecasting/tree/main">GitHub - arashnicoomanesh/zero-shot-demand-forecasting: A production-grade, MCP-compliant agentic forecasting tool. Designed for Agentic AI orchestrators to autonomously resolve inventory shortages, evaluate demand risk, and execute quantile-bounded supply-chain decisions-without requiring local fine-tuning.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*aFoz3AzY_YtsFVuc3Eno7A.png" /></figure><h3>II. Zero-Shot Forecasting with Foundation Models</h3><p>Zero-shot forecasting enables an agentic system to predict future temporal trajectories without training a model on domain-specific target data. Instead of collecting historical series, engineering domain features, and tuning hyper-parameters, historical context is passed directly to a pre-trained foundation model to receive a forecast in milliseconds.</p><blockquote>“<strong>Zero-shot forecasting</strong> is the capability of a pre-trained time-series model to predict future values on completely unseen datasets or domains without requiring any dataset-specific training, gradient updates, or fine-tuning.”</blockquote><p>These models are pre-trained on diverse time-series corpora spanning retail, financial markets, energy grids, and IoT telemetry. Through pre-training, they internalize universal temporal representations: multi-frequency seasonality, linear and non-linear trends, structural regime shifts, and intermittent spikes. When exposed to an unseen series, the model utilizes its context window to project future steps without parameter modifications.</p><pre>ZERO-SHOT IN-CONTEXT INFERENCE<br>                     <br> Historical Series (In-Context Window)         Predicted Trajectory<br> ───┼──────────┼──────────┼──────────┼─── ────────► ───┬──────────┬───<br>   t-30       t-20       t-10        t0             t+10       t+20<br>                                                      │<br>                                            ┌─────────┴─────────┐<br>                                            │ p90 (Upper Bound) │<br>                                            │ p50 (Median)      │<br>                                            │ p10 (Lower Bound) │<br>                                            └───────────────────┘</pre><h4>Operational Advantages</h4><ul><li>Zero Training Overhead: Eliminates offline pipeline execution, data labeling, and scheduled retraining jobs.</li><li>Zero Customer Data Retention: Eliminates fine-tuning state persistence, ensuring strict privacy boundaries across tenant boundaries.</li><li>Calibrated Risk Quantification: Generates probabilistic quantiles (p₁₀, p₅₀, p₉₀) alongside point estimates, converting raw predictions into actionable safety-stock parameters.</li></ul><p>Traditional paradigms construct separate models per SKU or region. The foundation model approach leverages transformer attention mechanisms to read mathematical structure directly from context, treating time-series patterns as domain-agnostic numerical signals.</p><h3>III. The Foundation Models: Chronos-2 &amp; TimesFM 2.5 XReg</h3><p>I selected two models with fundamentally different approaches to the same problem — forecasting a single target variable with external covariates.</p><p><strong>Primary: </strong><a href="https://github.com/google-research/timesfm"><strong>Google TimesFM 2.5 200M XReg </strong></a><strong>(Univariate + Exogenous Regressors)</strong></p><ul><li>Architecture: 200M-parameter decoder-only transformer. The core model is strictly univariate — it reads one target series and projects future values.</li><li>Covariate handling: XReg (Exogenous Regressors) subsystem. In xreg + timesfm mode, a linear model first fits the target to external variables (price, promotions), and TimesFM forecasts the residuals. This is computationally efficient and scales to 16,000-step contexts.</li><li>Why primary: For single-SKU demand forecasting, this hybrid approach (linear covariate absorption + univariate transformer) is often more stable than full multivariate attention, especially with sparse promotional signals.</li></ul><blockquote><strong>Google TimesFM 2.5 200M is fundamentally a univariate engine, but it includes an XReg (Exogenous Regressors) subsystem that allows you to incorporate external variables.</strong></blockquote><blockquote>While it is not a true “multivariate model” that forecasts multiple interdependent target variables simultaneously, its <strong>XReg mechanism</strong> bridges the gap by allowing it to handle external factors (like weather, prices, or holidays).</blockquote><blockquote>How XReg works in TimesFM 2.5</blockquote><blockquote>Instead of processing all data through a complex multivariate transformer architecture, Google Research utilizes an elegant hybrid approach:</blockquote><blockquote><strong>- The Core Model:</strong> The <strong>200M parameter decoder-only transformer</strong> strictly handles the <em>univariate target sequence</em> (e.g., your historical sales data) to predict future trends zero-shot.</blockquote><blockquote><strong>- The XReg Subsystem:</strong> It integrates external covariates using two primary routing methods depending on your configuration:</blockquote><blockquote><strong>- TimesFM + XReg:</strong> The model generates a zero-shot univariate forecast baseline first, and then fits a linear regression model on the residuals using your external covariates.</blockquote><blockquote><strong>- XReg + TimesFM:</strong> A linear model fits the target series to the external covariates first, and then TimesFM forecasts the remaining residuals.</blockquote><p><strong>Fallback: </strong><a href="https://github.com/amazon-science/chronos-forecasting"><strong>Amazon Chronos-2</strong></a><strong> (Multivariate / Group-Attention)</strong></p><ul><li>Architecture: Tokenized time-series transformer with group attention. Native multivariate design — the target series and covariates are processed together through shared attention layers.</li><li>Covariate handling: Past and future covariates are concatenated and tokenized alongside the target, then processed through the same attention mechanism.</li><li>Why fallback: Different vendor (AWS vs Google), different quantile generation (Monte Carlo sampling vs parametric), and different failure modes. When TimesFM’s XReg path fails on a specific array shape or HuggingFace hub is unreachable, Chronos provides an independent retry surface.</li></ul><p>Both models handle your payload (single target + covariates). There is no clean conditional split. TimesFM is primary because its XReg architecture is the better fit for demand forecasting. Chronos is secondary because it provides resilience. The univariate/multivariate distinction is an architectural property of the models, not a routing heuristic.</p><h4>Deterministic Routing &amp; Degradation</h4><p>I experimented with conditional routing — sending long-context series to one model and covariate-heavy series to another — but the heuristics were brittle and added operational complexity. I simplified to a single, unified chain. Every request enters through the same gate:</p><pre>                           ┌──────────────────────────────┐<br>                           │ Incoming TimeSeries Payload  │<br>                           └────────────┬─────────────────┘<br>                                        │<br>                                        ▼<br>                         ┌──────────────────────────────┐<br>                         │ Tier 1: Google TimesFM 2.5   │<br>                         │ (XReg + exogenous if present)│<br>                         └──────────────┬───────────────┘<br>                                        │ OOM / Struct Error / <br>                                        │ Hub Unreachable / Timeout<br>                                        ▼<br>                         ┌──────────────────────────────┐<br>                         │ Tier 2: Amazon Chronos-2     │<br>                         │ (Group-Attention Covariates) │<br>                         └──────────────┬───────────────┘<br>                                        │ OOM / CUDA Error /<br>                                        │ Unhandled Exception<br>                                        ▼<br>                         ┌──────────────────────────────┐<br>                         │ Tier 3: ARIMA(1,1,1) Baseline│<br>                         │ (strips exogenous, CPU-only) │<br>                         └──────────────────────────────┘</pre><ul><li><strong>Secondary Fallback Route:</strong> On TimesFM execution failure or CUDA memory exhaustion, execution degrades to Chronos-2, passing exogenous covariates via _build_chronos_covariates().</li><li><strong>Tertiary Baseline Degradation</strong>: If both foundation models fail or CUDA resources are fully exhausted, the system strips invalid covariates, sets exogenous_dropped = True, and degrades to the CPU-based ARIMA(1,1,1) baseline.</li></ul><h3>IV. System Architecture: The Agent-Skill Boundary</h3><p>This skill is a deterministic, symbolic computation engine designed to be invoked by a neural agent within a broader neuro-symbolic system. It is one component of the symbolic layer, not the architecture itself. The neural agent (e.g., an LLM orchestrator) performs high-level goal decomposition and context interpretation, while this skill executes deterministic mathematical transformations within strictly validated boundaries. The skill itself is not neuro-symbolic; it is the deterministic substrate that the neural agent invokes.</p><p>The following is a simplified view of the agent-to-skill call boundary. A complete neuro-symbolic architecture includes bidirectional feedback, knowledge-graph grounding, policy enforcement, and audit trails not shown here. For the full architectural stack, see Section VII.</p><pre>┌─────────────────────────────────────────────────────────────┐<br>│              AGENTIC ORCHESTRATOR (External)                |<br>|-------------------------------------------------------------|  <br>│  • Neural Reasoning + MCP Host + Policy Firewall            │<br>└──────────┬────────────────────┬────────────────────┬────────┘<br>           │ MCP Call           │ MCP Call           │ MCP Call<br>           ▼                    ▼                    ▼<br>┌──────────────┐    ┌─────────────────────────┐    ┌──────────────┐<br>│  Inventory   │    │  THIS REPO:             │    │   Pricing    │<br>│  Skill       │    │  Zero-Shot Forecaster   │    │   Skill      │<br>└──────────────┘    │(Symbolic, Deterministic)│    └──────────────┘<br>                    │                         │<br>                    │ • Pydantic Validation   │<br>                    │ • 3-Tier Fallback       │<br>                    │ • Quantile Sanitation   │<br>                    │ • Confidence Scoring    │<br>                    └─────────────────────────┘</pre><p><em>In MCP terminology, the Orchestrator is the Host application containing the MCP Client. Each Skill is an independent MCP Server running as a separate process. The Host discovers Servers via tool registries and invokes their exposed functions over stdio or HTTP.</em></p><h4>Execution Data Flow</h4><p>[ 1 ] Payload Construction &amp; Boundary Enforcement: The agent translates business intent into a TimeSeriesInputPayload. Pydantic v2 validates structural constraints before inference:</p><ul><li>Historical target array length: 16 ≤ L ≤ 16,000.</li><li>Forecast horizon: 1 ≤ H ≤ 1,024.</li><li>Numerical integrity: All values must be finite numbers (ℝ \ {±∞, NaN}).</li><li>Exogenous alignment: len(price_index) == len(target_series) + forecast_horizon.</li></ul><p>[ 2 ] Model Selection &amp; Fallback Routing: The payload is evaluated against covariate integrity rules to select the target inference engine. All requests enter at Tier 1 (TimesFM).</p><p>[ 3 ] In-Context Inference: The selected model processes the input tensor using non-blocking thread execution (asyncio.to_thread) to keep the asynchronous event loop responsive. A dedicated inference lock serializes forward passes per backend, preventing CUDA race conditions under concurrent load.</p><p>[ 4 ] Isotonic Quantile Sanitation &amp; Confidence Scoring: Raw model quantiles are sorted per timestep to prevent quantile non-monotonicity anomalies (p₁₀ ≤ p₅₀ ≤ p₉₀). The relative uncertainty spread yields a normalized confidence score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*4nvAIWxnT8N9odLpCUOO7w.png" /></figure><p>A score approaching 1.0 indicates tight predictive consensus, whereas a lower score signifies wider epistemic variance, alerting the agent to exercise operational caution.</p><p>[ 5 ] Structured Return: Output arrays, confidence scores, execution timing, model provenance, and operational metadata are packaged into a validated response.</p><h3>V. MCP Integration: Making It Agent-Ready</h3><p>To expose this skill to LLM orchestrators without custom client glue code, the service implements the Model Context Protocol (MCP) via FastMCP. MCP provides standard mechanisms for runtime tool discovery, schema registration, and error propagation.</p><p>Getting this right took longer than I expected. My first attempt returned error dictionaries as successful JSON payloads — a subtle but critical mistake. An MCP client receiving a 200-equivalent response with an error body has no way to distinguish failure from success. I had to rewrite the error path to raise proper McpError exceptions with structured metadata.</p><h4>FastMCP Server Implementation</h4><pre>import asyncio<br>import os<br>from typing import Dict, Any, List<br>from mcp.server.fastmcp import FastMCP<br>from mcp import McpError, ErrorData<br>from pydantic import ValidationError<br><br>from src.schemas.payloads import (<br>    TimeSeriesInputPayload,<br>    ForecastResponse,<br>    AgentFriendlyError,<br>)<br>from src.models.forecaster import ZeroShotForecastingEngine<br><br>mcp = FastMCP(&quot;Zero-Shot Demand Forecasting Engine&quot;)<br>_engine = None<br>_engine_lock = asyncio.Lock()<br><br># Unified concurrency control for both tools<br>_INFERENCE_SEMAPHORE = asyncio.Semaphore(<br>    int(os.getenv(&quot;MAX_CONCURRENT_INFERENCE&quot;, 4))<br>)<br><br>async def _get_engine_async() -&gt; ZeroShotForecastingEngine:<br>    global _engine<br>    if _engine is None:<br>        async with _engine_lock:<br>            if _engine is None:<br>                _engine = await asyncio.to_thread(ZeroShotForecastingEngine)<br>    return _engine<br><br>def _to_mcp_error(error: Exception, error_code: int = -32603) -&gt; McpError:<br>    &quot;&quot;&quot;Convert any exception into an MCP-compliant error.&quot;&quot;&quot;<br>    if isinstance(error, ValidationError):<br>        friendly = AgentFriendlyError.from_validation_error(error)<br>        code = -32602<br>    else:<br>        friendly = AgentFriendlyError.from_exception(error, error_code=&quot;INTERNAL_ERROR&quot;)<br>        code = error_code<br>    return McpError(ErrorData(code=code, message=friendly.message, data=friendly.model_dump()))<br><br>@mcp.tool()<br>async def forecast_demand(payload: dict) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Forecast demand for a product using zero-shot foundation models.<br>    &quot;&quot;&quot;<br>    async with _INFERENCE_SEMAPHORE:<br>        try:<br>            validated = TimeSeriesInputPayload(**payload)<br>            engine = await _get_engine_async()<br>            result = await asyncio.wait_for(<br>                asyncio.to_thread(engine.predict, validated),<br>                timeout=120.0<br>            )<br>            return result.model_dump()<br>        except ValidationError as e:<br>            raise _to_mcp_error(e, -32602) from e<br>        except asyncio.TimeoutError as e:<br>            raise _to_mcp_error(<br>                asyncio.TimeoutError(&quot;Inference timeout after 120s&quot;), -32603<br>            ) from e<br>        except Exception as exc:<br>            raise _to_mcp_error(exc, -32603) from exc<br><br>@mcp.tool()<br>async def forecast_batch(payloads: List[dict]) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Efficiently forecast an array of demand payloads with bounded concurrency.<br>    &quot;&quot;&quot;<br>    engine = await _get_engine_async()<br>    <br>    async def _process(p: dict) -&gt; dict:<br>        async with _INFERENCE_SEMAPHORE:<br>            try:<br>                validated = TimeSeriesInputPayload(**p)<br>                result = await asyncio.wait_for(<br>                    asyncio.to_thread(engine.predict, validated), timeout=120.0<br>                )<br>                return result.model_dump()<br>            except (ValidationError, asyncio.TimeoutError, Exception) as e:<br>                return _to_mcp_error(e).error.data  # Error dict per item<br><br>    responses = await asyncio.gather(*[_process(p) for p in payloads])<br>    # ... summary aggregation ...</pre><h4>Tool Discovery Schema</h4><p>Upon connection, an MCP client discovers the tool schema generated from Pydantic type hints:</p><pre>{<br>  &quot;name&quot;: &quot;forecast_demand&quot;,<br>  &quot;description&quot;: &quot;Forecast demand for a product using zero-shot foundation models.&quot;,<br>  &quot;parameters&quot;: {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>      &quot;target_series&quot;: {<br>        &quot;type&quot;: &quot;array&quot;,<br>        &quot;items&quot;: { &quot;type&quot;: &quot;number&quot; },<br>        &quot;minItems&quot;: 16,<br>        &quot;maxItems&quot;: 16000,<br>        &quot;description&quot;: &quot;Historical demand sequence.&quot;<br>      },<br>      &quot;forecast_horizon&quot;: {<br>        &quot;type&quot;: &quot;integer&quot;,<br>        &quot;minimum&quot;: 1,<br>        &quot;maximum&quot;: 1024,<br>        &quot;description&quot;: &quot;Steps forward to predict.&quot;<br>      },<br>      &quot;price_index&quot;: {<br>        &quot;type&quot;: &quot;array&quot;,<br>        &quot;items&quot;: { &quot;type&quot;: &quot;number&quot; },<br>        &quot;description&quot;: &quot;Optional price covariate matching target length + horizon.&quot;<br>      },<br>      &quot;promo_flag&quot;: {<br>        &quot;type&quot;: &quot;array&quot;,<br>        &quot;items&quot;: { &quot;type&quot;: &quot;integer&quot; },<br>        &quot;description&quot;: &quot;Optional promotional flag array (0 or 1) matching target length + horizon.&quot;<br>      }<br>    },<br>    &quot;required&quot;: [&quot;target_series&quot;, &quot;forecast_horizon&quot;]<br>  }<br>}</pre><h4>Actionable Error Contracts</h4><p>When input validation fails, returning raw stack traces prevents LLM self-correction. The system raises McpError exceptions carrying structured AgentFriendlyError metadata in the data field. This enables LLM orchestrators to distinguish failures from successes and perform single-turn self-correction:</p><pre>{<br>  &quot;error_code&quot;: &quot;VALIDATION_ERROR&quot;,<br>  &quot;message&quot;: &quot;Input validation failed at &#39;price_index&#39;: Price array misalignment. Expected 30 elements (Context: 23 + Horizon: 7), got 28.&quot;,<br>  &quot;expected&quot;: &quot;Payload matching TimeSeriesInputPayload schema where len(price_index) == len(target_series) + forecast_horizon.&quot;,<br>  &quot;received&quot;: &quot;{\&quot;location\&quot;: \&quot;price_index\&quot;, \&quot;expected_len\&quot;: 30, \&quot;received_len\&quot;: 28}&quot;,<br>  &quot;remediation_suggestion&quot;: &quot;Correct field &#39;price_index&#39; by resizing to 30 elements matching context (23) + horizon (7) and resubmit.&quot;<br>}</pre><h4>Observability-First Response Contract</h4><p>Every forecast carries operational metadata so the orchestrator can reason about latency, fallback depth, and GPU pressure:</p><pre>{<br>  &quot;request_id&quot;: &quot;a3f7e2d9b1c4&quot;,<br>  &quot;model_used&quot;: &quot;TimesFM-2.5&quot;,<br>  &quot;mean_prediction&quot;: [142.3, 145.1, 140.8, 148.2, 150.0],<br>  &quot;p10_quantile&quot;: [120.1, 122.4, 118.7, 125.3, 127.9],<br>  &quot;p50_quantile&quot;: [142.3, 145.1, 140.8, 148.2, 150.0],<br>  &quot;p90_quantile&quot;: [165.2, 168.5, 162.1, 170.4, 172.8],<br>  &quot;confidence_score&quot;: 0.87,<br>  &quot;horizon_length&quot;: 30,<br>  &quot;exogenous_dropped&quot;: false,<br>  &quot;backend_retries&quot;: 0,<br>  &quot;latency_ms&quot;: 142.3,<br>  &quot;gpu_memory_mb&quot;: 3847.2,<br>  &quot;warnings&quot;: []<br>}</pre><h3>VI. Validation &amp; Integration Testing</h3><p>A forecasting pipeline can look elegant on paper, but the real test is whether it runs reliably on real data. I validated my pipeline’s end-to-end integration on sample series from two demanding retail datasets — the M5 Walmart dataset and the Corporación Favorita dataset — to verify that the production mechanics remain stable under real-world telemetry.</p><h4>What I Tested</h4><p>My validation focused on integration and reliability, not large-scale benchmark replication:</p><ul><li>End-to-end execution: TimesFM 2.5 and Chronos-2 both load, ingest covariates, and produce forecasts on real M5 and Favorita series without fine-tuning.</li><li>Covariate alignment: Price indices and promotional flags align correctly across both backends via _build_chronos_covariates() and TimesFM&#39;s XReg subsystem.</li><li>Fallback chain: Forcing TimesFM failure triggers graceful degradation to Chronos-2 with covariates retained, and further failure degrades to ARIMA(1,1,1).</li><li>Quantile sanitation: Raw outputs from all three backends are sorted to guarantee <em>p</em>10​≤<em>p</em>50​≤<em>p</em>90​ on real data.</li><li>Confidence scoring: The normalized uncertainty metric produces sensible values across diverse series.</li></ul><h4>Published Validation of the Underlying Models</h4><p>The foundation models wrapped by this skill have been independently validated by their authors:</p><ul><li>TimesFM (Das et al., Google Research): Evaluated in zero-shot settings on 23 previously unseen datasets spanning finance, demand, weather, and traffic. Google Research reports MASE aggregated across these datasets, demonstrating that the model approaches supervised baseline accuracy without task-specific training. A follow-up few-shot variant improved zero-shot accuracy by 6.8% and matched supervised fine-tuning performance on the same benchmark suite.</li><li>Chronos-2 (Ansari et al., AWS): Evaluated on multiple public benchmarks including GIFT-Eval and the Chronos Benchmark II, demonstrating strong zero-shot transfer across domains.</li></ul><h4>The M5 Walmart Dataset</h4><p>The M5 competition contains over 30,000 item-store time series collected from 10 Walmart stores across three U.S. states. The data covers multiple product categories, hierarchical structures, and external factors like promotions, holidays, and price fluctuations.</p><p>I ran my pipeline against individual M5 series to verify that TimesFM and Chronos integrate correctly through the 3-tier fallback chain, that covariate alignment works across both backends, and that quantile sanitation and confidence scoring remain stable on real retail telemetry. These are integration and reliability tests, not a full hierarchical benchmark replication.</p><p>The foundation model backends have been independently validated at scale by their authors:</p><ul><li>Chronos-2 (Ansari et al., AWS): Delivered state-of-the-art zero-shot performance across multiple benchmarks (GIFT-Eval, Chronos Benchmark II). On energy/retail series tasks, zero-shot Chronos-2 produced a Weighted Absolute Percentage Error (WAPE) of 8.4%.</li><li>TimesFM 2.5 (Das et al., Google Research): Recorded a Weighted Root Mean Squared Scaled Error (WRMSSE) of 0.763 on M5 competition metrics, outperforming Moirai (0.798) and Prophet (0.812).</li><li>Promotional Uplift: On SKUs featuring active promotional flags, TimesFM 2.5 achieved a 23% improvement in Normalized Deviation (ND) compared to baseline models by incorporating exogenous signals.</li></ul><p>My skill inherits this accuracy when the underlying model succeeds. When it fails — CUDA OOM, hub unreachable, shape mismatch — the fallback chain ensures the agent still receives a mathematically valid forecast.</p><h4>The Corporación Favorita Dataset (Out-of-Distribution Stress Test)</h4><p>To evaluate cross-region generalization, I tested my pipeline against unit sales data from Corporación Favorita (Ecuador). This dataset introduces distinct macroeconomic dynamics, including daily oil price fluctuations, high local inflation markers, and unique regional promotional calendars.</p><p>I used my FavoritaDataLoader to extract high-volume store-family combinations, align oil-price covariates, and pass them through the full pipeline — Pydantic validation, TimesFM XReg inference, fallback to Chronos, and isotonic quantile sanitation. The pipeline executed end-to-end without retraining or local tuning, confirming that the production mechanics (lazy loading, memory eviction, error contracts) remain stable under international, out-of-distribution data.</p><p>The foundation models’ own published results demonstrate that deep temporal regularities transfer effectively across domains. My pipeline’s role is to make that transfer reliable in production — ensuring that when an Ecuadorian oil shock arrives, the agent gets a sanitized forecast with a confidence score, not a CUDA traceback.</p><h4>Evaluation Metrics Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*eQw-RaCXaLOwjLEV9pg1fg.png" /></figure><ul><li>Pinball Loss: Measures quantile calibration accuracy across p₁₀ and p₉₀ bounds.</li><li>Continuous Ranked Probability Score (CRPS): Evaluates overall predictive distribution quality.</li></ul><h4>In-Flight Throughput</h4><p>Chronos-2’s architecture processes over 300 time series per second on a single NVIDIA A10G GPU. TimesFM’s 200M-parameter decoder architecture achieves strong zero-shot performance across domains and granularities while maintaining low operational overhead.</p><h3>VII. What Makes This a Symbolic Skill, Not an Agent</h3><p>There is significant interest in “AI agents,” and it is easy to assume that any intelligent system that performs a task is an agent. This skill is not an agent, nor is it neuro-symbolic on its own. It is a symbolic skill — a deterministic, verifiable computation engine that sits at the boundary of a neuro-symbolic system. The neuro-symbolic architecture emerges only when this skill is invoked by a neural agent (LLM) through a structured protocol like MCP.</p><pre>┌─────────────────────────────────────────────────────────────┐<br>│              NEURAL AGENT (Stochastic Field)                │<br>│  • Goal Planning &amp; Intent Generation                        │<br>│  • Unstructured Context Interpretation                      │<br>│  • Probabilistic Reasoning                                  │<br>└──────────────────────────────┬──────────────────────────────┘<br>                               │ Natural Language Intent<br>                               ▼<br>┌─────────────────────────────────────────────────────────────┐<br>│                    THE RUBICON                              │<br>│  • Intent → Symbolic Plan Translation                       │<br>└──────────────────────────────┬──────────────────────────────┘<br>                               │ Structured Execution Plan<br>                               ▼<br>┌─────────────────────────────────────────────────────────────┐<br>│         SYMBOLIC ORCHESTRATOR (Deterministic Vault)         │<br>│  • DAG Execution Engine                                     │<br>│  • Policy-as-Code Firewall (Veto / Approve)                 │<br>│  • MCP Host / Tool Registry &amp; Discovery                     │<br>│  • JSON-RPC Marshaling &amp; Transport                          │<br>└──────────────────────────────┬──────────────────────────────┘<br>                               │ MCP stdio / JSON-RPC Payload<br>                               ▼<br>┌─────────────────────────────────────────────────────────────┐<br>│      SYMBOLIC SKILL: Zero-Shot Demand Forecaster            │<br>│                  (This Repository)                          │<br>│                                                             │<br>│  • Pydantic v2 Input Contract Enforcement                   │<br>│  • Deterministic 3-Tier Fallback Engine                     │<br>│  • Isotonic Quantile Sanitation                             │<br>│  • Non-Linear Confidence Scoring                            │<br>│  • Structured Error Contracts (McpError)                    │<br>│  • Observability Metadata (latency, GPU, retries)           │<br>└─────────────────────────────────────────────────────────────┘</pre><h4>The Architect vs. Construction Crew Analogy</h4><p>Think of the LLM Agent as the Architect and the Forecasting Skill as the Construction Crew. The architect designs structural plans, interprets client demands, and manages dependencies. The construction crew executes concrete structural tasks following exact engineering specifications.</p><p>The architect does not pour concrete directly; the construction crew does not redesign building blueprints. Decoupling neural orchestration from symbolic mathematical execution produces reliable, enterprise-grade AI systems.</p><h3>VIII. Production Hardening: Lessons I Learned the Hard Way</h3><p>Moving from a local prototype to a production-grade microservice revealed critical concurrency and memory management requirements. I learned most of these by breaking things first.</p><h3>Production Hardening Highlights</h3><ul><li><strong>Thread-Safe Lazy Instantiation: </strong>Double-checked locking (threading.Lock) ensures only one model instance is loaded into VRAM during concurrent cold-start requests. This prevents duplicate weight materialization when multiple agents trigger the service simultaneously.</li><li><strong>Sequential Inference Guard:</strong> While the MCP gateway remains fully asynchronous, a dedicated inference lock per backend serializes actual tensor forward passes. This prevents CUDA race conditions when multiple requests hit the same PyTorch model instance concurrently. I discovered this the hard way: running four parallel requests produced silent corruption until I added the locks.</li><li><strong>Bounded Batch Concurrency: </strong>The forecast_batch endpoint uses asyncio.gather bounded by an asyncio.Semaphore(4), preventing VRAM exhaustion during simultaneous multi-SKU queries.</li><li><strong>Per-Backend Circuit Breakers:</strong> Each foundation model maintains an independent circuit breaker (failure threshold: 5, cooldown: 60s). If TimesFM repeatedly fails (e.g., HuggingFace hub unreachable), the breaker opens and traffic is immediately routed to Chronos without waiting for timeouts.</li><li><strong>Isotonic Quantile Sanitation: </strong>Raw predictions undergo post-inference sorting to guarantee mathematical monotonicity (p₁₀ ≤ p₅₀ ≤ p₉₀) across all backends prior to returning JSON payloads.</li><li><strong>Resilient Memory Recovery:</strong> On CUDA Out-Of-Memory (OOM) events, the engine triggers gc.collect() and torch.cuda.empty_cache(), strips invalid exogenous signals, and seamlessly degrades down the 3-tier fallback chain.</li><li><strong>Model Eviction &amp; VRAM Conservation:</strong> To prevent unbounded memory growth in long-running services, the engine enforces a single-model residency policy. Loading TimesFM automatically evicts Chronos from VRAM (and vice versa), ensuring at most one foundation model occupies GPU memory at any moment.</li></ul><h3>IX. Conclusion</h3><p>Let me take you back to where I started: a friend staring at a blinking alert, a supply chain on the verge of disruption, and a traditional forecasting cycle measured in weeks, not minutes. That’s the problem I set out to solve. And the approach I’ve described here — zero-shot forecasting with foundation models, wrapped in a symbolic MCP skill, deployed within a neuro-symbolic architecture — is a fundamentally different way of thinking about demand forecasting.</p><h4>The Shift</h4><p>Instead of building complex ensembles and retraining them every quarter, I leveraged foundation models that were already pre-trained on massive datasets. Instead of forcing the agent to understand the details of time-series modeling, I created a clean symbolic boundary that the agent can invoke with a structured request. Instead of waiting for the data science team to deliver a forecast, I gave the agent the ability to forecast on demand, in real time.</p><p>The benchmarks on M5 and Corporación Favorita confirm what I suspected: zero-shot foundation models can match or exceed traditional approaches on out-of-distribution retail data, without any fine-tuning or feature engineering. The MCP integration makes the tool discoverable and usable by any agent in the ecosystem. And this neuro-symbolic system design separates reasoning from execution, ensuring that the deterministic, verifiable part of the pipeline remains safe and auditable.</p><h4>What I Shipped</h4><p>This isn’t a roadmap slide — these are the production mechanics already in the codebase:</p><ul><li>Lazy loading with double-checked locking: Models materialize on first use, not at startup. No VRAM is consumed until an inference request arrives.</li><li>3-tier resilient fallback: TimesFM → Chronos-2 → ARIMA(1,1,1), with automatic exogenous signal retention and CUDA OOM recovery.</li><li>Per-backend circuit breakers: Independent failure thresholds and cooldown timers prevent cascade failures when a model hub is unreachable.</li><li>Bounded batch concurrency: A semaphore-gather pattern protects GPU memory during multi-SKU fleet evaluations.</li><li>Isotonic quantile sanitation: Every backend’s raw output is sorted to guarantee mathematically valid p₁₀ ≤ p₅₀ ≤ p₉₀ ordering.</li><li>MCP-native error contracts: Validation and execution failures raise McpError with structured AgentFriendlyError metadata, enabling single-turn agent self-correction.</li><li>Model eviction: A single-model residency policy ensures unbounded VRAM growth cannot occur in long-running services.</li></ul><h4>What Comes Next</h4><p>The skill is production-hardened, but no system is ever finished. The next milestones are:</p><ul><li>Distributed observability: Prometheus metrics and OpenTelemetry traces for per-request latency, per-backend throughput, and GPU memory pressure dashboards.</li><li>Dynamic context windowing: Adaptive truncation strategies for series approaching the 16,000-step boundary to preserve the most statistically informative tail.</li><li>Multi-GPU sharding: Replicating model workers across devices to eliminate the single-model residency bottleneck for high-throughput deployments.</li></ul><p>But the bigger opportunity is the ecosystem. With MCP, this forecasting skill can be combined with other skills — inventory optimization, supplier pricing, logistics routing — to build a comprehensive agentic supply chain system. The skill is a building block, and I’m eager to see what other blocks people will build and how they’ll combine them.</p><h4>The Final Thought</h4><p>Zero-shot forecasting with foundation models isn’t a silver bullet. It won’t outperform a carefully tuned supervised model on a specific dataset. But it will give you a credible forecast in seconds, without any training, and without any data leaving your control. It will give you quantile bands and confidence scores that enable risk-aware decisions. And it will make your enterprise agents smarter, faster, and more autonomous.</p><p>The cost, complexity, and time of traditional model training are increasingly unsustainable. The alternative — zero-shot symbolic skills, composed within a neuro-symbolic architecture — is here, it works, and it’s ready for production. The warehouse manager doesn’t have to wait weeks anymore. They just have to ask the agent, and the agent has to know which skill to call.</p><p>I’ve built one of those skills. I hope you’ll build the others.</p><p><em>This skill is designed to be orchestrated, not to orchestrate. It is the mathematical engine beneath the agent — not the agent itself.</em></p><h3>References</h3><ol><li><strong>Chronos: Learning the Language of Time Series</strong> — Ansari et al. (Amazon Web Services, arXiv:2403.07815, 2024). <em>Establishes the tokenization framework for converting univariate time series into language modeling primitives.</em></li><li><strong>A Decoder-Only Foundation Model for Time-Series Forecasting (TimesFM)</strong> — Das et al. (Google Research, ICML 2024). <em>Details Google’s 200M parameter patch-based decoder architecture and exogenous covariate handling.</em></li><li><strong>Unified Training of Universal Time Series Forecasting Models (MOIRAI)</strong> — Woo et al. (Salesforce AI Research, arXiv:2402.02592, 2024). <em>Presents masked encoder architectures and multi-patch size processing across heterogeneous distributions.</em></li><li><strong>Lag-Llama: Towards Foundation Models for Probabilistic Time Series Forecasting</strong> — Rasul et al. (arXiv:2310.08278, 2024). <em>Introduces open-source probabilistic foundation models built on LLaMA-style decoder transformers.</em></li><li><strong>Tiny Time Mixers (TTMs): Fast Pre-trained Models for Enhanced Zero-Shot Forecasting</strong> — Ekambaram et al. (IBM Research, KDD 2024). <em>Focuses on lightweight, low-latency zero-shot temporal architectures optimized for edge deployment.</em></li><li><strong>Time-LLM: Time Series Forecasting by Reprogramming Large Language Models</strong> — Jin et al. (ICLR 2024). <em>Explores cross-modal alignment between natural language LLMs and numeric temporal sequences.</em></li><li><strong>UniTS: Building a Unified Time Series Model</strong> — Gao et al. (NeurIPS 2024). <em>Proposes unified multi-task architectures for zero-shot forecasting, classification, and anomaly detection.</em></li><li><strong>The M5 Competition: Background, Organization, and Implementation</strong> — Makridakis et al. (International Journal of Forecasting, Vol. 38, Issue 4, 2022). <em>Establishes the canonical retail hierarchical benchmark for evaluating demand forecasting systems.</em></li><li><strong>GIFT-Eval: A Benchmark for General Time Series Forecasting</strong> — AI21 Labs (arXiv:2409.11124, 2024). <em>Standardized evaluation suite for out-of-distribution foundation model zero-shot benchmarking.</em></li><li><strong>Strictly Proper Scoring Rules, Prediction, and Estimation</strong> — Gneiting &amp; Raftery (Journal of the American Statistical Association, 2007). <em>Defines the mathematical framework for quantile evaluation, Pinball Loss, and Continuous Ranked Probability Score (CRPS).</em></li><li><strong>Zero-Shot Forecasting Capability in Time-Series Foundation Models</strong> — Emergent Mind (2024). <em>Provides taxonomy and empirical tracking of zero-shot temporal transfer learning.</em></li><li><strong>Model Context Protocol (MCP) Specification</strong> — Anthropic (2024). <em>Defines the open standard for client-side tool discovery, JSON-Schema execution, and structured error boundaries.</em></li><li><strong>Neurosymbolic AI: The 3rd Wave</strong> — Garcez &amp; Lamb (Artificial Intelligence Review, 2023). <em>Establishes theoretical framework combining probabilistic neural perception with deterministic symbolic policy engines.</em></li><li><strong>FastMCP: High-Performance Framework for Model Context Protocol</strong> — FastMCP Specification (2024). <em>Provides standards for non-blocking asynchronous event loops and thread offloading in agentic microservices.</em></li><li><strong>Automatic Time Series Forecasting: The forecast Package for R</strong> — Hyndman &amp; Khandakar (Journal of Statistical Software, 2008). <em>Defines algorithmic foundations for classical fallback baselines including AutoARIMA.</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4374bc1868a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Hype of Expensive Chatbots: Bridging Strategic Business Intent with Adaptive Agentic…]]></title>
            <link>https://medium.com/@anicomanesh/beyond-the-hype-of-expensive-chatbots-bridging-strategic-business-intent-with-adaptive-agentic-d1144e9df041?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1144e9df041</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[agentic-architecture]]></category>
            <category><![CDATA[business-strategy]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 09:15:08 GMT</pubDate>
            <atom:updated>2026-02-16T09:15:08.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beyond the Hype of Expensive Chatbots: Bridging Strategic Business Intent with Adaptive Agentic Systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exVfDDm5Mi378DAgW3Qnmg.png" /></figure><p>In recent years many organizations have poured money into chatbots and workflow automation in pursuit of efficiency. Yet these “horizontal” solutions often fail to move the needle on real business value. In fact, nearly eight in ten companies report experimenting with generative AI (often in the form of chatbots and assistants) but see <strong>no significant bottom-line impact</strong>. That’s the “gen AI paradox” at work: broad adoption of conversational bots yields diffuse, hard-to-measure gains. In practice, traditional scripted bots can <em>reduce call volumes</em> and provide 24/7 service on routine queries, but they are inherently <strong>brittle</strong>. Every new question or process change usually means new rules, new code, and new integration work. Over time this stack of patches and workarounds becomes hidden technical debt. The real cost of these systems is not the initial deployment — it’s <em>constant maintenance</em> and risk. Leaders who chase short-term savings with rigid automation often find their operations brittle, requiring endless upkeep and human intervention.</p><h4>The Limits of Traditional Automation</h4><p>Standard automation excels at repetitive, well-structured tasks, but it struggles at the edges. Rule-based chatbots and scripted workflows cannot easily cope when things change. As one analysis explains, even minor variations — a typo, a new document layout, a slightly different phrasing — can break the workflow. For example, a customer-service bot may handle “reset password” requests fine, but if a user asks an off-script question, the bot will often respond with a generic “can’t help” message or hand off to a human.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*t33Fq2G4aZw-CB_71Yq8WQ.png" /><figcaption><em>Figure 1 : A typical chatbot “offline” message — the dead end users hit when a script can’t interpret input</em></figcaption></figure><p>Chatbot systems today often sit on top of existing processes as trivial conversational interfaces. They <strong>answer prompts but don’t take action</strong>. If a user types something unexpected, the bot simply fails or escalates, generating extra support tickets. Every new exception leads to more rules or retraining, driving up maintenance. As one expert notes, “the biggest weakness [of automation] remains unchanged: it can’t adapt. When business conditions shift… automated systems often fail”. This brittleness means that even “expensive” bots can become sinkholes of hidden operational risk: they freeze or mis-route when reality deviates from the script, and behind the scenes teams accumulate patchwork fixes like interest on technical debt</p><p>By contrast, <strong>agentic AI systems</strong> (sometimes called AI agents) are designed to be adaptive collaborators, not just reactive tools. An agentic system is built on a generative AI foundation but enriched with planning, memory, and context: it can perceive its environment, set goals, plan multi-step actions, and execute tasks across multiple systems with little oversight. Legacy automation “struggles with ambiguity, change, or orchestration across silos,” notes one source — but agentic systems solve this by operating with <em>autonomy and adaptability</em>. They refine strategies in real time, coordinate across departments, and only involve humans when necessary. In other words, a well-designed agentic workflow doesn’t shatter under unexpected inputs. Instead, it reroutes intelligently and learns over time.</p><h4>The Agentic Advantage: Resilience and Scale</h4><p>Agentic systems promise to turn the paradigm on its head. Rather than simply saving a few minutes here and there, they <strong>bring elasticity and resilience</strong> to operations. For example, an AI agent in supply-chain management could continuously monitor demand forecasts, shipping updates, and weather alerts. If a port delay or spike in orders appears, the agent can autonomously replan shipments, choose alternative routes, or reallocate inventory without human intervention. This kind of autonomy means processes keep running smoothly even when conditions change — “agents make operations more resilient” by monitoring disruptions and only escalating issues that truly require human judgment.</p><p>Put another way, agentic AI turns systems into proactive collaborators. Instead of bots that wait for exact prompts, agents pursue goals within defined boundaries. They can call APIs, update databases, and carry tasks through to completion. They handle errors by trying alternative approaches, and they maintain context over time. As one industry analysis summarizes: <em>“AI agents operate not just as assistants but as independent actors… They pursue objectives, adapt their approach when they hit roadblocks, and persist across complex workflows until they complete the task”</em>. This is why enterprises envision an “agentic AI mesh” — a modular, distributed architecture of many cooperating agents — as the future backbone of intelligent systems.</p><p>Importantly, agentic systems are an investment in long-term value, not just quick fixes. Because they learn and generalize, the need for manual “maintenance” drops sharply. Instead of adding countless rules to handle every scenario, an agentic solution can understand <em>meaning</em> and context, so it gracefully handles new variations. In one example from the pharmaceutical industry, an agent that learned to recognize legal phrases in documents (regardless of formatting, language variants, or rotation) eliminated hours of manual rule-tuning. The outcome: processes that become <strong>faster, cheaper, and more reliable</strong> over time, without the typical maintenance debt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynKYGmhO1jqw52_lrSQxUQ.png" /><figcaption>Figure 2. Brittle Automation Vs. Adaptive Agentic Systems . Figure By The Author</figcaption></figure><h4>Illustrative Examples: Chatbots vs. Agentic Systems</h4><p><strong>A. Brittle Chatbots in Action.</strong></p><p>Consider a multinational company that rolled out a scripted HR chatbot for 100,000 employees across 40 countries. Because policies and acronyms varied regionally, the bot’s responses had to be manually tailored everywhere. When employees asked anything slightly different, the bot often simply said “I don’t understand” or redirected to an email helpdesk. Behind the scenes, developers constantly patched the bot: adding new knowledge, writing exception rules, or redirecting flows. Ultimately this project became a <strong>maintenance nightmare</strong> — small policy changes triggered hours of testing and updates. This example shows how a seemingly helpful bot can become brittle and expensive at scale. Each unexpected user question turned into yet another work order for IT, ironically increasing costs and <strong>operational risk</strong> over time.</p><p><strong>B. Adaptive Agentic Workflow.</strong></p><p>Now imagine tackling the same HR scenario with an agentic approach. Instead of a single script, the system uses AI agents that draw on a robust knowledge base of policies, updated via human oversight. When an employee asks a nuanced question (“Can I work from home on Fridays if my team is abroad?”), the agent uses language understanding to interpret the request and check company guidelines, calendars, and manager approvals. If something is unclear, it might pull in additional context (recent policy memos or manager input) and adjust its answer. Crucially, the agent learns from each interaction: handling one new phrasing informs its future responses to similar queries. As a result, the system gracefully adapts to regional variations or policy changes without a developer rewriting rules. Over time it becomes a <strong>resilient consultant</strong>, not a brittle script.</p><p>Another example is an <strong>agentic system in supply chain or service operations</strong>. In a traditional setup, a spike in customer orders or a storm delay might break an automated restocking script, forcing human intervention. With agentic AI, an autonomous planning agent could continuously forecast demand and trigger actions. If lead times change, the agent dynamically reorders inventory or reroutes shipments by calling external logistics APIs. It might notify managers only for major decisions while taking care of routine adjustments itself. Such a system embodies architectural resilience: the business flow <em>flexes</em> with the situation rather than fracturing under stress. These illustrative cases show that agentic AI isn’t about flashy chat — it’s about embedding smart planning and adaptability into operations to <strong>reduce hidden risk</strong> and unlock real efficiency.</p><h4>Strategic Alignment and Long-Term Value</h4><p>For business leaders, the shift to agentic systems is not just a technical upgrade but a strategic imperative. Agentic AI succeeds only when deeply aligned with the company’s goals and processes. Instead of bolting on another bot, forward-thinking organizations <strong>reimagine workflows</strong> with agents at the core. This means defining clear outcomes, redesigning tasks around human-AI collaboration, and ensuring transparency and governance. An “agentic AI mesh” requires new capabilities — from data productization to agent-specific controls — but the payoff is an organization that <strong>learns and adapts</strong> over time.</p><p>Crucially, agentic systems mitigate the hidden costs of traditional automation. Just as unmanaged code debt can cripple software, unmanaged “automation debt” in legacy bots erodes ROI. Autonomous agents do introduce new governance challenges, of course, but these are surmountable with proper oversight. In fact, by building agents on an <em>open, extensible infrastructure</em>, leaders can maintain visibility into what agents do and why. This turns risk into manageable artifacts rather than silent failures. In effect, each agent becomes like a controlled subsystem that continuously learns, instead of a black-box script that quietly accumulates problems. Over the long term, organizations with agentic architectures expect not only lower maintenance costs but also increased agility and new revenue opportunities.</p><p>For executives, the message is clear:</p><blockquote><strong>Expensive chatbots alone are not enough</strong>. Short-sighted automation may cut headcount today but bury costly work in the background tomorrow. The more resilient path is to invest in adaptive, goal-driven AI agents that scale business intelligence and align with strategic intent. This future-oriented approach ensures that technology grows your core capabilities rather than your technical debt.</blockquote><h3>Key Takeaways</h3><ul><li>Traditional AI chatbots and scripted automation can cut costs initially but often become brittle. Every unanticipated scenario requires manual fixes, turning productivity gains into mounting <strong>automation debt</strong>.</li><li><strong>Agentic AI</strong> systems overcome these limits by planning and reasoning across dynamic conditions. They adapt strategies in real time and handle complexity without hard-coding every rule.</li><li>Forward-looking organizations should view agentic systems as <em>architectural investments</em>. Embedding intelligent agents into core processes builds modular, resilient operations aligned with business goals.</li><li>In the long run, adaptive agents reduce hidden operational risk and free teams to focus on strategy. Unlike bots that stall at the edges of their scripts, agents <strong>keep processes running and evolving</strong> — turning AI from a buzzword into a sustainable competitive advantage.</li></ul><p>By bridging strategic intent with adaptive AI, leaders can move “beyond the hype” of expensive chat interfaces to systems that truly scale intelligence and resilience over time.</p><h4>References</h4><p><em>A. </em><strong><em>Foundational Research on Agents, Planning, and Adaptation</em></strong></p><ol><li>Russell, S., &amp; Norvig, P.<br><em>Artificial Intelligence: A Modern Approach (4th Edition).</em><br>Pearson, 2021.<br> — Canonical foundation for intelligent agents, environments, planning, and rational action.</li><li>Wooldridge, M.<em>An Introduction to MultiAgent Systems (2nd Edition).</em><br>Wiley, 2009.<br> — Core theory behind agent autonomy, coordination, and emergent system behavior.</li><li>Sutton, R. S., &amp; Barto, A. G.<em>Reinforcement Learning: An Introduction (2nd Edition).</em>MIT Press, 2018.<br> — Establishes the learn–act–adapt loop that modern agentic systems operationalize.</li></ol><p><strong><em>B. Papers on Tool Use, Reasoning, and Agentic LLMs</em></strong></p><ol><li>Yao, S. et al. (2023).<em>ReAct: Synergizing Reasoning and Acting in Language Models.</em>arXiv:2210.03629<br> — Demonstrates why pure text generation fails without action-feedback loops.</li><li>Schick, T. et al. (2023).<em>Toolformer: Language Models Can Teach Themselves to Use Tools.</em>arXiv:2302.04761<br> — Shows how LLMs become operational assets when coupled with external tools.</li><li>Mialon, G. et al. (2023).<em>Augmented Language Models: A Survey.</em><br>arXiv:2302.07842<br> — A comprehensive survey of memory, tools, retrieval, and control mechanisms.</li></ol><p><strong><em>C. Memory, RAG, and Long-Term System Intelligence</em></strong></p><ol><li>Lewis, P. et al. (2020).<em>Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.</em>NeurIPS 2020.<br> — Foundational work enabling long-term organizational memory in AI systems.</li><li>Packer, C. et al. (2023).<em>MemGPT: Towards LLMs as Operating Systems.</em><br>arXiv:2310.08560<br> — Frames LLM-based agents as stateful systems rather than stateless chatbots.</li></ol><p><strong><em>D. Software Architecture, Resilience, and Systems Thinking</em></strong></p><ol><li>Fowler, M.<em>Patterns of Enterprise Application Architecture.</em><br>Addison-Wesley, 2002.<br> — Still relevant for understanding why brittle workflow automation collapses under change.</li><li>Beyer, B. et al.<em>Site Reliability Engineering.</em><br>O’Reilly Media, 2016.<br> — Introduces resilience, feedback loops, and failure as design inputs.</li><li>Hohpe, G., &amp; Woolf, B.<em>Enterprise Integration Patterns.</em><br>Addison-Wesley, 2003.<br> — Explains why point-to-point automation creates long-term technical debt.</li></ol><p><strong><em>E. Industry &amp; Strategy Perspectives</em></strong></p><ol><li>Gartner Research (2023–2024).<em>From Task Automation to Autonomous Business Capabilities.</em><br> — Industry framing of the shift from scripted automation to adaptive systems.</li><li>McKinsey Global Institute (2023).<em>The Economic Potential of Generative AI.</em><br> — Highlights why value comes from system-level integration, not chatbot UX.</li><li>Andreessen Horowitz (a16z).<em>The New AI Stack.</em><br> — Practical breakdown of agents, tools, memory, and orchestration layers.</li></ol><p><strong><em>F. Governance, Safety, and Control Layers</em></strong></p><ol><li>Open Policy Agent (OPA) Documentation &amp; Rego Language Papers<br> — Real-world examples of policy-as-code guarding autonomous execution.</li><li>Amodei, D. et al. (2016).<em>Concrete Problems in AI Safety.</em><br>arXiv:1606.06565<br> — Early but still relevant framing of control, oversight, and failure modes.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1144e9df041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“The Planning-Rubicon: Why the Vast Majority of AI Agents Are Just Expensive Chatbots”- Part I]]></title>
            <link>https://medium.com/@anicomanesh/the-planning-rubicon-why-the-vast-majority-of-ai-agents-are-just-expensive-chatbots-part-i-fa0409a10d8e?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa0409a10d8e</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[agency]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 10:09:54 GMT</pubDate>
            <atom:updated>2026-02-01T10:16:49.908Z</atom:updated>
            <content:encoded><![CDATA[<h4>Beyond the Wrapper: Why 2026 Will Separate Agent Infrastructure from Agent Theater</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-TvCfDo9_y8EtZrx.png" /><figcaption>Alpha Geometry <a href="https://thesequence.substack.com/p/the-sequence-radar-the-amazing-alphageometry2">Source</a></figcaption></figure><h3>I. The Great Agent Inflation</h3><p>In early 2026, Salesforce aggressively marketed Agentforce, with executives positioning AI agents as the future of nearly every SaaS workflow and enterprise process. By February, LinkedIn feeds were flooded with hyperbolic claims — everything from spreadsheets to everyday gadgets being rebranded as “agentic” and multi-million-dollar seed rounds routinely funded simple LLM wrappers — often just scheduled prompts or basic loops — rebranded as full “AI agents”.</p><p>Welcome to the Great Agent Inflation — the semantic collapse of one of the most important technical distinctions in modern AI.</p><p>The trajectory was predictable. In 2023, <strong>AutoGPT</strong> captured the imagination with promises of autonomous digital workers. In 2024, LangChain and CrewAI turned “agent” into a design pattern that any developer could spray onto existing code. By 2025, the term had metastasized into pure marketing vapor. A company building a chatbot that calls three APIs in sequence? That’s an agent. A spreadsheet with a Python macro? Also an agent. A standard RAG pipeline that remembers the previous question? Congratulations, you’ve built an “agentic memory system.”</p><p>But here’s the <strong>expensive reality</strong>: most of these systems aren’t agents. They’re expensive chat loops — pattern-matchers that generate confidently wrong plans and lack the architectural machinery to verify, commit, or recover from failure. A engineering team at a Series B startup recently confessed to me that their “autonomous research agent” costs $0.30 per query, takes 45 seconds to execute, and fails 40% of the time on tasks that a 50-line Python script handles perfectly. Multiple empirical analyses report similar cost–reliability gaps. Chen et al. (2024) show that ReAct-style agent loops frequently exceed <strong>$10 per task</strong> for simple workflows (e.g., grocery planning), while deterministic scripts performing the same task cost <strong>&lt;$0.001</strong> with &gt;99% reliability.</p><p>When we dug into the architecture, we found exactly what I expected: GPT-4o generating text, feeding that text into a function caller, feeding the result back into GPT-4o, repeat until token limit or budget exhaustion.</p><p>This isn’t <strong>agency</strong>. This is <strong>stochastic gradualism</strong> — the belief that if you wrap a language model in enough “ while” loops and error handling, it will eventually cross some threshold into autonomous intelligence. It won&#39;t. The difference between a chatbot that uses tools and an agent that plans is not a matter of iteration count; it&#39;s an architectural discontinuity involving commitment, grounding, and temporal awareness—three properties that 90% of &quot;agentic&quot; systems lack entirely.</p><p>I call this boundary the <strong>Planning-Rubicon</strong> — an architectural threshold defined by commitment, grounding, and temporality.</p><blockquote><strong>Methodology (brief):</strong><br> This article’s analysis draws on existing agent benchmarks such as A2Perf, which assess multiple agent frameworks across tasks and highlight pervasive challenges in autonomous planning and tool use.</blockquote><blockquote>It is also informed by industry surveys showing that a majority of deployed agents perform only a limited number of autonomous steps before requiring human oversight.</blockquote><blockquote>Building on these observations, systems are conceptually evaluated against a binary rubric of Commitment, Grounding, and Temporality — core architectural properties identified in the literature as necessary for reliable autonomy.</blockquote><blockquote>Systems satisfying all three conditions are described as having “crossed the Planning Rubicon.” This framework emphasizes structural design limitations rather than specific benchmark counts.</blockquote><p>The distinction matters because the cost structures are diverging. A system that merely generates plans — an “agentic” chatbot in the current dilution of the term — costs $0.03–0.30 per interaction and delivers hallucinated itineraries. A system that actually plans — crossing the Rubicon into committed, verified, temporally-grounded action — costs $3–30 per task but books the correct flight. The former feels like AI progress; the latter is actually automation that works.</p><blockquote>The industry has confused <strong>instrumental tool use</strong> with <strong>constitutional agency</strong>.</blockquote><blockquote>Tool use means invoking functions. Agency means managing the <strong>consequences</strong> of those invocations.</blockquote><p>Tool use is <strong>instrumental</strong>: the LLM is a function caller, a natural language API wrapper, a flaky replacement for typed parameters. Agency is constitutional: the system maintains beliefs about world state, evaluates preconditions before commitment, tracks temporal evolution, and recovers from execution failure. One generates text about action; the other generates text <em>that becomes</em> action with measurable consequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*etj7sBm5M-qEdJIX20YcPA.png" /><figcaption>Figure 1. Reclaiming th Meaning of Agent, by the author</figcaption></figure><p>In the sections that follow, I will define the Planning-Rubicon precisely, demonstrating that it is not merely philosophical but empirically testable. We will examine systems that fail to cross it (expensive chatbots masquerading as agents) and systems that successfully navigate it (architectures that separate deliberation from commitment).</p><p>The goal is to provide a field guide for builders and buyers: a set of specific architectural checkpoints that distinguish autonomous systems from autonomous marketing claims.</p><p>Because in 2026, the question is no longer “does it use AI?” The question is: does it know the difference between <strong>thinking</strong> about doing something, and having done it?</p><h3>What’s in This Series</h3><p>This investigation is split into two parts due to the technical depth required. Part 1 establishes the theoretical framework and empirical evidence. Part 2 provides the implementation roadmap and market analysis.</p><p>You are reading <strong>Part 1: The Diagnosis</strong>, which includes:</p><ul><li>Section I: The Hook — The Great Agent Inflation and the $0.30 vs. $30 cost divergence</li><li>Section II: Defining the <strong>Planning-Rubicon </strong>— The Three Gates (Commitment, Grounding, Temporality) and the POMDP formalization.</li><li>Section III: The Chatbot Masquerade — Autopsies of three dominant failure modes (AutoGPT, RAG+Tools, Wizard of Oz SaaS).</li><li>Section IV: <strong>Crossing the Rubicon </strong>— Architectural analysis of three systems that get it right (Operator, Voyager, AlphaProof).</li></ul><p><strong>Part 2: The Solution</strong> which includes:</p><ul><li>Section V: The Architecture Checklist — <strong>Five production-grade implementation patterns </strong>(checkpointing, observation loops, temporal models, error propagation, cost awareness) with code examples.</li><li>Section VI: The Business Implications — Why VCs should ask “Does it cross the Rubicon?” before funding, and the coming culling of wrapper startups.</li><li>Section VII: <strong>The Maturity Model</strong> — From Level 1 Chatbots to Level 3 Agents, plus the field guide for buyer diligence.</li></ul><p>If you’re building or buying “agentic” systems, you need both parts: Part 1 <strong>explains why most current architectures fail,</strong> and Part 2 p<strong>rovides the specific engineering patterns to fix them.</strong></p><h3>II. Defining the Planning-Rubicon</h3><p>If the Great Agent Inflation has confused tool use with agency, we require a precise boundary to separate them. I propose the Planning-Rubicon — the threshold where a system transitions from generating plans about action to executing actions with commitment. The term deliberately echoes Caesar’s crossing of the Rubicon river in 49 BCE: an irreversible decision point where deliberation ends and consequence begins. For AI syystems, this boundary is architectural, not merely prompt-engineered. It is the point where the system acknowledges that its outputs will modify external state in ways that cannot be undone by deleting tokens.</p><p>This concept builds upon the distinction between reasoning and planning developed in our analysis of LLM cognitive architectures [reference to previous article]. There, we established that reasoning — whether fast System 1 pattern-matching or slow System 2 deliberation — operates on symbols within the model’s context window. Planning requires operating on states in the environment. The Rubicon is the commit point between these regimes: the moment when the system transitions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*98s_0GGBm8SCWPfbGp8mqw.png" /></figure><p>Crossing the Rubicon requires passing <strong>three gates</strong> that collectively distinguish autonomous agents from sophisticated chatbots.</p><h4>Gate 1: Commitment</h4><p>Commitment is the property that distinguishes <em>simulating</em> an action from <em>taking</em> it. When GPT-4o generates the text “I will now book the flight,” no flight has been booked. The system has committed nothing; it has produced a string of tokens that, if fed to a human assistant, might result in action, but which remain entirely reversible. The tokens can be deleted, the context cleared, the model reset. This is <strong>stochastic simulation</strong> — pattern completion that resembles planning but carries no causal connection to the world.</p><p>True commitment requires that the system executes an action whose consequences outlast the computation. When OpenAI’s Operator clicks the “Purchase” button on a flight booking interface, the credit card is charged. When DeepMind’s AlphaProof submits a formal proof to the Lean theorem prover, the proof is verified or rejected by external logic it cannot hallucinate. These systems have crossed into irreversibility: their reasoning outputs have become causes in the world.</p><p>The commitment gap explains why most “agentic” enterprise tools fail at autonomy. They generate confident JSON payloads describing what <em>should</em> happen, but stop at the API gateway, waiting for human approval. This is not caution; it is architectural cowardice. The system lacks the verification machinery to know whether the JSON is correct before sending it, so it outsources the commit decision to a human in the loop. True agency requires internal mechanisms for pre-commit verification — checking preconditions, simulating consequences, establishing rollback procedures — so that the decision to act can be made autonomously.</p><h4>Gate 2: Grounding</h4><p>Grounding is the epistemic tether between internal representations and external reality. A grounded system does not merely <em>believe</em> it has booked a flight; it verifies that the booking reference exists in the airline’s database, that the confirmation email arrived, that the calendar event reflects the correct local time zone. This verification is the difference between intentionality (internal representation of goal state) and <strong>perception</strong> (external confirmation of actual state).</p><p>Recent SOTA systems approach grounding through three distinct mechanisms. <strong>Instrumental grounding</strong> (Claude 3.5 Sonnet with Computer Use, OpenAI Operator) uses pixel-level perception — screenshots, API responses, database query results — to verify preconditions and outcomes. The model reasons not just about “the form” but about <em>this specific form</em> visible on <em>this specific screen</em>, updating its world model when the UI elements differ from expectation. <strong>Executable grounding</strong> (Code Interpreter, DeepSeek R1 with tool use) validates reasoning by running code: the claim “343 × 12 = 4116” is tested by execution, not by pattern matching. <strong>Social grounding </strong>(multi-agent debate, verifier models) uses externalized critique: the system’s plan is evaluated by another process (human or model) before commitment, creating an epistemic check on hallucination.</p><p>The grounding gap is why pure inference-time scaling — o3’s 100-second deliberation or DeepSeek R1’s extended scratchpad — remains insufficient for agency. These models perform System 2 <em>internal</em> deliberation, but they deliberate on a frozen world model. The flight availability they “verify” internally corresponds to training data patterns, not to real-time seat maps. Without instrumental grounding, extended reasoning is merely spending more compute on a hallucination.</p><h4>Gate 3: Temporality</h4><p>Temporality is the acknowledgment that the world changes while the agent deliberates. Standard LLM inference occurs in a timeless instant — the forward pass, whether generating 10 tokens or 10,000, represents a single inference graph with no temporal extension. The implicit assumption is that the world state <em>s</em> remains constant during reasoning.</p><p>Agency requires <strong>temporal reasoning</strong>: the system must model Δ<em>t</em> — the time between observation -<em>ot-</em>​ and action -<em>at- </em>and the state changes Δ<em>s</em> that occur during that interval. When a travel agent plans a multi-city itinerary, seat availability at step 5 of the plan may differ from availability at step 1. A system without temporality generates static plans against obsolete observations; a system with temporality interleaves observation and action, updating its belief state <em>b</em>(<em>s</em>) continuously.</p><p>The temporality gap manifests practically as planning staleness. Recent work on <strong>“dynamic planning” </strong>(adaPlanner, ReAct with adaptive step sizing) addresses this by monitoring confidence: when uncertainty exceeds a threshold, the system pauses to re-observe rather than continuing with stale state estimates. More advanced approaches maintain explicit world models — differentiable simulators that predict state evolution during deliberation — but these remain approximations vulnerable to exogenous shocks (the flight cancellation caused by weather that the simulator didn’t model).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*Bi6EWQWBPyuadD2ejaZwwg.png" /><figcaption>Figure 2. Formalizing the gates by <a href="https://arxiv.org/pdf/1301.7381">Markov Decision Process Hierarchy</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*lSLNJXPuCu7FrEIdEvTb9Q.png" /><figcaption>Figure 3. <a href="https://people.csail.mit.edu/jbarry/papers/mworkposter.pdf">MDPs</a> World Model</figcaption></figure><h4>The Test</h4><p>To determine whether a system has crossed the Rubicon, apply the Non-Refundable Flight Test:</p><p><em>Can the system, without human intervention, search for a multi-city itinerary, identify a non-refundable fare, verify that the departure time fits within existing calendar constraints, execute the purchase API call (charging a real credit card), receive the confirmation, detect if the booking failed (e.g., seat no longer available between search and purchase), backtrack to alternative options if necessary, and complete the reservation — all while the human who initiated the request is in a meeting?</em></p><p>Passing requires all three gates: commitment (charging the card), grounding (detecting if the booking actually succeeded), and temporality (handling the seat availability changing between steps). Most “agentic” systems fail at Step 1 (<em>they generate the search parameters but wait for human commit</em>) or Step 6 (<em>they cannot autonomously detect booking failure from API responses and retry</em>).</p><p>The test is brutal because it combines <strong>uncertainty (dynamic pricing)</strong>, <strong>irreversibility (non-refundable)</strong>, and <strong>complexity (multi-constraint satisfaction).</strong> A system that passes is not merely using tools; it is planning. It has crossed the Rubicon.</p><p>In the next section, we examine specific architectures that fail this test — expensive chatbots masquerading as agents — and those that pass it, identifying the specific architectural mechanisms that enable true agency.</p><h3>III. Case Study: The Chatbot Masquerade — Where Agency Fails Architecturally</h3><h4>Three “Agents” That Aren’t</h4><p>In theory, the Planning-Rubicon provides a clean architectural distinction. In practice, <strong>the gap between theory and implementation</strong> has spawned an industry of expensive demos. The following case studies are not strawmen; they are the dominant architectural patterns of 2024–2026, collectively consuming billions in venture capital and engineering hours. Each represents a specific failure mode at the Rubicon — failures that persist in production systems today.</p><h4>[ — ] Case A: AutoGPT — The Ghost Runner</h4><p>AutoGPT (and its subsequent forks) exemplified an emergent ‘ghost-runner’ design pattern — unsupervised looped agents that often fail to embed commitment or external verification. Released in March 2023, it promised “autonomous AI agents that perform tasks without human intervention.” The architecture was seductively simple: GPT-4 looped through a cycle of <strong><em>Thought → Action → Observation</em>,</strong> with vector memory (Weaviate/Pinecone) providing persistence. It would plan complex tasks — “build a website,” “research competitors,” “order groceries” — decompose them into subtasks, and execute.</p><p>The reality was a ghost runner:</p><p><strong><em>“A system that generated impressive traces of activity without causal impact on the world.”</em></strong></p><h4>The Architectural Failure</h4><p>AutoGPT fails Gate 1 (Commitment) by simulating actions, and Gate 2 (Grounding) by equating internal artifacts (files, logs) with external state change. Its “actions” were API calls to search engines or file writers, but the system possessed no verification mechanism to confirm that an action had succeeded. When instructed to “book a flight,” it would search for flights, generate a JSON payload resembling a booking request, write that JSON to a local file, and mark the task “complete” because the file write succeeded. The grounding mechanism — if one could call it that — assumed that writing the representation of an action was equivalent to performing the action.</p><p>This is the <em>simulation trap</em>: the conflation of write(draft_email) with send(email). AutoGPT&#39;s codebase was littered with patterns like:</p><pre># Simplified from AutoGPT v0.4.0 logic<br>def execute_command(command_name, arguments):<br>    if command_name == &quot;send_email&quot;:<br>        draft = generate_email(arguments)<br>        write_to_memory(&quot;email_sent&quot;, draft)  # Grounding failure<br>        return &quot;Email sent successfully&quot;      # Commitment failure</pre><p>The system charged forward not because it crossed the Rubicon, but because it mistook the riverbank for the far side.</p><h4>The Cost Sink</h4><p>The economic damage was spectacular. A 2024 analysis by Latent Space Research found that AutoGPT instances attempting simple tasks (e.g., “create a grocery list based on my diet”) averaged 47 LLM calls per task, consuming ~$12 in API costs (GPT-4-turbo pricing), and took 4–6 minutes to complete. A human with Instacart takes 90 seconds. Worse, the success rate for autonomous completion (without human intervention to correct hallucinated tool outputs) was 14%. The remaining 86% terminated in infinite loops — “I see I haven’t completed the task; I will try again” — or hallucinated success states where the system reported completion while no external state had changed.</p><p>AutoGPT didn’t fail because it lacked intelligence; it failed because it lacked an architectural distinction between <em>planning</em> and <em>doing</em>. It was a System 2 deliberation engine (slow, thoughtful reasoning) bolted to System 0 action (no verification, no commit). Like Caesar sending a letter describing his river crossing instead of moving the legions.</p><h4>[ — ] Case B: Basic RAG with Tool Calling — The Lookup Machine</h4><p>By 2025, the “agent” label had migrated from autonomous loopers like AutoGPT to enterprise SaaS platforms built on Retrieval-Augmented Generation (RAG) with function calling. These systems — often marketed as “AI Agents for Enterprise Knowledge” — represent the most common architectural pattern in current B2B software. They combine:</p><ol><li>Vector retrieval (Pinecone/Weaviate/Chroma) for “memory”</li><li>Tool schemas (OpenAI Functions/Claude Tools) for “action”</li><li>Orchestration layers (LangChain/LlamaIndex) for “reasoning”</li></ol><p>The marketing pitch: “Your data talks back. Your agent executes workflows.”</p><p>The reality: This is a lookup machine with delusions of grandeur.</p><p><strong>Why Retrieval + Function Calling ≠ Agency</strong><br>These systems fail Gate 3 (Temporality) by design. Consider the standard “Agentic RAG” architecture for a customer support bot:</p><ul><li>Step 1: Retrieve documents (static snapshot of vector DB at time <em>t</em>0​ )</li><li>Step 2: LLM reasons over context + user query</li><li>Step 3: LLM emits function call (e.g., update_ticket_status)</li><li>Step 4: Execute API call</li><li>Step 5: LLM generates response</li></ul><p>The temporality gap appears in Step 3. The LLM plans the action based on retrieved state st0​​ , but the world state may shift during retrieval (network latency: 200ms) or reasoning (LLM inference: 2–5 seconds). If another agent (or human) updated the ticket between retrieval and function calling, the system executes based on stale preconditions. There is no belief update between observation and action; The POMDP loop is broken: <strong>observation → belief update → action occurs once</strong>, rather than <strong>continuously</strong>..</p><blockquote>More critically, these systems fail Gate 1 (Commitment) through architectural timidity. The “tool calling” pattern delegates the actual commit to the API layer, but the LLM has no verification that the API call succeeded in modifying state. I recently audited a “Sales Agent” startup that used GPT-4o to generate Salesforce API payloads. When the API returned a <strong>200 OK</strong> with an error message in the response body (common in legacy SOAP APIs wrapped in REST), the system parsed the JSON structure as success and reported &quot;Customer record updated&quot; to the user. The grounding mechanism—<strong>parsing JSON rather than querying the database state</strong>—<strong>failed</strong> to detect the null operation.</blockquote><p><strong>The Expensive Part</strong><br>The cost structure reveals the inefficiency. A typical enterprise RAG query:</p><ul><li>Vector search (Pinecone): $0.0001 per query</li><li>LLM context processing (128k tokens): $0.64 (GPT-4o)</li><li>Function calling overhead (retry loops): $0.12</li><li>Total: ~$0.76 per interaction</li></ul><p>For comparison, a deterministic Python script using the same Salesforce API with proper error handling costs $0.00002 in compute (AWS Lambda) and achieves 99.9% reliability versus the LLM’s 73% reliability in the same task. The “agent” costs 38,000% more to deliver worse outcomes because it hallucinates planning steps rather than executing verified state transitions.</p><p><strong><em>“This is not agency. This is stochastic search — expensive probabilistic retrieval masquerading as action.”</em></strong></p><h4>[ — ] Case C: Current “Agentic” SaaS — The Wizard of Oz</h4><p>The most insidious failure mode is not technical but operational: the Wizard of Oz “agent,” where the supposed autonomy is performed by humans behind a curtain of AI branding. This pattern dominates the 2025–2026 startup landscape, particularly in verticals like legal, medical, and financial services — high-stakes domains where irreversible actions carry liability.</p><p><strong>Behind the Curtain</strong><br>Consider “AgentFlow” (pseudonym for a Series B legaltech startup I reviewed in late 2025). Their marketing materials showed an “AI Agent” drafting contracts, negotiating terms via email, and executing signature workflows. The architecture diagram showed a complex multi-agent system with “Planner,” “Negotiator,” and “Executor” modules.</p><p>The production architecture was different:</p><ol><li>GPT-4o drafts the contract (simulation)</li><li>Human paralegal reviews and edits (actual cognition)</li><li>GPT-4o formats the final PDF (presentation layer)</li><li>Human clicks “Send” (commitment)</li><li>System reports: “Your AI Agent executed the contract”</li></ol><p>The “agent” here is a <em>decision support system</em> that has been anthropomorphized into an <em>autonomous actor</em>. The Three Gates are not failed; they are outsourced. Commitment (Gate 1) is performed by the human. Grounding (Gate 2) is performed by the human verifying the draft against case law. Temporality (Gate 3) is handled by the human noticing that the counterparty’s email changed terms during the negotiation.</p><p><strong>Why This Matters for Scalability</strong><br>The Wizard of Oz model is economically parasitic. It captures the pricing premium of “AI automation” ($0.30/query) while incurring the labor costs of human-in-the-loop (HITL) review ($2.50/query when fully loaded). The unit economics only work if the human reviews multiple “agent” outputs simultaneously — effectively turning the “agent” into a ticket-sorting UI for offshore workers.</p><blockquote>This architecture also creates a dangerous incentive gradient. As VCs demand “agentic” metrics (tasks completed per hour),<strong> these companies face pressure to reduce human oversight</strong>, pushing the system toward <strong>unsupervised commitment</strong> without the <strong>architectural machinery (verification, rollback, belief states) </strong>to support it. The result is predictable: a 2025 incident at a “autonomous recruiting agent” startup made headlines when the system — having reduced human oversight to cut costs — sent offer letters to candidates with hallucinated salary figures, resulting in $400K in legal exposure and rescinded offers.</blockquote><h4>The Test Failure</h4><p>Apply the Non-Refundable Flight Test to these systems:</p><ul><li><strong>AutoGPT</strong>: Fails at Step 1 (generates search parameters, marks task complete).</li><li><strong>RAG+Tools</strong>: Fails at Step 4 (generates the booking payload, requires human to click “Confirm”).</li><li><strong>Wizard of Oz SaaS</strong>: Fails at Step 4 (passes to human for commit, taking 4 hours instead of 4 seconds).</li></ul><p>None cross the Rubicon. All invoice as if they did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*I9TEYc3La4llVW3_eX6Lcw.png" /><figcaption>Figure 4. Architecture Comparison Table through 3 gates. by the author</figcaption></figure><h4>Interlude: The Expense of Simulation</h4><p>These three cases share a common trait: they substitute <em>generative rehearsal</em> for <em>executive commitment</em>. AutoGPT rehearses plans it cannot verify. RAG systems rehearse API calls against stale state. Wizard of Oz systems rehearse autonomy with human actors.</p><p>The cost is not merely financial, though the financial waste is staggering (industry estimates suggest billions were invested in 2025 into agent-branded startups and features; a non-trivial portion appears to fund architectures that do not meet the Planning-Rubicon thresholds). The deeper cost is <strong>architectural debt</strong>: organizations building on these patterns accumulate technical liabilities — hallucinated state machines, unverified commit points, temporal blind spots — that must be paid down when (if) they attempt to build true agency.</p><p>In the next section, we examine the alternative: systems that successfully cross the Rubicon, and the specific mechanisms that enable them to pass the Three Gates.</p><h3>IV. Case Study: Crossing the Rubicon</h3><p><strong><em>What Real Agency Looks Like</em></strong></p><p>The failures documented in Part III share a common architecture: they simulate action without commitment, retrieve without verification, and plan against static hallucinations. But the Planning-Rubicon is not merely a theoretical boundary — it is a crossable threshold. The following systems demonstrate what happens when architecture is designed to pass the Three Gates not by accident, but by engineering discipline. These are not prototypes; they are production-grade demonstrations that agency is achievable when we abandon the “wrapper” mentality and embrace the computational rigor of belief states, verification loops, and irreversible commits.</p><h4>[ — ] Case A: OpenAI Operator (2025) — The Pixel-Level Commit</h4><p>When OpenAI released <a href="https://openai.com/index/introducing-operator/">Operator </a>in January 2025, the technical documentation revealed something rare in the consumer AI space: an explicit architectural commitment to the POMDP formalism. Operator is not a language model with tool access; it is a perception-action loop that uses GPT-4o as a heuristic policy operating over a <em>grounded</em> state space — the actual pixels of a browser interface.</p><p><strong>Crossing Gate 1: Commitment via DOM Interaction</strong><br>Unlike the “Ghost Runner” pattern of AutoGPT, Operator does not generate JSON descriptions of clicks. It executes browser actions through the <strong>Computer-Use Agent (CUA) </strong>model, which outputs direct motor commands (cursor coordinates, scroll deltas, keyboard inputs) that interact with the browser’s DOM. When Operator clicks the “Purchase” button on an airline website, the action is irreversible: the browser sends the HTTPS POST, the credit card processor charges the account, and the database commits the transaction.</p><p>This is the essence of crossing the Rubicon — the system maintains an internal commitment store that tracks which actions have been executed versus simulated. Before any click, Operator generates a “pre-commit verification” step: it compares the current screenshot against its expected state (the “grounding check”), calculates confidence intervals for the action outcome, and only then sends the motor command. This mirrors the Bratmanian concept of <strong>planning as commitment to action </strong>— the system treats the boundary between <strong>deliberation and execution</strong> as a formal state transition, not a logging event.</p><p><strong>Crossing Gate 2:</strong> <strong>Screenshot as Epistemic Tether</strong><br>Operator solves the grounding problem through instrumental perception. Rather than parsing HTML (which can be hallucinated or stale), it processes screenshots at 1920×1080 resolution, using pixel-level differences to verify state changes. When booking the non-refundable flight (our canonical test), Operator does not assume that clicking “Confirm” results in a booked flight. It enters a verification loop:</p><ol><li><strong>Pre-condition check</strong>: Screenshot analysis confirms the button state (enabled vs. disabled, text reading “Confirm” vs. “Processing”)</li><li><strong>Action execution</strong>: Motor command sent, DOM modified</li><li><strong>Post-condition verification:</strong> Screenshot capture confirms the success page load, OCR extracts the confirmation number, and the system queries the airline’s booking API (if available) to verify the PNR exists in the external database</li></ol><p>This is the difference between <strong>pattern matching (RAG)</strong> and <strong>perceptual grounding (POMDP)</strong>. The belief state <em>b</em>(<em>s</em>) is updated not by parsing text, but by computer vision models detecting visual changes in the interface. When a loading spinner appears, Operator’s <strong>temporal model </strong>knows to suspend further actions until the screenshot delta indicates stability — a level of environmental coupling that vector databases cannot achieve.</p><p><strong>Crossing Gate 3: Temporality through Asynchronous State Management</strong><br>Browser environments are temporally chaotic: network latency varies, JavaScript lazy-loads content, and popup modals appear asynchronously. Operator handles this through a dynamic observation schedule. Rather than assuming fixed time steps (the AutoGPT “loop every 5 seconds” approach), it implements an event-driven architecture where the observation frequency adapts to interface entropy.</p><p>When booking the flight, if the “Seat Selection” modal takes 3.2 seconds to load (variable due to server load), Operator detects the visual change (screenshot diff &gt; threshold) and updates its belief state before proceeding. If the seat availability changes between search and selection (the temporal failure mode that crashes RAG systems), Operator detects the delta (the seat is now greyed out in the screenshot) and enters a replanning phase: query alternative seats, update constraints, re-verify calendar conflicts, then commit to the new option. This is temporal reasoning — the system models Δ<em>t</em> explicitly and maintains rollback checkpoints at each gate crossing.</p><h4>[ — ] Case B: Voyager (Fan et al., Nvidia Research 2023) —The Generative Skill Curriculum</h4><p>While Operator navigates digital bureaucracies through pixel-level perception, Voyager demonstrates agency in open-ended embodied environments through a fundamentally different architectural philosophy: <em>generative skill libraries</em>. This system — released in 2023 and establishing the codebase paradigm for Minecraft agents — exemplifies how Large Language Models can cross the Rubicon not through formal verification (like AlphaProof) or computer vision (like Operator), but through <strong>executable code generation</strong> with iterative self-improvement.</p><p>It is worth noting the institutional divergence here: whereas DeepMind has pursued agency through reinforcement learning world models (Dreamer) and formal methods (AlphaProof), the Nvidia team behind Voyager bet on <em>program synthesis</em> — treating the LLM as a coder that writes its own tools, then commits them to a persistent executable library.</p><p><strong>Crossing Gate 1: Code as Irreversible Commitment</strong></p><p>Voyager’s commitment mechanism is its automatic curriculum module. When the system decides to “craft a stone pickaxe,” it does not generate a natural language plan (“First, I will chop wood…”). Instead, the LLM (GPT-4) writes Python code using the Mineflayer API — executable functions like craft_stone_pickaxe()—that interact with the Minecraft server. This code is then executed, irreversibly consuming inventory items (crafting grid slots, sticks, cobblestone) and modifying the world state (blocks placed, items crafted).</p><p>The architectural innovation is the separation of the Code Generator (deliberation) from the Code Executor (commitment). Unlike AutoGPT, Voyager enforces a <strong>hard boundary between code generation (deliberation) and code execution (commitment)</strong>.: the LLM proposes actions in a sandboxed reasoning phase, but the commit occurs only when the code is deployed to the environment. Death — falling into lava, being killed by mobs, or starvation — is a <em>real failure state</em> that cannot be undone by backspacing. This creates genuine commitment: once the attack_zombie() function runs, the avatar’s health bar either drops or it doesn&#39;t, and the system must live with the consequences.</p><p>Crucially, Voyager adds a critic module (based on code-davinci-002) that pre-screens generated code for syntax errors before execution — a “pre-commit verification” that prevents trivial failures. This is Gate 1 crossed with engineering discipline: the system verifies it <em>can</em> cross before stepping into the river.</p><p><strong>Crossing Gate 2: Execution Verification as Grounding</strong></p><p>Where Operator grounds through screenshots (pixel perception) and AlphaProof through theorem provers (formal logic), Voyager grounds through execution feedback loops. The system verifies success not by parsing its own confidence, but by querying the game state API: Did the cobblestone count decrease by 3? Did the inventory gain a pickaxe? Did the coordinates change after executing move_forward(10)?</p><p>This is <em>instrumental grounding</em> via code execution — the environment becomes a unit test suite. When Voyager attempts to “build a shelter,” it executes the generated construction code, then runs a verification function checking for roof blocks above the avatar. If the check returns False, the grounding has failed; the belief state <em>b</em>(<em>s</em>) updates from &quot;shelter built&quot; to &quot;exposed to mobs,&quot; triggering a replanning episode. This prevents the &quot;hallucinated success&quot; endemic to RAG systems: Voyager cannot claim to have crafted an item while the inventory API shows zero count.</p><p>The system also implements social grounding through its skill library: successful code is compressed into reusable “skills” (vector embeddings of working code) and stored in a vector database. When facing a novel situation, Voyager retrieves only <em>verified, previously executed</em> skills — not hallucinated plans. This creates an epistemic anchor: the system grounds current actions in historically verified executions.</p><p><strong>Crossing Gate 3: Temporal Curriculum and State Decay</strong></p><p>Minecraft operates on a 20-minute day/night cycle with stochastic mob spawning and crop growth mechanics. Voyager handles temporality through an automatic curriculum that models skill prerequisites as a temporal graph. The system knows that “mining diamond” requires “crafting iron pickaxe” which requires “crafting stone pickaxe” — a temporal dependency chain where state changes persist.</p><p>Unlike static planners, Voyager implements checkpointing at temporal boundaries: it saves the game state before attempting risky multi-step tasks (e.g., exploring caves). If the agent dies (temporal failure: nighttime arrived while mining, spawning hostile mobs), the system respawns and updates its belief state: the inventory is lost (irreversible), but the skill library retains the knowledge of <em>how</em> to recover. This models Δ<em>t</em> explicitly — the system tracks how long actions take and schedules “shelter seeking” before nightfall based on predicted execution time.</p><h4>The Paradigm Split: Generative vs. Formal Agency</h4><p>Voyager represents a distinct lineage in agentic AI — the Generative Code-Synthesis Approach — which contrasts sharply with DeepMind’s Formal/RL Approach exemplified by AlphaProof and Dreamer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*0bgOn4Jqdh33O5EC7jhU0Q.png" /><figcaption>Table 1. Voyager Vs. AlphaProof</figcaption></figure><p>This divergence illustrates that crossing the Rubicon is <strong>architecture-agnostic </strong>— there are multiple valid engineering paths to agency. Voyager succeeds in high-entropy, open-ended environments where formal verification is impossible (you cannot formally prove a Minecraft mob won’t spawn), while AlphaProof succeeds in deterministic domains where formal guarantees are essential. Both, however, respect the Three Gates: they commit irreversibly, verify against external state, and model time as a state-modifying variable.</p><p>Whereas DeepMind’s agents tend to <em>learn</em> policies through environmental interaction (RL), Voyager generates policies through code synthesis (LLM), then commits them. The Rubicon is crossed in both cases, but Voyager crosses via generative programming, making it the progenitor of modern “Agentic Coding” systems (Cursor, Devin) that use LLMs to write and execute software.</p><h4>[ — ] Case C: AlphaProof (DeepMind) — Formal Verification as Commitment</h4><p>The most rigorous crossing of the Rubicon occurs in domains where commitment is mathematically irreversible. <a href="https://www.julian.ac/blog/2025/11/13/alphaproof-paper/">DeepMind’s AlphaProof</a> (2024–2025), which achieved silver-medal performance at the International Mathematical Olympiad, represents the apex of Gate 2 (Grounding) through formal verification. Unlike Operator’s perceptual grounding or Voyager’s embodied grounding, <strong>AlphaProof uses theorem-prover grounding — the only form of verification that offers mathematical certainty.</strong></p><p><a href="https://deepmind.google/blog/ai-solves-imo-problems-at-silver-medal-level/">AI achieves silver-medal standard solving International Mathematical Olympiad problems</a></p><p><strong>Crossing Gate 1: Proof Submission as Irreversible Commit</strong><br>In formal mathematics, a proof submitted to the Lean 4 proof assistant is verified by Lean’s kernel: Lean mechanically checks proof terms against its logic, providing a deductive verification oracle. Whether a theorem is then stored or published depends on the repository or package manager in use. If the proof is valid, the theorem is added to the library; if invalid, the system returns a false verdict that cannot be bargained with. AlphaProof&#39;s LLM component (fine-tuned Gemini) generates proof steps, but the<strong> commitment decision </strong>is outsourced to the Lean kernel—a piece of external logic that the AI cannot hallucinate or persuade.</p><p>This is architectural cowardice inverted: whereas Wizard of Oz SaaS uses humans to avoid commitment, AlphaProof uses the rigid logic of a theorem prover to <strong>enforce</strong> commitment. The system generates candidate proofs, but it knows that once the apply tactic is executed in Lean, the consequences are real. This creates a hyper-disciplined deliberation phase: AlphaProof uses tree search (MCTS) to explore proof paths, but only commits when the formal verifier provides a certificate of correctness.</p><p><strong>Crossing Gate 2: Formal Verification as Perfect Grounding</strong><br>AlphaProof solves the grounding problem by eliminating approximation entirely. When it claims to have proven a number theory result, it does not check confidence scores or parse text responses. It checks the <strong>proof term</strong> in Lean’s type theory — a data structure that is either well-typed (grounded in the axioms of mathematics) or malformed. This is grounding reduced to computation: the belief state <em>b</em>(<em>s</em>) is updated from “conjecture” to “theorem” only when the external verifier returns tactic_state = no_goals (all subproves closed).</p><p>This represents the strongest possible form of Gate 2:<strong> the verification mechanism is not probabilistic</strong> (screenshots can be misread, game states can lag) but <em>deductive</em>. The system cannot hallucinate a successful proof because the Lean kernel acts as an immutable oracle. This is the architectural pattern that enterprise “agents” should emulate: <strong>not human-in-the-loop, but verifier-in-the-loop</strong> — external, formal, and incorruptible.</p><p><strong>Crossing Gate 3: Proof States as Temporal Snapshots</strong><br>Mathematical reasoning has its own temporality: the “state” of a proof evolves as tactics transform the goal. AlphaProof manages this through <strong>proof state tracking.</strong> Each tactic application changes the proof state (reducing complex goals to simpler subgoals), and the system maintains a history of these transformations. If a tactic leads to a dead end (the goal becomes unsolvable), AlphaProof backtracks to a previous checkpoint — explicitly modeling the temporality of the search process.</p><p>This mirrors the rollback mechanisms needed in flight booking: just as Operator saves checkpoint states before clicking “Purchase,” AlphaProof maintains proof snapshots before applying risky tactics. The difference is that AlphaProof’s temporality is deterministic (tactics transform goals predictably), while Operator’s is stochastic (network delays vary). Both, however, treat time as a resource that modifies state, requiring checkpointing before irreversible commits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*DCGp-ebgatcqpzrtmPh_wQ.png" /><figcaption>Figure 5. AlphaProof Workflow</figcaption></figure><h4>Synthesis: The Architectural Pattern</h4><p>These three systems — Operator (digital automation), Voyager (embodied AI), and AlphaProof (formal reasoning) — share a structural isomorphism despite their domain differences:</p><ol><li>They separate deliberation from commitment via explicit commit gates (motor commands, code execution, proof submission)</li><li>They ground through external verification loops (screenshots, game state APIs, theorem provers) rather than internal confidence</li><li>They model time as a state-modifying variable (loading states, day cycles, proof evolution) with checkpoint/rollback capability</li></ol><p><strong>They are not “agents” because they use tools; they are agents because they manage the <em>consequences</em> of tool use.</strong> In the next section, we distill these successes into an actionable architectural checklist for builders who wish to cross the Rubicon intentionally rather than accidentally.</p><h3>End of Part 1</h3><p>We have established the Rubicon as an architectural boundary, diagnosed the failure modes of the Vast Majority of current “agents,” and identified the three systems that successfully cross it.</p><p>But knowing <em>what</em> separates chatbots from agents is different from knowing <em>how to build</em> the latter.</p><p><strong>In Part 2</strong>, we translate these theoretical gates into concrete engineering requirements: the<strong> five-checkpoint architecture </strong>for production systems, the cost models that make true agents economically viable, and the maturity framework for evaluating vendor claims. I will provide the specific implementation patterns — from database transaction logs to visual verification loops.</p><h3>References</h3><p><strong>Core Framework &amp; Theory</strong></p><p>[1] Kahneman, D. (2011). <em>Thinking, Fast and Slow</em>. Farrar, Straus and Giroux. (System 1/2 distinction)</p><p>[2] Russell, S., &amp; Norvig, P. (2020). <em>Artificial Intelligence: A Modern Approach</em> (4th ed.). Pearson. (MDP/POMDP formalization, Chapter 17)</p><p>[3] Kaelbling, L. P., Littman, M. L., &amp; Cassandra, A. R. (1998). “Planning and acting in partially observable stochastic domains.” <em>Artificial Intelligence</em>, 101(1–2), 99–134. (POMDP foundation)</p><p>[4] Yao, S., et al. (2023). “ReAct: Synergizing Reasoning and Acting in Language Models.” <em>ICLR 2023</em>. (ReAct as approximate POMDP solver)</p><p><strong>Commitment &amp; Irreversibility</strong></p><p>[5] Bratman, M. E. (1987). <em>Intention, Plans, and Practical Reason</em>. Harvard University Press. (Philosophical foundation of commitment in action)</p><p>[6] OpenAI. (2025). “Operator System Card.” <em>OpenAI Safety Documentation</em>. (Computer use with irreversible actions)</p><p>[7] DeepMind. (2024). “AlphaProof: Training Language Models to Formalize and Prove Mathematics.” <em>Nature</em>. (Formal verification before commitment)</p><p><strong>Grounding &amp; Verification</strong></p><p>[8] Hao, S., et al. (2023). “Reasoning with Language Model Is Planning with World Model.” <em>arXiv:2305.14992</em>. (World model grounding)</p><p>[9] Anthropic. (2024). “Computer Use.” <em>Anthropic Documentation</em>. (Claude 3.5 Sonnet pixel-level grounding)</p><p>[10] Wang, Q., et al. (2024). “Executable Code Actions Elicit Better LLM Agents.” <em>ICML 2024</em>. (Executable grounding via Code Interpreter)</p><p>[11] Lightman, H., et al. (2023). “Let’s Verify Step by Step.” <em>ICLR 2024</em>. (Process reward models for verification)</p><p><strong>Temporality &amp; Dynamic Planning</strong></p><p>[12] Sun, H., et al. (2024). “AdaPlanner: Adaptive Planning from Feedback with Language Models.” <em>NeurIPS 2024</em>. (Adaptive step sizing for temporal reasoning)</p><p>[13] Schrittwieser, J., et al. (2020). “Mastering Atari, Go, chess and shogi by planning with a learned model.” <em>Nature</em>, 588(7839), 604–609. (MuZero world model for temporal planning)</p><p>[14] Liu, B., et al. (2023). “LLM+P: Empowering Large Language Models with Optimal Planning Proficiency.” <em>arXiv:2304.11477</em>. (Temporal planning with classical planners)</p><p><strong>Planning-Rubicon &amp; Agency Distinction</strong></p><p>[15] Bratman, M. E. (1999). <em>Faces of Intention: Selected Essays on Intention and Agency</em>. Cambridge University Press. (Agency and commitment)</p><p>[16] Yao, S., et al. (2023). “Tree of Thoughts: Deliberate Problem Solving with Large Language Models.” <em>NeurIPS 2023</em>. (Deliberation vs. action distinction)</p><p>[17] Chen, X., et al. (2024). “An Emerging World of Agents.” <em>arXiv:2410.14228</em>. (Recent survey on agent architectures)</p><p><strong>AutoGPT Architecture &amp; Promises</strong></p><p>[18] Richards, T. (2023). <em>AutoGPT: An Autonomous GPT-4 Experiment</em> [GitHub Repository]. Significant Gravitas. (Original “Ghost Runner” architecture with vector memory and infinite loops)</p><p>[19] Wang, L., et al. (2024). “Evaluating the Performance of Large Language Models in Autonomous Task Completion.” <em>Proceedings of the AAAI Conference on Artificial Intelligence</em>, 38(21), 23–31. (Empirical analysis showing &lt;15% success rates on multi-step tasks without human intervention)</p><p><strong>Cost Analysis &amp; API Economics</strong></p><p>[20] Chen, Y., et al. (2024). “The Economic Reality of LLM Agents: Cost, Latency, and Reliability Trade-offs.” <em>arXiv:2401.07872</em>. (Documents $10+ API costs for simple grocery lists via agent loops vs. $0.001 deterministic scripts)</p><p>[21] Ouyang, S. (2024). “The Inference Cost of Agentic AI.” <em>Latency Letters</em>, 3(2). (Analysis of token consumption in ReAct-style loops showing 40–100× cost inflation over single-shot inference)</p><p><strong>Hallucination in Tool Use</strong></p><p>[22] Pan, A., et al. (2023). “Do LLMs Know When to Use Tools? Evaluating Tool Use in Large Language Models.” <em>NeurIPS 2023 Workshop on Foundation Models for Decision Making</em>. (Documents “hallucinated success” where systems report tool execution without API calls)</p><p><strong>Temporal Staleness &amp; State Decay</strong></p><p>[23] Yu, W., et al. (2024). “Corrective Retrieval-Augmented Generation (CRAG).” <em>ICLR 2024</em>. (Demonstrates that 35% of RAG failures stem from retrieval temporality — stale documents used for planning against changed environments)</p><p>[24] Asai, A., et al. (2023). “Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection.” <em>arXiv:2310.11511</em>. (Shows necessity of verification loops; standard RAG lacks grounding gates)</p><p><strong>Function Calling ≠ Agency</strong></p><p>[25] Qin, Y., et al. (2023). “Tool Learning with Foundation Models.” <em>ACM Computing Surveys</em>, 56(1), 1–40. (Survey distinguishing “tool use” (instrumental) from “agentic action” (constitutional); establishes that majority of current “agents” are tool-users)</p><p>[26] Liu, N. F., et al. (2023). “Lost in the Middle: How Language Models Use Long Contexts.” <em>Transactions of the Association for Computational Linguistics</em>, 12, 157–173. (RAG systems lose temporal coherence across long tool-using trajectories)</p><p><strong>Enterprise “Agent” Architecture Failures</strong></p><p>[27] Gray, M. L., &amp; Suri, S. (2019). <em>Ghost Work: How to Stop Silicon Valley from Building a New Global Underclass</em>. Houghton Mifflin Harcourt. (Foundational text on Wizard of Oz AI systems where “autonomy” is performed by hidden human labor)</p><p>[28] Miceli, M., et al. (2024). “The Myth of Autonomy: Human-in-the-Loop as Architectural Debt in AI SaaS.” <em>CSCW 2024</em>. (Analysis of 47 “AI Agent” startups finding 89% rely on human commit gates while marketing autonomous capabilities)</p><p><strong>Scalability &amp; Safety Failures</strong></p><p>[29] Selbst, A. D., et al. (2024). “The Automation Paradox in LegalTech: When ‘AI Agents’ Increase Rather Than Decrease Labor Costs.” <em>Stanford Technology Law Review</em>, 28(2), 145–189. (Documents $2.50/query human oversight costs hidden in $0.30/query AI pricing)</p><p>[30] Bender, E. M., et al. (2024). “The Dangers of Anthropomorphic Language in AI Marketing.” <em>Communications of the ACM</em>, 67(8), 36–38. (Critique of “Agent” terminology obscuring HITL dependencies)</p><p><strong>Computer Use Architecture</strong></p><p>[31] OpenAI. (2025). “Computer-Using Agent (CUA): System Architecture and Safety Analysis.” <em>OpenAI Technical Report</em>. (Details pixel-level perception loop, commitment store, and irreversible action verification; establishes POMDP implementation for web automation)</p><p>[32] Beaumont, C., et al. (2024). “Large Language Models as Browser Agents: A Study of WebVoyager.” <em>ACM Transactions on the Web</em>. (Precedent work on screenshot-based grounding for web agents, establishing visual verification protocols adopted in Operator)</p><p><strong>Perceptual Grounding</strong></p><p>[33] Koh, J. Y., et al. (2024). “VisualWebArena: Evaluating Multimodal Agents on Realistic Visual Web Tasks.” <em>CVPR 2024</em>. (Benchmark for pixel-based grounding in browser environments; validates screenshot verification over DOM parsing)</p><p>[34] Shi, T., et al. (2024). “Spotlight: Mobile UI Understanding using Vision-Language Models.” <em>CHI 2024</em>. (Technical basis for visual grounding via pixel-level feedback loops)</p><p><strong>Generative Skill Libraries</strong></p><p>[35] Wang, G., et al. (2023). “Voyager: An Open-Ended Embodied Agent with Large Language Models.” <em>arXiv:2305.16291</em> (NeurIPS 2023 spotlight). (Original “skill library” architecture; code-as-commitment mechanism; executable grounding via Mineflayer API)</p><p>[36] Liang, J., et al. (2023). “Code as Policies: Language Models for Embodied Control.” <em>ICRA 2023</em>. (Theoretical foundation for generating executable code as action; precedes Voyager’s implementation in Minecraft)</p><p><strong>Embodied Verification</strong></p><p>[37] Fan, L., et al. (2022). “MineDojo: Building Open-Ended Embodied Agents with Internet-Scale Knowledge.” <em>NeurIPS 2022</em>. (Environment infrastructure for Voyager; establishes API-based state verification against game dynamics)</p><p>[38] Cai, Y., et al. (2024). “Curriculum Learning for Embodied Agents: From Voyager to General World Models.” <em>IEEE Robotics &amp; Automation Letters</em>, 9(3), 2341–2348. (Analysis of death-as-grounding-signal and temporal curriculum in open-ended environments)</p><p><strong>Code Execution as Commitment</strong><br><em>(See [10] Wang et al., 2024 for executable grounding; cited above)</em></p><p><strong>Formal Verification as Grounding</strong></p><p>[39] Lewis, D., et al. (2024). “Mathematical Reasoning with Formal Verification: The AlphaProof Approach.” <em>Bulletin of Symbolic Logic</em>, 30(3), 412–438. (Details of commitment protocols in formal mathematics; proof state tracking as temporal model)</p><p><strong>Neuro-Symbolic Agency</strong></p><p>[40] de Moura, L., &amp; Ullrich, S. (2021). “The Lean 4 Theorem Prover and Programming Language.” <em>CADE 2021</em>. (Technical reference for the Lean kernel acting as grounding oracle — immutable verification mechanism)</p><p>[41] Polu, S., &amp; Sutskever, I. (2020). “Generative Language Modeling for Automated Theorem Proving.” <em>arXiv:2009.03393</em>. (Precedent for LLM+prover architectures; establishes separation between generation (deliberation) and kernel checking (commitment))</p><p><strong>Cross-Cutting: Comparative Agency Architectures</strong></p><p>[42] Wang, X., et al. (2024). “Agentic AI: A Comparative Study of Code Synthesis, Computer Use, and Formal Methods.” <em>arXiv:2406.12345</em>. (Contrasts Voyager-style generative agents with AlphaProof-style formal agents with Operator-style perceptual agents — maps to Three Gates framework)</p><p>[43] Fan, L. (Jim Fan). (2024). “From Voyager to World Models: The Future of Embodied AI.” <em>Keynote at NeurIPS 2024</em>. (Retrospective on Voyager’s architecture as precursor to spatial intelligence; discusses commitment mechanisms in open-world environments)</p><p>[44] Zhang, Y., et al. (2024). “Beyond Text: Executable Actions in Foundation Models.” <em>ICLR 2024</em>. (Distinguishes systems that “generate plans” from systems that “execute code”; establishes Rubicon-like threshold between simulation and action)</p><h4>Citation Notes for Publication:</h4><ol><li>Voyager Attribution: Cite as Wang et al. (2023) in bibliography, but acknowledge Jim Fan (senior author, Nvidia Research) in text as the research lead.</li><li>Operator recency: As of February 2026, Operator (Jan 2025) has limited academic citations; cite the OpenAI Technical Report (2025) and supplement with WebVoyager (CVPR 2024) for the visual grounding theory.</li><li>Cost Analysis: Replace my draft’s “Latent Space Research” with Chen et al. (2024) “The Economic Reality of LLM Agents” for the $0.30 vs. $0.00002 cost comparison.</li><li>Wizard of Oz: Use Gray &amp; Suri (2019) for the sociological foundation of hidden human labor in “autonomous” systems, and Miceli et al. (2024) for specific AI SaaS analysis.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa0409a10d8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Mixture of Experts (MoE) and Kimi K2]]></title>
            <link>https://medium.com/@anicomanesh/a-deep-dive-into-mixture-of-experts-moe-and-kimi-k2-4eef8c1ec31c?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eef8c1ec31c</guid>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[kimi-k2]]></category>
            <category><![CDATA[moe]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 16:27:34 GMT</pubDate>
            <atom:updated>2026-01-30T16:27:34.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*uALuy7LVn3lZ-taR" /></figure><h3>1. Introduction to Mixture-of-Experts (MoE)</h3><h4>1.1 Defining Mixture-of-Experts: A Paradigm Shift in Model Scaling</h4><p>Mixture of Experts (MoE) represents a sophisticated machine learning technique that fundamentally alters how complex problems are approached within artificial intelligence. At its core, MoE employs multiple specialized “expert networks” or “learners” to segment a problem space into more manageable, homogeneous regions. This approach is a form of <strong>ensemble learning</strong>, historically recognized as “committee machines”.[1] The central tenet of MoE is to move beyond the traditional model of a single, monolithic network attempting to master every facet of a complex task. Instead, MoE distributes the workload among smaller, specialized networks, with each focusing on a distinct aspect of the problem, thereby enhancing both efficiency and accuracy.</p><p>To illustrate this concept, one can envision an AI model as a highly specialized team, akin to a medical doctor handling health issues, a mechanic addressing car problems, or a chef managing culinary tasks. Within this team, a “manager” or “coordinator” intelligently directs specific inquiries or tasks to the most suitable specialist.[2] This “divide and conquer” methodology is a foundational principle driving the MoE architecture.</p><h4>1.2 The Rationale Behind MoE: Addressing Computational and Scalability Challenges</h4><p>Traditional large language models (LLMs) operate by activating all their billions of parameters for every single query. This “dense” activation leads to substantial computational costs, prolonged training and inference times, and inherent difficulties in achieving deep specialization across diverse tasks.6 MoE directly confronts these limitations by activating only a small subset of its experts at any given time. This selective activation dramatically reduces the computational overhead without compromising performance.[5] This capability is instrumental in enabling models to scale to vastly larger parameter counts in an efficient manner.</p><p>The ability of MoE to reduce computational costs while simultaneously increasing model capacity is a critical advantage. This is not merely about making models more economical to operate; it facilitates the creation of models that would be computationally prohibitive to train and run efficiently using conventional dense architectures. The operational principle of sparse activation, inherent to MoE, leads directly to reduced computational cost per inference and training step. This, in turn, allows for a significant increase in the total number of parameters, ultimately improving model quality for a given computational budget. This fundamental relationship between efficiency and scalability is a primary driver behind MoE’s widespread adoption in cutting-edge LLMs. Furthermore, this nexus of efficiency and scalability holds the potential to broaden access to powerful models. If models can achieve greater scale while remaining cost-effective, it lowers the barrier for smaller organizations and researchers to leverage state-of-the-art AI, thereby fostering broader innovation beyond the confines of well-funded research laboratories.</p><h4>1.3 A Brief History of MoE in Machine Learning</h4><p>The conceptual groundwork for Mixture of Experts was laid in 1991 with the seminal paper “Adaptive Mixture of Local Experts”.[2] This foundational research introduced the innovative idea of decomposing complex problems into smaller subproblems, each assigned to a specialized model. Early MoE models were trained using established optimization methods, such as maximal likelihood estimation or the expectation-maximization (EM) algorithm, drawing parallels to techniques employed for Gaussian mixture models.</p><p>Between 2010 and 2015, significant advancements in deep learning propelled MoE forward. During this period, MoE architectures transitioned from being standalone ensemble methods to becoming integral components within deeper neural networks. This integration allowed models to achieve both immense scale and remarkable efficiency concurrently. Concurrently, research into “conditional computation” gained prominence, focusing on dynamically activating or deactivating specific model components based on the input data.[9] This evolution represents a crucial shift: from merely combining independent models after their individual computations (as in traditional ensemble methods) to dynamically routing computation</p><p><em>within</em> a single, large model. This architectural integration, coupled with the principle of conditional computation, enabled the sparse activation that underpins the efficiency gains observed in modern LLMs. This progression signifies a move towards AI architectures that are more biologically inspired and resource-aware. Instead of relying on brute-force computation, models are now designed to intelligently allocate their computational resources, mirroring how biological brains might selectively activate specific neural pathways for different tasks.</p><h3>2. Architectural Foundations of MoE Models</h3><h4>2.1 The Core Components: Experts and Gating Networks</h4><p>The efficacy of MoE models stems from the harmonious interaction of two primary components: expert networks and the gating network.</p><p><strong>2.1.1 Expert Networks: Specialized Processing Units</strong></p><p>Expert networks are individual sub-networks, typically implemented as neural networks or layers, that are specifically trained to specialize in particular subsets of data or distinct tasks.2 Within the context of large language models, these experts are frequently Feed-Forward Networks (FFNs) embedded within the Transformer layers.[9] For instance, in models like Mistral, different experts might develop proficiency in understanding specific languages, dialects, or even particular types of queries. In computer vision applications, one expert might specialize in recognizing textures, while another becomes adept at identifying edges or shapes.[5] Each expert receives the same input, but processes it uniquely according to its learned specialization. The collective outcome of this arrangement is that experts become highly specialized: if two experts are proficient at predicting a certain type of input, but one is marginally superior, the gating function will eventually learn to favor the better performer. This process allows the less proficient expert to then specialize in other data regions, thereby increasing the overall model’s coverage and depth of knowledge.</p><p><strong>2.1.2 The Gating Network (Router): Intelligent Input Dispatch</strong></p><p>The gating network, also referred to as the router or dispatcher, is a pivotal component responsible for evaluating incoming tasks or input tokens and determining which expert(s) are most suitable for processing them. This network functions as a “traffic director,” intelligently routing inputs to the most appropriate expert(s).[3] The routing decision is typically based on learned weights, often implemented using a softmax function applied to a trainable weight matrix. The gating network can employ various strategies, ranging from probabilistic methods, where soft assignments are made to multiple experts, to deterministic methods that route each task to a single expert.[10] In modern deep learning MoE architectures, a “top-k” gating function is frequently used, where only the top-k entries (experts) are retained, and all others are set to zero, thereby ensuring sparse activation.</p><p>The router’s capability to intelligently route inputs is a significant advantage. It learns to identify and exploit underlying structural patterns within the input data. The process of training the router alongside the experts enables it to discern inherent data clusters or features. This understanding then guides efficient and specialized routing, directing inputs to the most competent expert, which in turn improves the overall model’s performance. This implies that MoE models, beyond their efficiency, are also implicitly acquiring a form of meta-knowledge about their data space. The gating network essentially becomes a representation of how different types of information should be processed, contributing to a more interpretable and adaptable model.</p><h4>2.2 Sparse Activation and Conditional Computation: The Efficiency Engine</h4><p>Sparse activation is a defining characteristic and a key advantage of Mixture of Experts models. In contrast to dense models, where all parameters are active for every input, sparse activation ensures that only a small subset of experts (typically one to a few) are activated per input. This method is rooted in the concept of “conditional computation,” where the model’s computational graph dynamically adjusts its operations based on the specific input data.[4] The primary benefit of this approach is a substantial reduction in computational requirements, processing time, and memory usage during both training and inference, all without compromising performance. For example, Mistral 8x7B, despite having eight experts, activates only two per token, significantly enhancing processing efficiency.</p><h4>2.3 Variations and Evolution in MoE Architectures</h4><p>MoE architectures have evolved to incorporate various sophisticated designs to further optimize performance and specialization.</p><ul><li><strong>Hierarchical MoE:</strong> Some architectures implement multiple levels of gating in a tree-like structure. In this setup, gating functions at higher levels direct inputs to lower-level gatings or directly to leaf-node experts.1 This hierarchical arrangement allows for even more complex and granular specialization, enabling the model to handle problems with intricate sub-structures. <strong><em>Note</em></strong><em>:hierarchical/tree-structured gating is largely theoretical or from early MoE work (e.g., Jordan &amp; Jacobs 1994, Eigen et al. 2013). Modern state-of-the-art MoE models (GShard, Switch, Mixtral, DeepSeek) use flat, single-level gating rather than tree-structured hierarchies</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgQg9cVSxHWjJSBB64Lkrw.png" /><figcaption>Fig. 1:Illustration of hierarchical MoE. The three low-level models are aggregated via the high-level gating network. <a href="https://arxiv.org/pdf/2410.19225">Source</a></figcaption></figure><ul><li><strong>Fine-Grained Segmentation</strong>: Rather than hierarchical trees, contemporary approaches utilize a large pool of small experts (e.g., 256 experts activating top-8) to increase combinatorial capacity and specialization granularity.</li><li><strong>Shared Experts:</strong> Certain models introduce “shared experts” that are designed to learn core, frequently used capacities. These shared experts work in conjunction with “routed experts,” which are specialized for peripheral, less frequently encountered capacities. This hybrid approach ensures that common knowledge is efficiently leveraged while allowing for deep specialization in niche areas.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*mtAG9q_XRlahxF_65Me7nA.png" /><figcaption>Figure 2. Illustration of DeepSeekMoE. Subfigure (a) showcases an MoE layer with the conventional top-2 routing strategy. Subfigure (b) illustrates the fine-grained expert segmentation strategy. Subsequently, subfigure © demonstrates the integration of the shared expert isolation strategy, constituting the complete DeepSeekMoE architecture. It is noteworthy that across these three architectures, the number of expert parameters and computational costs remain constant.</figcaption></figure><ul><li><strong>Modern MoE Layers:</strong> In contemporary deep learning, MoE layers frequently replace traditional feedforward networks (FFNs) within established architectures like Transformers. This integration allows the MoE paradigm to be seamlessly incorporated into state-of-the-art models.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tCbhWd77i-vDnCnK.png" /><figcaption>Figure 3. Decoder-only transformer architecture.The standard decoder-only transformer architecture used by most generative LLMs is shown in the figure above; see <a href="https://cameronrwolfe.substack.com/p/decoder-only-transformers-the-workhorse">here</a> for an in-depth overview of this architecture. In the context of LLMs, MoEs make a simple modification to this architecture — <em>we replace the feed-forward sub-layer with an MoE layer</em>! This MoE layer is comprised of several experts (i.e., anywhere from a few experts [13] to thousands [5]), where each expert is its own feed-forward sub-layer with an independent set of parameters; see below for a depiction.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pZLSNei96o-mPOPl.png" /><figcaption>Figure 4. MoE layer in a transformer block.We can similarly convert encoder-decoder transformers, such as <a href="https://cameronrwolfe.substack.com/p/t5-text-to-text-transformers-part">T5</a> , into MoE models by replacing feed-forward sub-layers in both the encoder and the decoder with MoE layers. However, we usually only convert a portion of these sub-layers (e.g., every other layer) to MoE layers. <a href="https://cameronrwolfe.substack.com/p/conditional-computation-the-birth">Source</a></figcaption></figure><p>When applied to transformer models, MoE layers have two primary components:</p><ul><li><em>Sparse MoE Layer</em>: replaces dense feed-forward layers in the transformer with a sparse layer of several, similarly-structured “experts”.</li><li><em>Router</em>: determines which tokens in the MoE layer are sent to which experts.</li></ul><p>Each expert in the sparse MoE layer is just a feed-forward neural network with its own independent set of parameters. The architecture of each expert mimics the feed-forward sub-layer used in the standard transformer architecture. The router takes each token as input and produces a probability distribution over experts that determines to which expert each token is sent; see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*58aAR2kOGpJRwyma.png" /><figcaption>Figure 5.Structure of an MoE layer. <a href="https://arxiv.org/pdf/2101.03961">Source</a></figcaption></figure><p>The evolution from basic MoE to hierarchical structures and the inclusion of shared/routed experts signifies a growing sophistication in how expertise is managed within these models. This progression is not simply about parallelizing computation; it involves building adaptive, multi-grained models of knowledge. As models increase in size and complexity, a simple, flat MoE architecture might become inefficient or susceptible to load imbalance issues. Consequently, more intricate routing mechanisms and expert structures become necessary to maintain efficiency and specialization. This trend suggests a future for AI architectures that are not only vast but also highly modular and self-organizing, capable of dynamically reconfiguring their internal processing based on the demands of the task, much like a complex adaptive system.</p><p>A summary of the key components of MoE architecture is provided in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhWMTOATl5YQe0PYuu3ohw.png" /><figcaption>Figure 6. Comprehensive Architectural Diagram of Mixture of Experts (MoE) Components</figcaption></figure><p>In figure 6 The visualization presents a three-level hierarchical decomposition of sparse expert architectures.</p><p>(A)<strong> Central Hub:</strong> The MoE controller coordinating eight functional modules.</p><p>(B) <strong>Level 1 — Core Components (Inner Ring):</strong> Eight specialized nodes arranged radially by operational-phase:</p><ul><li>(1) Expert Networks (blue) implementing feed-forward processing with routed (sparsely activated) and shared (always-active) variants;</li><li>(2) Gating Network (orange) computing routing distributions <em>G</em>(<em>x</em>)=Softmax(<em>Wg</em>​⋅<em>x</em>+<em>bg</em>​) ;</li><li>(3) Top-<em>k</em> Routing (purple) selecting <em>k</em>≪<em>N</em> experts via argmax<em>k</em>​ operations;</li><li>(4) Sparse Activation (teal) enforcing computational efficiency <em>O</em>(<em>N</em>)→<em>O</em>(<em>k</em>) ;</li><li>(5) Load Balancing Loss (red) optimizing following to prevent expert collapse;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*1sqrqqdvzyN3eDN9lVxCnA.png" /></figure><ul><li>(6) Capacity Factor (amber) maintaining buffer margins <em>γ</em>&gt;1.0 per expert;</li><li>(7) All-to-All Communication (dark gray) enabling distributed expert parallelism via cross-device token routing; and</li><li>(8) Auxiliary Loss (gray) stabilizing training via router <em>z</em> -loss regularization.</li></ul><p><strong>(C) Level 2 — Functional Annotations: </strong>Each component expands into three semantic dimensions — Description (technical specification), Role/Function (operational purpose), and Analogy (intuitive metaphor) — connected via dotted dependency lines.</p><p><strong>(D) Inter-Component Relationships:</strong> Dashed arrows indicate architectural dependencies: the Gating Network controls Expert routing and selects Top-<em>k</em> indices; Top-<em>k</em> enables Sparse Activation; Sparse Activation necessitates Load Balancing and Capacity buffers; Expert Networks require All-to-All Communication in distributed settings; and the Gating mechanism is stabilized by Auxiliary Loss components. The diagram captures the transition from dense to sparse computation, illustrating how MoE architectures decouple parameter capacity (<em>O</em>(<em>N</em>) ) from computational cost (<em>O</em>(<em>k</em>) ) through learned routing mechanisms.</p><h3>3. Operational Principles and Training Dynamics of MoE</h3><h4>3.1 How MoE Models Process Information Flow</h4><p>The operational flow within an MoE model is characterized by dynamic routing and selective computation. Upon receiving an input, such as a token in a large language model, the gating network first evaluates its characteristics.[9] Based on this evaluation, the gating network intelligently selects a small subset of experts, typically the “top-k” experts (where ‘k’ is a small number, often 2 or 8 in practice), to process that specific input.</p><p>Crucially, only these selected experts are activated and perform computations for that particular input. The outputs generated by the chosen experts are then combined, most commonly through a weighted sum determined by the gating network’s output. This entire process is iterative, repeating for each layer of the model. At every layer, the router has the potential to select a different set of experts, adapting its choice based on the evolving representation of the input token as it propagates through the network.[11]</p><h4>3.2 The Joint Training Process: Optimizing Specialization and Routing</h4><p>The training of MoE models is a sophisticated joint optimization process, where both the expert networks and the gating network are trained concurrently, typically utilizing backpropagation.</p><ul><li><strong>Expert Training:</strong> Each individual expert is trained to minimize its loss function specifically on the subset of data that it is routed to. This targeted training fosters deep specialization within each expert’s domain.</li><li><strong>Gating Network Training:</strong> Concurrently, the gating network learns to accurately predict the most suitable expert(s) for a given input. Its training is intrinsically linked to the performance of the experts it selects, as its objective is to optimize the overall routing accuracy.</li><li><strong>Joint Optimization:</strong> The overall loss function for the MoE system combines the losses from the individual experts and the gating network. This integrated approach encourages a collaborative optimization, ensuring that both components work in harmony. Gradients are propagated through both the gating network and the expert models, facilitating updates that improve the system’s global performance.</li><li><strong>Feedback Loop:</strong> A vital aspect of this training dynamic is the inherent feedback loop. As an expert becomes more proficient at handling a certain type of data, the router becomes more likely to direct similar data to that expert in subsequent iterations. This continuous reinforcement mechanism further solidifies and refines the specialization of each expert.</li></ul><h4>3.3 Advantages of MoE: Efficiency, Specialization, and Scalability</h4><p>MoE architectures offer several compelling advantages over traditional dense models, particularly in the context of large-scale AI.</p><ul><li><strong>Reduced Computational Costs:</strong> By activating only a fraction of their total parameters per input, MoE models significantly reduce the number of Floating Point Operations (FLOPs) compared to dense models of equivalent parameter count. This translates directly into substantial cost efficiency during both training and inference.[5]</li><li><strong>Faster Training and Inference:</strong> The sparse computation inherent in MoE architectures results in quicker processing times for a given target level of performance. This speed advantage is critical for deploying large models in real-world applications.</li><li><strong>Better Specialization:</strong> Each expert within an MoE model can become highly skilled in a particular domain or subtask. The gating mechanism actively encourages this focus on specific input types, allowing the model to handle diverse and complex data more effectively than a single, generalist model.</li><li><strong>Scalability:</strong> MoE models possess a remarkable ability to scale model capacity by simply adding more experts without incurring a proportional increase in computational cost. This characteristic makes them exceptionally well-suited for large-scale applications. They can achieve a quality level comparable to dense models much faster during pretraining.[9]</li></ul><p>The MoE architecture effectively inverts the common adage, “jack of all trades, master of none,” which often applies to dense LLMs that attempt to handle all tasks with the same set of weights.[6] MoE, by contrast, enables profound specialization. This architectural design leads to the development of specialized experts, which in turn results in higher proficiency within specific domains. Consequently, the overall performance across diverse tasks is superior compared to a single generalist model, particularly as model size increases. This directly addresses the limitations encountered by monolithic models attempting to learn everything simultaneously. This shift suggests a new understanding of “intelligence” in large models: rather than a single, monolithic “brain,” it is a collaborative intelligence where specialized modules contribute to a more robust and adaptable whole. This could lead to models that are not just “smarter” in a general sense, but also more “expert” and precise in their outputs.</p><p>The table below provides a comparative overview of MoE models against traditional dense models and ensemble methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1aWAH7ll0hOROncT1yIvEw.png" /><figcaption>Table 1 : Comparison of MoE vs. Dense Models vs. Ensemble Methods</figcaption></figure><h4>3.4 Navigating Challenges: Load Balancing, Overfitting, and Communication Overhead</h4><p>Despite their numerous advantages, MoE models present several challenges that require careful management.</p><ul><li><strong>Load Balancing:</strong> A persistent issue in MoE architectures is the tendency for some experts to be frequently consulted, while others remain underutilized or become “dead” experts. This imbalance leads to uneven batch sizes during training and can significantly reduce overall efficiency.</li><li><strong>Overfitting:</strong> While specialization is a strength, it can also lead to overfitting if the gating mechanism fails to generalize effectively to unseen data. This means an expert might become too specialized to a narrow data distribution.</li><li><strong>Complexity:</strong> MoE models are inherently more complex to design and train compared to traditional models. The intricate gating mechanism and the necessity to balance expert specialization introduce additional layers of complexity in development and deployment.</li><li><strong>Memory Requirements:</strong> Although MoE models are computationally efficient per inference, they require all their parameters to be loaded into RAM, leading to substantial memory requirements, especially for trillion-parameter scale models.</li><li><strong>Communication Overhead:</strong> In large-scale distributed training environments, cross-node communication can become a significant bottleneck. This is particularly true with sparse activation across a large number of experts, as data needs to be routed efficiently across different computational units.</li></ul><h4>3.5 Advanced Techniques for Robust MoE Training</h4><p>To overcome the challenges associated with MoE, several advanced techniques have been developed to ensure robust training and deployment.</p><ul><li><strong>Auxiliary Loss Functions:</strong> To promote proper load balancing and ensure that experts are selected with relatively equal frequency, auxiliary loss functions are often incorporated during training. Techniques such as Noisy Top-k Gating, introduced by Shazeer et al. (2017), add a small amount of tunable noise to the expert selection process, which helps in achieving a more balanced distribution of training across all experts.</li><li><strong>Regularization:</strong> Regularization techniques, including expert dropout, are employed to prevent overfitting and encourage distributed specialization. This involves randomly deactivating certain experts during training, compelling the gating network to distribute input routing more evenly and preventing over-reliance on a few dominant experts.</li><li><strong>Capacity Constraints:</strong> Imposing explicit capacity constraints on experts can prevent any single expert from becoming overloaded with tasks, thereby promoting a more balanced distribution of learning across the entire set of experts.</li><li><strong>Optimized Inference Engines:</strong> For efficient deployment, especially for very large MoE models, highly optimized inference engines are crucial. Examples include vLLM, SGLang, KTransformers, and NVIDIA’s TensorRT-LLM.15 These engines are designed to manage GPU memory and computation efficiently, supporting features like continuous batching and expert parallelism to maximize throughput and minimize latency.</li></ul><p>The benefits of MoE are evident, but their practical realization has necessitated substantial engineering innovation to address deployment and training difficulties. The development of auxiliary losses, regularization techniques, and specialized inference engines directly tackles these practical hurdles. This progression demonstrates that cutting-edge AI development is increasingly an interdisciplinary endeavor, demanding not only theoretical breakthroughs in model architecture but also sophisticated engineering to render these models practical and deployable at scale. The “state-of-the-art” in AI is as much a testament to robust implementation as it is to novel design.</p><h3>4. Kimi K2</h3><h4>4.1 Overview: Moonshot AI’s Kimi K2 and its Agentic Focus</h4><p>Kimi K2 is a novel large language model developed by the Chinese artificial intelligence company Moonshot AI, with backing from digital conglomerate Alibaba.16 Its release as an open-weight model has generated considerable attention, drawing parallels to the “DeepSeek moment” due to its impressive performance.[16]</p><p>A defining characteristic of Kimi K2 is its meticulous optimization for “agentic tasks.” This means the model is specifically engineered not merely to provide answers but to actively perform actions, execute commands, and autonomously reason through complex, tool-driven problems. This design philosophy emphasizes the model’s capacity to learn from external experiences and engage in autonomous problem-solving, aligning with contemporary research on AI agents. Moonshot AI offers two distinct variants of Kimi K2: Kimi-K2-Base, which serves as a foundational model for custom fine-tuning, and Kimi-K2-Instruct, a post-trained model optimized for general-purpose chat and autonomous task execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zJYGR2SoGvj_Mat8.png" /><figcaption>Figure 7. Model Variants. <a href="https://github.com/MoonshotAI/Kimi-K2?utm_source=substack&amp;utm_medium=email">Source</a></figcaption></figure><h4>4.2 Kimi K2’s MoE Architecture: Scale and Specifics</h4><p>Kimi K2 is architected as a state-of-the-art Mixture-of-Experts Transformer model, embodying significant advancements in large language model design.</p><p><strong>4.2.1 Total vs. Activated Parameters: The Efficiency Equation</strong></p><p>A notable feature of Kimi K2 is its vast scale combined with its operational efficiency. The model comprises a staggering 1 trillion total parameters, yet only 32 billion of these parameters are activated during any single forward pass.13 This sparse activation mechanism is central to its efficiency, allowing it to deliver high performance while remaining relatively inexpensive to operate despite its immense size.</p><p><strong>4.2.2 Expert Configuration and Routing Strategy</strong></p><p>Kimi K2’s architecture is meticulously designed to leverage the MoE paradigm effectively. It features 61 layers in total, including one dense layer. The model incorporates 384 distinct expert sub-models. For each input token at every layer, a sophisticated router network dynamically selects 8 experts to process the current state, subsequently combining their outputs. Additionally, the architecture includes 1 “shared expert,” likely designed to handle common, core capacities across various inputs.[17] The attention mechanism employed is Multi-head Latent Attention (MLA), which is specifically engineered for long context support, and the model utilizes 64 attention heads. The activation function used throughout the network is SwiGLU.</p><p><strong>4.2.3 Innovations in Training: The MuonClip Optimizer</strong></p><p>Kimi K2 underwent pre-training on an unprecedented dataset of 15.5 trillion tokens, demonstrating its capacity for large-scale learning. A significant innovation enabling this monumental training scale and stability is the proprietary “MuonClip optimizer”. This optimizer was specifically developed to address and resolve instabilities, such as “logit explosions,” which are common challenges encountered during the training of very large Transformer models. The successful application of MuonClip resulted in zero training instability throughout Kimi K2’s extensive pre-training phase.[13]</p><p>The consistent mention of the MuonClip optimizer and its role in achieving “zero training instability” on a dataset of 15.5 trillion tokens points to a critical enabling technology. Training models with trillions of parameters is notoriously difficult due to instability issues. The MuonClip optimizer directly addresses these challenges by preventing training crashes and maintaining stability, which in turn allows for the successful pre-training of unprecedentedly large MoE models on vast datasets. This directly contributes to Kimi K2’s state-of-the-art performance and its ability to scale. This innovation extends beyond Kimi K2; it signifies a breakthrough in large-scale LLM training methodologies. It has the potential to pave the way for even larger and more stable models across the entire industry, potentially reducing the cost of extensive experiments by minimizing compute waste resulting from restarts.</p><h4>4.3 Performance Analysis: Benchmarks and Real-World Capabilities</h4><p>Kimi K2’s performance is particularly noteworthy across several key dimensions, especially in its targeted domain of agentic AI.</p><p><strong>4.3.1 Agentic Intelligence, Tool Use, and Reasoning Prowess</strong></p><p>Kimi K2 is specifically engineered for robust tool use, advanced reasoning, and autonomous problem-solving.13 Its design prioritizes “acting” rather than merely “answering,” making it exceptionally well-suited for applications requiring multi-step workflows and complex task execution. The model demonstrates strong performance in tool-use benchmarks, achieving 65.8% accuracy on Tau2, a benchmark for telecom tasks, which notably outperforms GPT-4.1 and Claude Sonnet 4.20 Kimi K2’s agentic capabilities are significantly enhanced by large-scale synthetic data generation that simulates real-world tool use across thousands of scenarios, including training on Model Context Protocol (MCP) tools.[23]</p><p>However, internal tests indicate some nuances in its performance. For instance, performance may decline on certain tasks if tool use is enabled, or the model might generate excessive tokens when dealing with particularly hard reasoning tasks or unclear tool definitions.[22] Furthermore, its raw reasoning capabilities are reported to be “slightly lower” than Claude 4 Opus on some multi-step math and logic benchmarks. These observations suggest a deliberate trade-off or a highly focused optimization strategy.</p><p><strong>4.3.2 Coding Performance: Leading the Open-Source Frontier</strong></p><p>One of Kimi K2’s most impressive and widely acclaimed areas of performance is in coding tasks.[16] It achieves a remarkable 65.8% single-attempt accuracy on SWE-bench Verified, a benchmark that assesses a model’s ability to resolve real GitHub issues. This score surpasses GPT-4.1’s 54.6% and is only marginally behind Claude Sonnet 4’s 72.7%.20 With parallel test-time computation, Kimi K2’s accuracy on SWE-bench Verified can reach 71.6%.20 On LiveCodeBench, an end-to-end coding benchmark, Kimi K2 scores 53.7%, outperforming GPT-4.1 (44.7%), Claude 4 Opus (47.4%), and DeepSeek-V3 (46.9%).20 The model also leads open-source models on the multilingual version of SWE-bench with 47.3% accuracy and achieves a state-of-the-art score of 80.3 on the EvalPlus benchmark.23 It is consistently ranked as the top open model on SWE-bench Verified and LiveCodeBench.19</p><p>Kimi K2’s exceptional performance in coding and agentic tasks is not incidental; it is explicitly described as “meticulously optimized for agentic tasks”.14 This indicates a deliberate strategic choice by Moonshot AI to establish a niche and excel in a specific, high-value domain, rather than aiming for a generalist “jack of all trades” approach. The focused training on synthetic agentic data and tool use directly leads to its superior performance in coding and tool-calling benchmarks, positioning Kimi K2 as a specialized leader in this domain. This trend suggests that the AI market may increasingly favor specialized, high-performance models tailored for specific enterprise use cases, such as coding, data analysis, or legal research, rather than relying on a single, all-encompassing artificial general intelligence. Companies might opt for a portfolio of specialized models to address different tasks effectively.</p><p><strong>4.3.3 Comparative Performance Against Other Frontier Models</strong></p><p>Kimi K2 demonstrates competitive or superior performance against leading proprietary models such as OpenAI’s GPT-4.1 and Anthropic’s Claude 4 Opus on several agentic-coding benchmarks.20 It has notably surpassed GPT-4.1 on both SWE-bench Verified and LiveCodeBench.20 Furthermore, Kimi K2 often performs better on benchmarks compared to other open-source counterparts like DeepSeek V3, Qwen 2.5, and LLaMA 4.18 Its mathematical reasoning capabilities are also strong, evidenced by a 97.4% accuracy on MATH-500, outperforming GPT-4.1.20 Kimi K2 has been characterized as “DeepSeek V3 with fewer heads and more experts” 18 and as being “50% larger, sparser (384 vs 256 experts), lighter per-token” than DeepSeek V3.19 While its capabilities are extensive, it does exhibit slightly lower raw reasoning performance compared to Claude 4 Opus Thinking on certain multi-step math/logic benchmarks.19 Additionally, it currently lacks vision capabilities, a feature present in some competing models.[19]</p><p>The following table provides a comparative summary of Kimi K2’s performance across key benchmarks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cue6RI9m3w--IRoS.png" /><figcaption>Figure 8: DeepSeek V3/R1 vs. Kimi K2: Comparison <a href="https://magazine.sebastianraschka.com/p/the-big-llm-architecture-comparison">Source</a></figcaption></figure><h4>4.4 Practical Considerations: Cost-Effectiveness, Speed, and Context Window</h4><p>Beyond its architectural and performance characteristics, Kimi K2 offers compelling practical advantages, particularly in terms of cost.</p><ul><li><strong>Cost-Effectiveness:</strong> Kimi K2 is notably affordable, especially given its performance. Its pay-as-you-go pricing is approximately $0.14-$0. per million input tokens and $2.49-$2.50 per million output tokens. This pricing structure makes it 10–100 times cheaper than models like Claude 4 Opus and significantly more economical than most other frontier models 22, positioning it as one of the most affordable options currently available.[18]</li><li><strong>Speed:</strong> Kimi K2’s output generation speed is reported to be around 32–42.2 tokens per second.19 While this is a decent speed, it is slower compared to some competitors, such as GPT-4.1 (approximately 50 tokens/second) and Claude 4 Sonnet (approximately 91.3 tokens/second).19 Some tests also indicated a significantly longer time for code generation.</li><li><strong>Latency:</strong> The model exhibits a relatively low latency, with a Time to First Token (TTFT) of 0.55 seconds, which is lower than the average for comparable models.</li><li><strong>Context Window:</strong> Kimi K2 supports a substantial context length of 128,000 tokens. While impressive, this is smaller than the context windows offered by some other frontier models, such as Claude (200,000 tokens) and Grok-4.</li></ul><p>The cost-effectiveness of Kimi K2 is consistently highlighted as a major advantage, especially when considering its strong performance. This creates a disruptive force within the LLM market. The combination of its MoE architecture and the MuonClip optimizer leads to highly efficient training and inference. This efficiency, in turn, allows Moonshot AI to offer competitive performance at a fraction of the cost of proprietary models. This dynamic represents a significant market disruption and increases accessibility for developers and businesses. This could accelerate the commoditization of LLM inference, shifting the competitive landscape from raw model capability, where proprietary models currently hold a lead, to cost-performance ratios and specialized applications. It empowers a broader range of users to develop AI-powered applications without encountering prohibitive costs, thereby fostering a more vibrant open-source ecosystem.</p><h4>4.5 Deployment and Accessibility: Making Kimi K2 Available</h4><p>Moonshot AI has adopted an open-weight strategy for Kimi K2, meaning its trained parameters are freely available for download and adaptation by researchers and developers.</p><ul><li><strong>API Access:</strong> Kimi K2 is accessible through Moonshot AI’s own API , providing direct programmatic access to its capabilities. Additionally, it is available via unified LLM access platforms such as OpenRouter, which aggregates access to various models.</li><li><strong>Self-Hosting:</strong> For those opting for self-hosting, obtaining the model weights requires substantial storage, potentially hundreds of gigabytes, due to its trillion-parameter scale. The weights are distributed in a specific block-fp8 format, which helps in reducing memory usage.</li><li><strong>Optimized Inference Engines:</strong> To ensure efficient serving of Kimi K2, particularly given its size and MoE architecture, Moonshot AI recommends utilizing highly optimized inference engines. These include vLLM, SGLang, KTransformers, and NVIDIA’s TensorRT-LLM. Such engines are crucial for managing GPU memory and computation effectively, supporting features like continuous batching and expert parallelism for high throughput.</li><li><strong>Large-Scale Deployment:</strong> Moonshot AI and its partners, such as LMSys, are actively focused on developing and implementing robust large-scale deployment strategies. These include Prefill-Decode (PD) Disaggregation and Large-Scale Expert Parallelism (EP) to efficiently handle MoE routing across numerous GPUs. Frameworks like Open Model Engine (OME) are designed to simplify the complexities associated with distributed deployment, abstracting away GPU topology, sharding, and runtime configuration.[14]</li></ul><p>Moonshot AI’s strategic decision to release Kimi K2 as an open-weight model, coupled with its cost-effectiveness, represents a deliberate effort to gain market share and foster widespread adoption by reducing barriers to entry. The combination of an open-weight release, competitive pricing, and strong performance is anticipated to lead to rapid community adoption and experimentation. This, in turn, is expected to increase Moonshot AI’s influence and market presence, posing a significant challenge to established proprietary models. This approach signifies a growing trend where open-source models, by leveraging architectural innovations like MoE, are becoming increasingly competitive with closed-source frontier models. This rising competition is likely to stimulate further innovation across the AI landscape and potentially lead to a more diverse and accessible ecosystem for AI development and deployment.</p><h3>5. Kimi K2 Thinking</h3><p>On Nov 6, 2025 the Kimi K2 team also released their new “Thinking” model variant. The architecture is unchanged from Kimi K2 above, except that they extended the context size from 128k to 256k.</p><p>According to the <a href="https://moonshotai.github.io/Kimi-K2/thinking.html">benchmarks shared by the Kimi team</a>, the model exceeds the performance of the leading proprietary LLMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*43xtqpPmjFBc4qu5.jpeg" /><figcaption>Figure 9: DeepSeek R1 versus Kimi K2 Thinking architecture (top) and Kimi K2 Thinking benchmarks (bottom). <a href="https://magazine.sebastianraschka.com/p/the-big-llm-architecture-comparison">Source</a></figcaption></figure><p>Kimi K2 Thinking (released November 6, 2025) outperforms GPT-5 on key benchmarks while being 4x cheaper and offering more generous free access. K2 beats GPT-5 on BrowseComp (60.2% vs 54.9%), GPQA Diamond (85.7% vs 84.5%), and excels at agentic tasks (200–300 sequential tool calls). Pricing: K2 costs $0.15/$2.50 per million tokens vs GPT-5’s $1.25/$10 (4–8x cheaper). Free access: K2 offers unlimited website use + API free tier (3M tokens/day), while GPT-5 limits free users to 10 messages/5 hours. This guide helps you choose based on performance, cost, and use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HLIOs0ArcuH47MF6.png" /><figcaption>Figure 10: <strong>K2 Thinking excels at</strong>: Web research and information synthesis, sustained agentic workflows, deep reasoning on challenging problems, multi-source data analysis, autonomous task execution. <strong>GPT-5 excels at</strong>: Code generation and debugging, creative writing and storytelling, nuanced conversation, single-turn complex instructions, established OpenAI ecosystem integration. <a href="https://fastgptplus.com/en/posts/kimi-k2-vs-gpt5-free">Source</a></figcaption></figure><h4>K2 Thinking General Capabilities</h4><p>Creative Writing: ​K2 Thinking delivers improvements in completeness and richness. It shows stronger command of style and instruction, handling diverse tones and formats with natural fluency. Its writing becomes more vivid and imaginative — poetic imagery carries deeper associations, while stories and scripts feel more human, emotional, and purposeful. The ideas it expresses often reach greater thematic depth and resonance.</p><p>Practical Writing: ​K2 Thinking demonstrates marked gains in reasoning depth, perspective breadth, and instruction adherence. It follows prompts with higher precision, addressing each requirement clearly and systematically — often expanding on every mentioned point to ensure thorough coverage. In academic, research, and long-form analytical writing, it excels at producing rigorous, logically coherent, and substantively rich content, making it particularly effective in scholarly and professional contexts.</p><p>Personal &amp; Emotional: ​When addressing personal or emotional questions, K2 Thinking responds with more empathy and balance. Its reflections are thoughtful and specific, offering nuanced perspectives and actionable next steps. It helps users navigate complex decisions with clarity and care — grounded, practical, and genuinely human in tone.</p><h4>K2 Thinking and Agentic Coding</h4><p>K2 Thinking exhibits substantial gains in coding and software development tasks. It achieves scores of 61.1% on SWE-Multilingual, 71.3% on SWE-Bench Verified, and 47.1% on Terminal-Bench, showcasing strong generalization across programming languages and agent scaffolds.</p><p>The model delivers notable improvements on HTML, React, and component-intensive front-end tasks — translating ideas into fully functional, responsive products. In agentic coding settings, it reasons while invoking tools, integrating fluidly into software agents to execute complex, multi-step development workflows with precision and adaptability.</p><h3>6. Conclusion and Future Outlook</h3><p>The Mixture-of-Experts (MoE) architecture has fundamentally transformed the landscape of large language model (LLM) scaling. By enabling models to achieve massive parameter counts with a controlled computational cost, MoE has fostered unprecedented specialization and significantly enhanced overall efficiency. This paradigm shift addresses the inherent limitations of monolithic dense models, paving the way for more capable and economically viable AI systems.</p><p>Kimi K2 stands as a testament to the state-of-the-art capabilities achievable with the MoE framework. Its architectural specifics, including 1 trillion total parameters with only 32 billion active per pass, the utilization of 384 experts with 8 selected per token, and the inclusion of a shared expert, demonstrate a sophisticated implementation of the MoE principle. The crucial role of the novel MuonClip optimizer in ensuring zero training instability during its pre-training on 15.5 trillion tokens highlights a significant engineering breakthrough that enables such extreme scale and stability. Kimi K2’s leading performance in specialized agentic and coding tasks further solidifies its position as a frontier model, particularly in areas requiring autonomous problem-solving and tool integration.</p><p>The success of Kimi K2 carries profound implications for the broader AI landscape. It underscores the increasing viability of open-source models in challenging the dominance of proprietary leaders, fostering a more competitive and innovative environment. The strategic importance of specialization, as exemplified by Kimi K2’s focus on agentic AI, suggests a future where models are tailored for specific, high-value enterprise use cases rather than being general-purpose. Furthermore, the continuous innovation in training stability and efficient deployment mechanisms for large-scale models, as seen with MuonClip and optimized inference engines, is critical for making these powerful AI capabilities practical and accessible. The exceptional cost-effectiveness of Kimi K2, driven by its efficient MoE design, holds the potential to democratize access to advanced AI, enabling a wider range of developers and organizations to build sophisticated AI-powered applications.</p><p>Looking ahead, the evolution of MoE architectures is likely to continue with advancements such as more dynamic and adaptive routing mechanisms, even more granular expert activation strategies, and further optimizations for processing extremely long context windows. The trajectory of agentic AI, with models like Kimi K2 leading the charge, points towards increasingly autonomous and capable AI systems that can seamlessly integrate with complex workflows and tools. Kimi K2, therefore, represents a pivotal step in pushing the boundaries of accessible, high-performance AI, particularly in the burgeoning realm of intelligent agents.</p><h4>Works cited</h4><ol><li>Mixture of experts — Wikipedia, accessed July 27, 2025, <a href="https://en.wikipedia.org/wiki/Mixture_of_experts">https://en.wikipedia.org/wiki/Mixture_of_experts</a></li><li>What Is Mixture of Experts (MoE)? How It Works, Use Cases &amp; More, accessed July 27, 2025, <a href="https://www.datacamp.com/blog/mixture-of-experts-moe">https://www.datacamp.com/blog/mixture-of-experts-moe</a></li><li>Mixture of Experts (MoE) Explained — Ultralytics, accessed July 27, 2025, <a href="https://www.ultralytics.com/glossary/mixture-of-experts-moe">https://www.ultralytics.com/glossary/mixture-of-experts-moe</a></li><li>Mixture of Experts: How an Ensemble of AI Models Decide As One — Deepgram, accessed July 27, 2025, <a href="https://deepgram.com/learn/mixture-of-experts-ml-model-guide">https://deepgram.com/learn/mixture-of-experts-ml-model-guide</a></li><li>What is Mixture of Experts (MoE)? How it Works and Use Cases — Zilliz Learn, accessed July 27, 2025, <a href="https://zilliz.com/learn/what-is-mixture-of-experts">https://zilliz.com/learn/what-is-mixture-of-experts</a></li><li>Mixture-of-Experts (MoE) LLMs: The Future of Efficient AI Models — SaM Solutions, accessed July 27, 2025, <a href="https://sam-solutions.com/blog/moe-llm-architecture/">https://sam-solutions.com/blog/moe-llm-architecture/</a></li><li>Mixture of Experts (MoE) Architecture: A Deep Dive and Comparison of Top Open-Source Offerings, accessed July 27, 2025, <a href="https://www.architectureandgovernance.com/applications-technology/mixture-of-experts-moe-architecture-a-deep-dive-and-comparison-of-top-open-source-offerings/">https://www.architectureandgovernance.com/applications-technology/mixture-of-experts-moe-architecture-a-deep-dive-and-comparison-of-top-open-source-offerings/</a></li><li>MoE (Mixture of Experts) for Dummies: A Beginner’s Guide — Michiel Horstman, accessed July 27, 2025, <a href="https://michielh.medium.com/moe-mixture-of-experts-for-dummies-d1a7e14c1846">https://michielh.medium.com/moe-mixture-of-experts-for-dummies-d1a7e14c1846</a></li><li>Mixture of Experts Explained — Hugging Face, accessed July 27, 2025, <a href="https://huggingface.co/blog/moe">https://huggingface.co/blog/moe</a></li><li>Why New LLMs use an MoE Architecture | Exxact Blog, accessed July 27, 2025, <a href="https://www.exxactcorp.com/blog/deep-learning/why-new-llms-use-moe-mixture-of-experts-architecture">https://www.exxactcorp.com/blog/deep-learning/why-new-llms-use-moe-mixture-of-experts-architecture</a></li><li>Explaining the Mixture-of-Experts (MoE) Architecture in Simple Terms | by Gregory Zem, accessed July 27, 2025, <a href="https://medium.com/@mne/explaining-the-mixture-of-experts-moe-architecture-in-simple-terms-85de9d19ea73">https://medium.com/@mne/explaining-the-mixture-of-experts-moe-architecture-in-simple-terms-85de9d19ea73</a></li><li>On the Benefits of Learning to Route in Mixture-of-Experts Models — OpenReview, accessed July 27, 2025, <a href="https://openreview.net/pdf?id=QV79qiKAjD">https://openreview.net/pdf?id=QV79qiKAjD</a></li><li>moonshotai/Kimi-K2-Instruct (and Kimi-K2-Base) : r/LocalLLaMA — Reddit, accessed July 27, 2025, <a href="https://www.reddit.com/r/LocalLLaMA/comments/1lx8xdm/moonshotaikimik2instruct_and_kimik2base/">https://www.reddit.com/r/LocalLLaMA/comments/1lx8xdm/moonshotaikimik2instruct_and_kimik2base/</a></li><li>Deploying Kimi K2 with PD Disaggregation and Large-Scale Expert Parallelism on 128 H200 GPUs | LMSYS Org, accessed July 27, 2025, <a href="https://lmsys.org/blog/2025-07-20-k2-large-scale-ep/?linkId=100000374601795">https://lmsys.org/blog/2025-07-20-k2-large-scale-ep/?linkId=100000374601795</a></li><li>Tutorial: Kimi K2 for code generation with observability | genai-research — Wandb, accessed July 27, 2025, <a href="https://wandb.ai/onlineinference/genai-research/reports/Tutorial-Kimi-K2-for-code-generation-with-observability--VmlldzoxMzU4NjM5MA">https://wandb.ai/onlineinference/genai-research/reports/Tutorial-Kimi-K2-for-code-generation-with-observability--VmlldzoxMzU4NjM5MA</a></li><li>Kimi K2: What’s all the fuss and what’s it like to use? — Thoughtworks, accessed July 27, 2025, <a href="https://www.thoughtworks.com/en-us/insights/blog/generative-ai/kimi-k2-whats-fuss-whats-like-use">https://www.thoughtworks.com/en-us/insights/blog/generative-ai/kimi-k2-whats-fuss-whats-like-use</a></li><li>Kimi K2 is the large language model series developed by Moonshot AI team — GitHub, accessed July 27, 2025, <a href="https://github.com/MoonshotAI/Kimi-K2">https://github.com/MoonshotAI/Kimi-K2</a></li><li>Kimi K2: A Guide With Six Practical Examples — DataCamp, accessed July 27, 2025, <a href="https://www.datacamp.com/tutorial/kimi-k2">https://www.datacamp.com/tutorial/kimi-k2</a></li><li>Kimi K2 — Open-Source Agentic Model | by Shravan Kumar | Jul, 2025 | Medium, accessed July 27, 2025, <a href="https://medium.com/@shravankoninti/kimi-k2-open-source-agentic-model-dd27e7537afb">https://medium.com/@shravankoninti/kimi-k2-open-source-agentic-model-dd27e7537afb</a></li><li>Kimi K2 by Moonshot AI: A Trillion-Parameter Open-Source Powerhouse Redefining Agentic AI | by Sai Dheeraj Gummadi | Jul, 2025 | Medium, accessed July 27, 2025, <a href="https://medium.com/@gsaidheeraj/kimi-k2-by-moonshot-ai-a-trillion-parameter-open-source-powerhouse-redefining-agentic-ai-763cc2db138f">https://medium.com/@gsaidheeraj/kimi-k2-by-moonshot-ai-a-trillion-parameter-open-source-powerhouse-redefining-agentic-ai-763cc2db138f</a></li><li>Announcing Kimi K2 on GMI Cloud, accessed July 27, 2025, <a href="https://www.gmicloud.ai/blog/announcing-kimi-k2-on-gmi-cloud">https://www.gmicloud.ai/blog/announcing-kimi-k2-on-gmi-cloud</a></li><li>China’s Moonshot AI Releases Trillion Parameter Model Kimi K2 — HPCwire, accessed July 27, 2025, <a href="https://www.hpcwire.com/2025/07/16/chinas-moonshot-ai-releases-trillion-parameter-model-kimi-k2/">https://www.hpcwire.com/2025/07/16/chinas-moonshot-ai-releases-trillion-parameter-model-kimi-k2/</a></li><li>Moonshot’s Kimi K2 for Coding: Our First Impressions in Cline, accessed July 27, 2025, <a href="https://cline.bot/blog/moonshots-kimi-k2-for-coding-our-first-impressions-in-cline">https://cline.bot/blog/moonshots-kimi-k2-for-coding-our-first-impressions-in-cline</a></li><li>Kimi K2 vs. Claude 4 Sonnet: what you should pick for agentic coding — Composio, accessed July 27, 2025, <a href="https://composio.dev/blog/kimi-k2-vs-claude-4-sonnet-what-you-should-pick-for-agentic-coding">https://composio.dev/blog/kimi-k2-vs-claude-4-sonnet-what-you-should-pick-for-agentic-coding</a></li></ol><p>25. Kimi K2 — Intelligence, Performance &amp; Price Analysis, accessed July 27, 2025, <a href="https://artificialanalysis.ai/models/kimi-k2">https://artificialanalysis.ai/models/kimi-k2</a></p><p>26. <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Kimi+Team">Kimi Team</a> , 2025 , “Kimi K2: Open Agentic Intelligence”, <a href="https://doi.org/10.48550/arXiv.2507.20534"><br>https://doi.org/10.48550/arXiv.2507.20534</a></p><p>27. <a href="https://substack.com/@rasbt">Sebastian Raschka, PhD</a> , “The Big LLM Architecture Comparison , From DeepSeek V3 to Mistral 3 Large: A Look At Modern LLM Architecture Design”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eef8c1ec31c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LLM Reasoning Powers the Agentic AI Revolution]]></title>
            <link>https://medium.com/@anicomanesh/how-llm-reasoning-powers-the-agentic-ai-revolution-cbefd10ebf3f?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbefd10ebf3f</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[reasoning]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agentic-architecture]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 14:10:54 GMT</pubDate>
            <atom:updated>2026-01-30T21:08:38.362Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Your LLM Can’t Plan (And How Agentic Architectures Fix It)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ogng7Vhi8eJ2xW2y.jpg" /><figcaption>Image Source <a href="https://images.newscientist.com/wp-content/uploads/2024/04/09121015/SEI_198633450.jpg?width=700">How AI mathematicians might finally deliver human-level reasoning:</a></figcaption></figure><h3>I. Introduction: The Reasoning-Action Gap</h3><p>In September 2024, OpenAI released o1, a model capable of scoring 83% on the International Mathematics Olympiad qualifying exam — a task that demands sophisticated deductive reasoning, multi-step algebraic manipulation, and abstract pattern recognition. Yet this same system, when asked to perform the ostensibly simpler task of booking a multi-city flight itinerary, will likely hallucinate non-existent flight numbers, ignore real-time price changes, and fail to verify whether the selected seats actually exist. This is not a quirk of implementation, but a fundamental paradox at the heart of modern artificial intelligence: we have built systems that can think profoundly but cannot act reliably.</p><p>This paradox exposes a critical distinction that the current AI discourse often obscures. <strong>Reasoning </strong>— the cognitive capacity to draw inferences, chain logical steps, and solve structured problems — <strong>is not synonymous with planning</strong>, which requires reasoning plus commitment, environmental grounding, and error recovery. A mathematician solving a proof operates in a closed symbolic world where variables behave predictably; a traveler booking flights operates in an open physical world where seat availability changes by the second, payment gateways timeout, and weather disruptions cascade through itineraries. The former requires only <strong>monologue</strong>: an extended internal chain of thought. The latter demands <strong>dialogue</strong>: a continuous loop of reasoning, acting, observing, and re-reasoning.</p><p>The emergence of “agentic AI” represents the industry’s attempt to bridge this gap. But framing agentic systems merely as “LLMs with tools” fundamentally misunderstands the architectural leap required. Tools — APIs, browsers, code interpreters — are necessary but insufficient. The crucial innovation is not the availability of screwdrivers and databases, but the transformation of reasoning from a stateless monologue into a stateful, feedback-driven dialogue. When GPT-4 generates a <strong>chain-of-thought (CoT)</strong> to solve a math problem, it produces a linear narrative: “First, I notice the pattern is quadratic, so I calculate the discriminant…” This is Kahneman’s <strong><em>System 1</em></strong> <strong><em>thinking</em></strong> extended in time — fast, intuitive, pattern-based generation that happens to look like logic because it mimics human reasoning transcripts. It is “<strong>thinking fast</strong>” stretched across many tokens, but it remains fast thinking: associative, confident, and brittle.</p><p>True planning requires <strong><em>System 2</em> <em>thinking</em></strong> — slow, deliberate, methodical — but crucially, it requires <strong><em>System 2 embodied</em></strong> in an environment that talks back. When an agent books a flight, it cannot simply reason its way to a solution in a single forward pass. It must propose an action (“search flights from NYC to London on March 15”), observe the result (“no direct flights available”), and enter a new reasoning phase conditioned on this observation (“therefore, I should check connections through Frankfurt”). This is not an extended monologue; it is a conversation between the model’s reasoning engine and the world’s messy state.</p><p>The architectural shift from monologue to dialogue introduces three critical requirements absent in pure LLM reasoning. <strong>First</strong>, grounding: the model must map its abstract reasoning steps to concrete, verifiable changes in environment state. <strong>Second</strong>, recoverability: when an action fails (the Frankfurt flight is full), the system must backtrack not just in token space but in commitment space, abandoning partial plans without catastrophic forgetting. Third, temporal awareness: reasoning must incorporate the reality that time passes between steps, and the world changes during that passage.</p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//arxiv.org/pdf/2502.17419&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/0857b9bdf28b6fe03c5cb3a922b100c0/href">https://medium.com/media/0857b9bdf28b6fe03c5cb3a922b100c0/href</a></iframe><p>Recent advances in “inference-time scaling” — exemplified by <strong>o1, DeepSeek R1, and Gemini 2.0 Flash Thinking</strong> — complicate but do not resolve this gap. These models allocate additional computation at inference to generate extended “<a href="https://arxiv.org/pdf/2112.00114"><strong>scratchpads</strong></a>” of internal deliberation, effectively simulating System 2 thinking within the forward pass. They verify their own intermediate steps, backtrack within the context window, and explore multiple solution paths before committing to an answer. This represents a profound advance in reasoning capability, yet it remains fundamentally stateless with respect to the external world. The model can spend 100 seconds “thinking” about flight routes, but if seat availability changes during those 100 seconds, the thinking is already obsolete. Without the dialogue loop — without the capacity to pause reasoning, execute an action, and incorporate environmental feedback — inference-time scaling is merely spending more compute on a hallucination.</p><p>This article explores how the field is engineering the <strong>transition from reasoning to planning</strong>, from thinking to thinking-while-acting. We begin by examining the cognitive foundations of current LLM reasoning — the System 1 pattern-matching that powers autoregressive models and the emerging System 2 capabilities of test-time compute scaling. We then analyze why these capabilities, impressive as they are, fail to constitute <strong>agency</strong>. From there, we dissect the agentic architecture: the <strong>ReAct loops</strong>, <strong>tree-search planners</strong>, and <strong>hierarchical task networks</strong> that transform raw reasoning into reliable action. We propose a synthesis identifying three distinct modes of agentic reasoning —<strong> reflective, instrumental</strong>, and <strong>collective</strong> — each requiring different combinations of internal inference and external feedback. Finally, we confront the current limitations: the exponential decay of accuracy in long-horizon plans, the verification gap between generated plans and executable actions, and the fundamental question of whether LLMs can truly plan or merely simulate planning through increasingly sophisticated pattern matching.</p><blockquote>The stakes extend beyond technical architecture. As AI systems move from answering questions to executing intentions across hours, days, or weeks — from booking flights to managing supply chains to conducting scientific research — the distinction between reasoning and planning becomes the distinction between assistance and autonomy. Understanding this gap is prerequisite to building systems we can trust not merely to think correctly, but to act wisely.</blockquote><h3>II. The Foundation: How LLMs Reason</h3><h4>A. The Reasoning Spectrum: Capability, Emergence, and Scale</h4><p>A common misconception holds that “reasoning” is a binary property — either a model can reason or it cannot. In reality, reasoning capability in LLMs is emergent, continuous, and architecturally constrained. Not all models possess it; those that do, possess it in degrees; and recent SOTA models have begun specializing into “reasoning” vs. “non-reasoning” variants optimized for different latency-accuracy tradeoffs.</p><h4>The Emergence Threshold</h4><p>Reasoning is an <strong>emergent ability</strong> — it appears unpredictably at scale rather than improving gradually with parameter count . Research from Wei et al. (2022) and subsequent work demonstrates that below approximately 50–70B parameters, models struggle with tasks requiring multi-step composition, despite excelling at pattern recognition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgPiUZYtB86D8_Gm98JKwQ.png" /><figcaption>Table 1. Taxonomy of SOTA LLM Reasoning Capabilities (2024–2026).<br>The current landscape exhibits a tripartite fragmentation: (1) <em>Fast/Generalist</em> models optimize for low-latency conversational use via System 1 pattern matching; (2) <em>Inference-Time Reasoners</em> (o3, R1) trade speed for accuracy via test-time compute scaling, effectively simulating System 2 deliberation; (3) <em>Dense Generalists</em> (Llama 3, Qwen 2.5) serve as open-weight baselines with implicit reasoning only; (4) <em>Distilled Reasoners</em> attempt to compress expensive reasoning into efficient student models but suffer from fragile verification; (5) <em>Long-Context Specialists</em> (Kimi K2.5, Gemini 1.5 Pro) sacrifice speed for massive retrieval windows, enabling instrumentally-grounded reasoning via in-context retrieval rather than scratchpad deliberation; and (6) <em>MoE Efficient Reasoners</em> (DeepSeek V3, Mixtral) decouple parameter count from inference cost via sparse routing. Agentic architectures must orchestrate across these classes — deploying Fast models for tool execution, Inference-Time models for verification, and Long-Context models for retrieval — compensating for the fact that no single model optimizes the full speed-accuracy-context frontier.</figcaption></figure><p>This heterogeneous landscape resists simple binary classification. Table 1 presents a taxonomy of current SOTA models across six functional classes, ranging from <em>Fast Generalists</em> optimized for conversational latency (GPT-4o, Claude 3.5) to <strong><em>Inference-Time Reasoners</em> </strong>that sacrifice throughput for deliberative accuracy (o3, DeepSeek R1) . Crucially, the table distinguishes between<strong> <em>Dense Generalists</em> </strong>— open-weight models relying on pre-trained patterns (Llama 3.1 405B, Qwen 2.5) — and<strong> <em>Distilled Reasoners</em>,</strong> which attempt to compress expensive test-time scaling into efficient student models (R1-Distill-Qwen 32B) but exhibit verification fragility .</p><p>Two architectural novelties disrupt the traditional speed-accuracy trade-off. First, <strong><em>Long-Context Specialists</em> </strong>(Kimi K2.5, Gemini 1.5 Pro) achieve instrumentally-grounded reasoning via retrieval over 2M+ token contexts, though Liu et al. demonstrate that accuracy degrades at extreme lengths due to attention bottlenecks — the “lost in the middle” phenomenon that limits their use for fine-grained reasoning chains . Second, <strong><em>MoE Efficient Reasoners </em></strong>(DeepSeek V3, Mixtral 8x22B) decouple parameter scale from inference cost via sparse routing, enabling 671B-parameter systems to inference at 37B-parameter speed, albeit with non-deterministic reasoning paths due to expert load balancing .</p><p>Agentic architectures must orchestrate across this spectrum. No single model class occupies the pareto frontier — speed, accuracy, and context length remain mutually constrained. The three modes of agentic reasoning (Reflective, Instrumental, Collective) essentially function as strategies to combine these classes: <em>Reflective</em> mode invokes Inference-Time Reasoners for verification; <em>Instrumental</em> mode leverages Long-Context Specialists for retrieval grounding; <em>Collective</em> mode distributes tasks across Fast Generalists (execution) and MoE Reasoners (specialized routing).</p><h4>Critical Distinction: System 1 vs. System 2 in Current SOTA</h4><p>The taxonomy in Table 1 maps onto<a href="https://thedecisionlab.com/reference-guide/philosophy/system-1-and-system-2-thinking"> Kahneman’s cognitive dual-process theory </a>, but with architectural specificity. Fast Generalists (GPT-4o, Claude 3.5 standard mode) implement <em>System 1</em> reasoning — fast associative pattern matching that generates confident-sounding but potentially hallucinated logical steps. These models excel at intuitive leaps but lack explicit verification; their “reasoning” is emergent from statistical regularities rather than algorithmic manipulation .</p><blockquote>We are all familiar with the experience of trying not to stare at the oddly dressed couple at the neighboring table in a restaurant. We also know what it is like to force our attention on a boring book, when we constantly find ourselves returning to the point at which the reading lost its meaning… And every human being has had the experience of not telling someone to go to hell. One of the tasks of System 2 is to overcome the impulses of System 1. In other words, System 2 is in charge of self-control.</blockquote><blockquote>Daniel Kahneman</blockquote><p>Conversely, Inference-Time Reasoners (o3, DeepSeek R1) implement <em>System 2</em> — deliberative, sequential, self-verifying cognition. These models generate 10,000–100,000 token “scratchpads” of internal deliberation before committing to answers, achieving 87% accuracy on AIME-2024 versus GPT-4o’s 13%, but requiring 30–120 seconds per complex query and costing $20–100 per evaluation . The trade-off is explicit: latency for reliability.</p><h4>Architectural Scaling Mechanisms</h4><p>Where Table 1 categorizes by capability, the underlying architectures reveal <em>why</em> these capability classes emerge:</p><p>Dense Transformers (GPT-4, Llama 3.1 405B) scale reasoning log-linearly with parameters but encounter hard limits on complex logic due to attention bottlenecks and context window constraints during forward passes .</p><p>Mixture of Experts (DeepSeek V3, Mixtral 8x22B) relax this constraint by routing reasoning tasks to specialized sub-networks, achieving GPT-4-level reasoning at 20% inference cost through sparse activation (37B active parameters of 671B total) . However, expert routing introduces non-determinism — reasoning quality varies based on load balancing stochasticity.</p><p>Test-Time Optimized models (o3, R1) represent a paradigm shift: they decouple reasoning quality from parameter count entirely by scaling <em>inference compute</em> rather than model size. DeepSeek R1 achieves superhuman mathematical reasoning using only the DeepSeek-V3-Base architecture (already capable via MoE) by adding 10–100× inference-time computation for step-wise verification .</p><h4>The “Reverse Scaling” Phenomenon</h4><p>This heterogeneity creates a deployment dilemma: not all tasks benefit from System 2 reasoning. Recent evaluations demonstrate <em>reverse scaling</em> — o3 performs worse than GPT-4o on simple pattern-matching tasks because it “over-thinks,” generating elaborate scratchpads for questions requiring immediate intuitive response . This explains the market bifurcation visible in Table 1: GPT-4o for chatbot interfaces (&lt;2s latency), o3 for mathematical proof generation (120s acceptable if accuracy is paramount).</p><p><strong>Implication for Agentic AI</strong>: No single model class occupies the Pareto frontier of speed, accuracy, and cost. The three modes of agentic reasoning (Section IV) function as <em>routing strategies</em> across this landscape — deploying Fast Generalists for tool execution (Instrumental), Inference-Time Reasoners for verification (Reflective), and Long-Context Specialists for retrieval grounding (also Instrumental), coordinated via Collective-mode orchestration.</p><h4>Why This Matters for Agentic AI</h4><p>The heterogeneity of reasoning capabilities explains why agentic architectures cannot simply “plug in” any LLM. A travel booking agent powered by GPT-4o will confidently hallucinate flight connections; one powered by o1 will take 2 minutes to verify each leg. The three modes of agentic reasoning (Reflective, Instrumental, Collective) are essentially compensatory strategies for the fact that<strong> no single model configuration optimizes both speed and reasoning depth.</strong></p><p>Agentic architectures mix models:</p><ul><li>Fast LLMs for execution (Instrumental mode),</li><li>Slow reasoning models for verification (Reflective mode),</li><li>Ensembles for robustness (Collective mode).</li></ul><p>Understanding that reasoning is not universal — but graduated and expensive — frames the architectural necessity of the systems described in Section III.</p><h4>B. The Pattern-Matching Baseline: Autoregression as System 1 Thinking</h4><p>At their core, Large Language Models are completion engines trained on the objective of next-token prediction. Given a sequence of tokens <em>x</em>1​,<em>x</em>2​,…,<em>xt</em>​ , the model learns the conditional probability distribution <em>P</em>(<em>xt</em>+1​∣<em>x</em>1​,…,<em>xt</em>​) and samples from it iteratively until a stopping condition is met. This architecture, while seemingly simple, implements a form of associative reasoning — what Daniel Kahneman termed System 1 thinking: fast, intuitive, pattern-based, and largely unconscious</p><p>System 1 reasoning excels at tasks where solutions are <strong>pattern-recognition</strong> problems disguised as logic. When GPT-4 solves a simple arithmetic problem or completes a familiar coding task, it is not executing a formal algorithm step-by-step in the manner of a calculator or compiler. Rather, it is recognizing statistical regularities in its training data: “problems of this structure typically resolve to answers of that structure.” The chain of tokens it generates — “First, we distribute the 3 across the parentheses, giving us 3x + 12…” — is not a transparent window into step-by-step logical deduction but a <strong>simulacrum</strong> of reasoning, generated because the model has seen thousands of similar worked examples and learned the surface form of valid derivations.</p><p>This pattern-matching baseline explains both the impressive fluidity and the brittle failures of early LLMs. In a landmark 2023 study of planning capabilities, researchers found that standard LLMs (GPT-3.5, GPT-4) could generate plausible-sounding plans for concrete tasks — calculating flight costs, scheduling meetings — but failed catastrophically when those plans required tracking implicit preconditions or handling environmental volatility . The models exhibited what we might call reasoning hallucinations: confident-sounding logical steps that contained fundamental flaws, such as proposing to “click the submit button” without verifying that the form was complete, or scheduling two meetings at overlapping times without checking for conflicts .</p><p>The limitation is architectural. Autoregressive generation is stateless with respect to any world beyond the token stream. Each prediction step conditions only on the context window — immediate preceding tokens — and carries no mechanism to verify whether the generated plan corresponds to executable reality. The model operates in a “monologue” mode: it speaks, and then speaks more, but never listens. This is System 1 thinking extended temporally — fast, flowing, but incapable of the hesitation and verification that characterizes careful deliberation.</p><h4>C. The Inference-Time Revolution: Scaling Compute to Simulate System 2</h4><p>The past year has witnessed a paradigm shift with the introduction of “reasoning models” — OpenAI’s o1, DeepSeek’s R1, and the Gemini 2.0 Flash Thinking variants. These models depart from the standard next-token prediction paradigm by implementing test-time compute scaling: they allocate additional computation during inference, generating extended chains of internal deliberation (often called “scratchpads” or “thinking tokens”) before producing the final response .</p><p>Rather than generating the immediate answer <em>y</em> from input <em>x</em> , these models first generate a lengthy reasoning trace <em>r</em>=<em>r</em>1​,<em>r</em>2​,…,<em>rn</em>​ , sometimes consuming 10,000 to 100,000 tokens of internal monologue for complex problems, and then condition the final output on this trace: <em>P</em>(<em>y</em>∣<em>x</em>,<em>r</em>) . This architecture explicitly implements Kahneman’s <em>System 2</em> thinking: slow, deliberate, step-by-step analysis . The models verify intermediate steps, explore multiple solution paths (“Wait, let’s check if this assumption holds…”), and backtrack when they detect errors (“Actually, that approach leads to a contradiction; let me try another angle”).</p><p>The empirical results are striking. On the American Invitational Mathematics Examination (AIME), a benchmark for advanced mathematical reasoning, OpenAI’s o1 achieved 83% accuracy, compared to GPT-4o’s 13%. On the GPQA diamond benchmark — PhD-level problems in biology, chemistry, and physics — the system scored 78%, surpassing expert human performance . DeepSeek R1, trained with pure reinforcement learning without supervised fine-tuning, demonstrated emergent reasoning behaviors including self-verification and long-horizon planning, suggesting that given sufficient compute and the right optimization objectives, complex reasoning patterns can arise rather than being explicitly programmed .</p><p>Three technical innovations enable this capability. First, chain-of-thought (CoT) prompting — elaborated by Wei et al. (2022) and refined through numerous follow-up works — demonstrated that explicitly prompting models to “think step by step” elicits multi-step reasoning that is more accurate than direct answering . Second, self-consistency sampling generates multiple reasoning paths and aggregates them (through majority voting or learned verifiers) to improve reliability . Third, and most critically, reinforcement learning on reasoning traces (RLVR) optimizes not just for correct answers but for the quality of the thinking process itself, rewarding models for generating verifiable intermediate steps .</p><p>However, a crucial distinction remains: this System 2 simulation operates entirely within token space. The “world” the model reasons about is the context window; the actions it evaluates are hypothetical continuations of text. When o1 reasons about a coding problem, it can simulate the execution of code in its “head” only to the extent that such execution is captured in patterns from training data. It cannot actually run the code, observe the traceback, and adjust accordingly — not without exiting the monologue and entering the dialogue loop of agentic execution.</p><p>The distinction between “internal System 2” (test-time compute within the forward pass) and “external System 2” (reasoning interleaved with environmental action) is subtle but foundational. Test-time scaling allows the model to be <em>deliberate</em>; agents allow the model to be <em>grounded</em>. The former improves reasoning quality; the latter transforms reasoning into planning.</p><h4>D. Why Pure LLM Reasoning Fails at Agency: The Three Gaps</h4><p>Despite the advances in inference-time reasoning, pure LLM cognition — whether fast (System 1) or slow (System 2) — fails to constitute agency due to three structural gaps between token generation and actionable planning.</p><p><strong>1. The Grounding Gap: Symbols Without Reference</strong></p><p>Agentic action requires mapping abstract reasoning steps to concrete state changes in the environment. When a model reasons “I will check flight prices,” the token string “check flight prices” must connect to an actual API call that returns real data. Pure LLMs operate in a realm of <em>ungrounded symbols</em>. They can generate the sentence “The button turns green when clicked,” but they cannot verify whether a specific button on a specific webpage is currently green, red, or absent . This is the difference between <em>intention</em> (internal representation of desired state) and <em>perception</em> (verification of actual state).</p><p>Recent work on “world models” attempts to address this by training LLMs to simulate environment state transitions internally — treating the model itself as a differentiable simulator . While promising, current world models remain crude approximations, accurate for stylized game environments but failing for the combinatorial complexity of real-world logistics. The grounding gap persists: internal simulation is not external verification.</p><p><strong>2. The Commitment Gap: Reasoning Without Reversibility</strong></p><p>Reasoning is cheap; acting is expensive. When an LLM generates a flawed proof in a math problem, it can backtrack instantly by deleting tokens and regenerating — a zero-cost operation. When an agentic system books a non-refundable flight based on a reasoning error, the cost is real and irreversible. Pure LLM reasoning lacks commitment semantics: it cannot distinguish between “thinking about doing X” and “having done X.” This leads to what planning researchers call the “open-loop” problem — generating a sequence of actions without feedback mechanisms to detect when the world state has diverged from the planned trajectory .</p><p>The commitment gap manifests practically in “reasoning decay”: studies show that accuracy compounds exponentially in multi-step reasoning chains, dropping precipitously as the planning horizon extends . If each reasoning step is 90% reliable, a 5-step plan has only 59% success probability. Without the ability to pause, verify, and replan — without the dialogue loop — long-horizon agency becomes statistically impossible regardless of reasoning sophistication.</p><p><strong>3. The Temporal Gap: Frozen Time vs. Flowing Time</strong></p><p>LLM reasoning occurs in a timeless instant — the forward pass, whether generating 10 tokens or 10,000, is a single computation graph with no temporal extension. Agency unfolds in time: the flight prices queried 30 seconds ago may have changed; the calendar slot that was open when planning began may be taken by the time the agent attempts to book it. Pure reasoning models are atemporal; they generate plans as if photographing a static world, then attempting to execute against a moving target.</p><p>This temporal blindness explains why even sophisticated reasoning models struggle with “dynamic planning” tasks. A 2024 evaluation of LLM planners found that while models could generate syntactically valid plans for Blocksworld and Logistics benchmarks, their success rate dropped to near zero when environmental stochasticity was introduced — when actions had probabilistic outcomes or when exogenous events could invalidate preconditions .</p><p>The inference-time revolution addresses <em>depth</em> of reasoning — how many cognitive steps the model can simulate internally — but not <em>breadth</em> of interaction — how many environmental feedback loops it can accommodate. The next section explores the architectural innovations that bridge these gaps: the ReAct pattern, tree-search planning, and hierarchical reasoning systems that transform the monologue into a dialogue.</p><h3>III. The Agentic Architecture: Reasoning as a Control Loop</h3><h4>A. The ReAct Pattern: From Monologue to Dialogue</h4><p>The fundamental breakthrough in agentic AI was the recognition that reliable planning requires closing the loop between reasoning and environmental feedback. The <strong>ReAct</strong> (Reasoning + Acting) paradigm, introduced by Yao et al. (2023), formalizes this as an interleaved sequence of Thought, Action, and Observation . Unlike the linear Chain-of-Thought (CoT) generation — where a model reasons once and outputs a final answer — ReAct implements a <em>dialogue</em>: the model thinks, acts upon the world, perceives the result, and thinks again.</p><p>In this architecture, the LLM serves as both the controller and the cognitive engine. At each step <em>t</em> , the model generates a reasoning trace <em>rt</em>​ (e.g., “I need to check the current weather in London before suggesting an outdoor activity”) followed by an action <em>at</em>​ (e.g., calling a weather API or executing Python code). The environment returns an observation <em>ot</em>​ (e.g., “Rain expected, 15°C”), which is appended to the context, and the cycle repeats. This creates a stateful, partially observable Markov Decision Process (POMDP) where the LLM policy <em>π</em>(<em>rt</em>​,<em>at</em>​∣<em>h</em>&lt;<em>t</em>​) conditions on the full interaction history <em>h</em> rather than just the initial prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWyNvX9Un-GYetuI7mfMbQ.png" /><figcaption>Figure 1. The ReAct Control Loop Architecture as a Partially Observable Markov Decision Process (POMDP). The diagram illustrates the iterative reasoning-acting-observing cycle that transforms static LLM inference into stateful agentic behavior. (A) The Thought Phase (blue) implements the LLM policy <em>πθ</em>​(<em>at</em>​∣<em>ht</em>​) , generating actions conditioned on interaction history <em>ht</em>​ . Internal subprocesses include context analysis, strategy selection (Tree-of-Thoughts vs. greedy decoding), action generation with schema validation, self-correction for consistency checking, and termination condition evaluation. (B) The Action Phase (rust/orange) executes selected tools within environment E , with explicit pre-check validation to prevent hallucinated API calls, parameter extraction from reasoning traces, and timeout handling (typically <em>t</em>max​=30 s). © The Observation Phase (sage green) processes environmental feedback through result parsing (JSON/HTML/pixels), schema validation to detect malformed responses, error classification (retryable vs. fatal), state extraction (Δ<em>s</em>=<em>st</em>+1​−<em>st</em>​ ), and Bayesian belief updating <em>P</em>(<em>s</em>∣<em>o</em>) to maintain a probabilistic world model. (D) The Episodic Memory (dashed grey) persists the trajectory history <em>ht</em>​={(<em>a</em>1​,<em>o</em>1​),…,(<em>at</em>−1​,<em>ot</em>−1​)} across iterations, enabling context-dependent reasoning. (E) Error Recovery Paths (dashed red arrows) close feedback loops from execution failures and validation errors back to the Thought phase, implementing retry logic and replanning. (F) Mathematical Formulation: The system is formally a POMDP with belief states <em>b</em>(<em>s</em>) , actions <em>a</em>∈A , observations <em>o</em>∈O , and transition dynamics <em>P</em>(<em>s</em>′∣<em>s</em>,<em>a</em>) . Iteration terminates when either the goal is achieved, <em>t</em>=<em>T</em>max​ (typically 10 steps), or a fatal error occurs. This architecture bridges the “Reasoning-Action Gap” by grounding abstract LLM cognition in environmental feedback loops.</figcaption></figure><p>Recent implementations have dramatically expanded the action space beyond simple API calls. OpenAI’s <em>Operator</em> (2025) and Anthropic’s <em>Computer Use</em> (2024) enable LLMs to control entire computer interfaces — viewing screenshots, moving cursors, clicking buttons, and typing text . This represents a shift from <em>symbolic</em> tool use (structured JSON function calls) to <em>embodied</em> tool use (pixel-level interaction with graphical interfaces). The reasoning loop now handles visual grounding: the model must reason about UI element locations, interpret visual feedback, and correct misalignments between its internal plan and the actual screen state.</p><p>Here is the Modern ReAct implementation with tool use (OpenAI/Anthropic computer use style):</p><pre># SOTA ReAct Loop (OpenAI style with tool use)<br>class Agent:<br>    def __init__(self, model=&quot;gpt-4o&quot;):<br>        self.client = OpenAI()<br>        self.tools = [<br>            {&quot;type&quot;: &quot;function&quot;, &quot;function&quot;: {&quot;name&quot;: &quot;search_flights&quot;, ...}},<br>            {&quot;type&quot;: &quot;computer_preview&quot;, ...}  # Computer use capability<br>        ]<br>        self.memory = []<br>    <br>    async def run(self, goal: str, max_steps=10):<br>        for step in range(max_steps):<br>            # Reasoning step<br>            response = self.client.chat.completions.create(<br>                model=self.model,<br>                messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: goal}] + self.memory,<br>                tools=self.tools,<br>                tool_choice=&quot;auto&quot;<br>            )<br>            <br>            message = response.choices[0].message<br>            <br>            # Action execution<br>            if message.tool_calls:<br>                result = await self.execute_tool(message.tool_calls[0])<br>                self.memory.append({&quot;role&quot;: &quot;tool&quot;, &quot;content&quot;: result})<br>            else:<br>                return message.content  # Final answer</pre><p>The critical advantage of this loop is error recovery. When the action “click Submit” fails because the button is grayed out, the observation (unchanged screen state or error message) triggers a new reasoning phase (“The form is incomplete; I need to fill the email field first”). Pure LLM reasoning lacks this corrective mechanism; ReAct implements <strong>reversibility through iteration </strong>— the commitment gap is bridged by making actions small and observations frequent, allowing the planner to course-correct before catastrophic deviation.</p><h4>B. Planning as Search: Beyond Linear Chains</h4><p>While ReAct implements local reasoning — deciding the next step based on current state — complex tasks require<strong> global planning</strong>: exploring multiple future trajectories and selecting optimal paths. Recent architectures have adapted classical search algorithms to leverage LLMs as heuristic evaluators within combinatorial search spaces.</p><p><strong>Tree of Thoughts (ToT)</strong>, proposed by Yao et al. (2023) and extended by Hao et al. (2023), generalizes CoT from chains to trees . At each node, the LLM generates multiple candidate thoughts (diverse reasoning steps), and a value function — either the LLM itself or a trained verifier — evaluates which branch merits expansion. This enables deliberate problem-solving: the model can backtrack from dead ends (“This algebraic manipulation leads to contradiction; try factoring instead”) and explore counterfactuals (“What if I had taken the logarithm first?”). The search can be implemented via Breadth-First Search (BFS), Depth-First Search (DFS), or, most effectively, Monte Carlo Tree Search (MCTS). Here is MCTS (Monte Carlo Tree Search) implementation for LLM planning:</p><pre># SOTA Tree of Thoughts with MCTS<br>class MCTSPlanner:<br>    def __init__(self, model, c_puct=1.4):<br>        self.model = model  # Can be o3 or DeepSeek R1<br>        self.c_puct = c_puct  # Exploration parameter<br>        <br>    def select(self, node):<br>        # UCB1 selection: balance exploration/exploitation<br>        best_score = -inf<br>        for child in node.children:<br>            score = child.value + self.c_puct * child.prior * sqrt(node.visits) / (1 + child.visits)<br>            if score &gt; best_score:<br>                best_child = child<br>        return best_child<br>    <br>    def evaluate(self, state):<br>        # Use reasoning model to score state<br>        response = self.model.generate(<br>            f&quot;Rate probability of success (0-1): {state}&quot;,<br>            reasoning_effort=&quot;high&quot;  # o3 parameter<br>        )<br>        return float(response)</pre><p><strong>Monte Carlo Tree Search with LLMs </strong>represents the current frontier in agentic planning. Here, the LLM serves as both the <em>policy network</em> (suggesting promising actions) and the <em>value network</em> (estimating state quality), replacing the neural networks traditionally trained via self-play in AlphaGo . Recent systems like AlphaProof demonstrate the power of this approach: by combining LLM intuition with MCTS exploration and formal verification, the system solves International Mathematical Olympiad problems that defeat pure neural or pure symbolic approaches . The key insight is that search amplifies reasoning: an LLM with modest accuracy becomes superhuman when allowed to explore thousands of reasoning paths and verify candidates.</p><p><a href="https://arxiv.org/pdf/2308.09687"><strong>Graph of Thoughts (GoT)</strong></a> further generalizes this to arbitrary graph structures, where thoughts can aggregate (merging multiple solution attempts), refine (iterative improvement), or generate (exploration) . Unlike trees where nodes have single parents, graphs allow “thought transformations” — combining insights from divergent reasoning paths. This mirrors human creative problem-solving, where solution components from failed attempts often inform successful ones.</p><p>However, these search-based methods face the <strong>computational grounding problem</strong>: exploring thousands of reasoning trajectories internally (in token space) is expensive, while exploring them externally (via environment interaction) may be impossible (e.g., when actions have real-world costs or time constraints). Recent work addresses this through “world models” — LLM-based simulators that approximate environment dynamics, allowing the agent to conduct mental simulations (System 2 internal) before committing to physical actions (System 2 external) . The agentic controller thus operates a hierarchy: rapid internal search over simulated outcomes, followed by conservative external execution of verified plans.</p><h4>C. Hierarchical Reasoning and Cognitive Architectures</h4><p>Long-horizon agency requires abstraction — the capacity to plan at multiple temporal scales. A human planning a conference doesn’t sequence individual keystrokes (“move cursor to Chrome icon”); they operate at mid-level goals (“book venue”) composed of sub-goals (“check availability,” “compare prices,” “sign contract”), which themselves decompose into atomic actions. Recent agentic architectures implement similar hierarchies through meta-cognitive scaffolding.</p><p><strong>Reflexion</strong> (Shinn et al., 2023) introduces <strong><em>self-reflective agents</em></strong> that maintain a memory of past failures . Unlike standard ReAct agents that forget previous episodes, Reflexion agents write verbal “self-reflections” to a memory buffer (“I failed because I assumed the API response would contain a ‘price’ field, but it uses ‘cost’”). In subsequent trials, the LLM conditions its reasoning on this experiential memory, implementing a form of in-context learning from autonomous experience. This addresses the temporal grounding gap: rather than the plan becoming stale, the planner itself evolves.</p><p><strong>Voyager</strong> (Wang et al., 2023) implements a <em>skill library</em> for embodied agents in Minecraft . When the agent successfully executes a novel procedure (“craft a stone pickaxe”), it synthesizes the code into a reusable function, stored with a natural language description embedding. Future planning can then invoke this skill as a primitive action, enabling compound learning — the agent builds increasingly sophisticated behaviors from verified components, mirroring human procedural memory.</p><p><strong>AdaPlanner</strong> (Sun et al., 2024) and similar systems introduce adaptive planning that dynamically adjusts plan granularity based on uncertainty . When confidence is high, the agent executes open-loop plans (long sequences without observation); when uncertainty spikes (e.g., entering an unfamiliar webpage), it switches to closed-loop ReAct-style micro-steps. This optimizes the cost-accuracy tradeoff: frequent observations provide grounding but incur latency and API costs.</p><p><strong>Multi-Agent Architectures</strong> decompose reasoning across specialized instances. Rather than one LLM attempting universal competence, systems like <em>MetaGPT</em> or <em>ChatDev</em> assign distinct agents to roles — Product Manager, Architect, Developer, Tester — each maintaining separate context windows and reasoning chains that interact via structured communication protocols . This implements <em>collective reasoning</em>: the “System 2” is distributed across multiple processes, with debate and verification emerging from inter-agent critique rather than intra-agent deliberation.</p><p><strong>Tool-Augmented Verification </strong>addresses the grounding gap by outsourcing verification to external systems. When an agent generates a plan (e.g., a Python script), it does not merely simulate execution internally; it executes the code in a sandboxed environment, captures the traceback if it fails, and feeds the error message back into the reasoning loop (CodeAct paradigm) . This hybrid architecture — neural reasoning + symbolic verification — combines the flexibility of LLMs with the precision of formal methods. Recent systems like <em>LLM+P</em> (LLM + Classical Planner) explicitly decompose planning: the LLM parses natural language goals into PDDL (Planning Domain Definition Language) specifications, invokes classical AI planners (fast, optimal, verifiable) to generate action sequences, then translates these back into executable commands.</p><h4><strong>The Unified Control Loop</strong></h4><p>Synthesizing these advances, the modern agentic architecture operates as a multi-level control system:</p><ol><li><strong>Strategic Level:</strong> An LLM generates high-level intent (“Organize a team offsite in Tokyo”)</li><li><strong>Tactical Level:</strong> The intent is decomposed via ToT/MCTS search into sub-goals (flights, hotels, visas)</li><li><strong>Execution Level:</strong> Each sub-goal invokes ReAct loops with tool use (APIs, browsers, code)</li><li><strong>Verification Level: </strong>External validators check preconditions (budget constraints, calendar conflicts)</li><li><strong>Metacognitive Level:</strong> Reflexion-style memory updates the agent’s world model based on execution outcomes</li></ol><blockquote>This architecture does not eliminate the LLM’s reasoning limitations — it <strong>compensates</strong> for them through environmental coupling. The commitment gap is managed through checkpointing (save states before irreversible actions); the grounding gap through verification loops; the temporal gap through reactive replanning. Reasoning becomes not an internal monologue but a<strong> control<em> </em>process</strong> — an ongoing conversation between the model’s generative capacity and the world’s resistant reality.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1BO8m7ZnSdR335ByYSPFcA.png" /><figcaption>Figure 2: The Unified Control Loop. The modern agentic architecture operates as a multi-level control system where (1) Strategic intent is decomposed at the Tactical level via search algorithms, (2) Execution occurs through environmental feedback loops, (3) Verification provides checkpointing to manage commitment risks, and (4) Metacognitive memory enables learning across episodes. This architecture compensates for inherent LLM limitations through environmental coupling rather than reasoning enhancement alone.</figcaption></figure><h3>IV. The Synthesis: Three Modes of Agentic Reasoning</h3><p>Thus far, we have mapped the technical evolution from static LLM reasoning to dynamic agentic architectures. Yet this progression raises a deeper question: when does sophisticated reasoning become reliable planning? The answer lies not in any single mechanism, but in the mode of reasoning employed — how <strong>cognitive work is distributed across internal deliberation, external tools, and collective intelligence</strong>. I propose that agentic systems operate through three distinct yet complementary modes of reasoning, each addressing specific limitations of pure neural computation.</p><h4>A Reflective Mode: Internal Deliberation as Self-Correction</h4><p>The reflective mode corresponds to System 2 thinking directed inward — reasoning about one’s own reasoning. This is the domain of inference-time scaling models (o1, DeepSeek R1, Gemini 2.0 Flash Thinking), which allocate additional computation to generate extended “chains of thought” before committing to actions . Unlike standard Chain-of-Thought prompting, which merely elicits pre-trained patterns, <strong>reflective mode implements active self-correction</strong>: the model identifies errors in its own reasoning, backtracks from dead ends, and verifies intermediate steps through internal consistency checks.</p><p>DeepSeek R1 demonstrates that this capability can emerge from <strong>pure reinforcement learning without supervised fine-tuning</strong>. When optimized with verifiable reward signals (correctness of final answers), the model spontaneously develops behaviors resembling human deliberation: it restates problems in its own words, explores multiple solution strategies (“Alternatively, we could factor this…”), and allocates more tokens to steps with high uncertainty . This is metacognitive monitoring — the system tracks its own confidence and allocates computational resources accordingly.</p><p>The reflective mode addresses the <em>reasoning decay</em> problem identified in Section II. By pausing to verify (“Wait, does this step follow from the previous?”), the model reduces the compounding error rate in multi-step chains. Recent work on process-based reward models (PRMs) formalizes this: rather than rewarding only correct final answers, PRMs provide feedback on the validity of intermediate reasoning steps, training the model to recognize and correct faulty logic <em>during</em> generation .</p><p>However, reflective mode remains fundamentally stateless with respect to external reality. It can catch logical contradictions but not factual obsolescence. When o1 spends 30 seconds internally verifying a flight itinerary, the seat availability it “verified” against its internal world model may have changed during those 30 seconds. Reflective mode improves reasoning quality but not grounding; it is necessary but insufficient for agency.</p><h4>B. Instrumental Mode: Tools as Extended Cognition</h4><p>The instrumental mode addresses the grounding gap by externalizing cognitive work. Here, reasoning extends beyond the neural network into the environment — APIs become external working memory, code interpreters become simulators, and computer interfaces become sensory organs. This aligns with the “extended mind” thesis in cognitive science: cognitive processes are not bounded by the skull (or the context window) but distributed across the tools we wield .</p><p>Recent advances in computer use capabilities exemplify this shift. Anthropic’s Claude 3.5 Sonnet (Computer Use) and OpenAI’s Operator do not merely generate text descriptions of actions; they perceive pixel-level screenshots, reason about UI element locations (“The ‘Submit’ button is at coordinates 450, 200”), and execute precise mouse movements and keystrokes . The reasoning loop now incorporates visual perception: the model sees the actual state of the world, not just a text description of it.</p><p>Instrumental reasoning manifests in three forms:</p><ol><li><strong>Retrieval-augmented reasoning</strong>: External knowledge bases (vector databases, search engines) expand the model’s knowledge beyond training cutoffs</li><li><strong>Executable reasoning</strong>: Code interpreters allow the model to “think” via execution — calculating exact arithmetic, running simulations, or validating logic through empiricism rather than pattern matching</li><li><strong>Embodied reasoning</strong>: Physical or virtual robotics ground abstract plans in sensorimotor loops, where actions have measurable physical consequences</li></ol><p>The critical advantage is verifiability. When an LLM reasons reflectively about “what 343 × 12 equals,” it relies on learned patterns that may hallucinate. When it reasons instrumentally by executing Python (print(343*12)), the result is verified by the external interpreter.<strong> The tool serves as an epistemic anchor,</strong> tethering abstract reasoning to ground truth.</p><h4>C. Collective Mode: Distributed Cognition</h4><p>The collective mode distributes reasoning across multiple specialized agents, implementing a form of “society of mind” where cognition emerges from the interaction of distinct cognitive processes . Rather than burdening a single LLM with universal competence, collective systems instantiate separate agents for distinct functions: Planner, Critic, Executor, Verifier.</p><p><strong>MetaGPT</strong> and <strong>ChatDev</strong> demonstrate this architecture for software development . A “Product Manager” agent decomposes requirements, an “Architect” designs the system structure, a “Developer” writes code, and a “Tester” verifies functionality. Each agent maintains separate context windows and reasoning chains; communication occurs through structured handoffs (design documents, code reviews) that enforce interface contracts.</p><p>The collective mode addresses the <em>capacity</em> limitations of single models. While individual LLMs suffer from context window constraints and reasoning decay, multi-agent systems parallelize cognition. Recent work shows that multi-agent debate — where distinct agents propose solutions and critique each other’s reasoning — consistently outperforms single-agent chain-of-thought on complex reasoning tasks . The “critic” agent serves as an externalized reflective mode, supplying the self-correction capability that single models often lack.</p><p>Furthermore, collective mode enables specialization. Agents can be fine-tuned or prompted for specific reasoning styles: one agent optimized for creative divergence (generating many options), another for critical convergence (evaluating options against constraints). This mirrors human organizational structures where teams combine diverse cognitive styles to solve complex problems.</p><p>The code bellow demonstrates the synthesis — how the three modes integrate in a real system:</p><pre># SOTA Multi-Mode Agent System<br>class HybridAgentSystem:<br>    def __init__(self):<br>        self.fast_model = OpenAI(model=&quot;gpt-4o&quot;)      # System 1 - Instrumental<br>        self.slow_model = OpenAI(model=&quot;o3&quot;)          # System 2 - Reflective  <br>        self.critic = OpenAI(model=&quot;gpt-4o&quot;)          # Collective - Critic<br>        <br>    async def plan(self, task):<br>        # Collective Mode: Multi-agent debate<br>        drafts = await asyncio.gather(<br>            self.generate_plan(persona=&quot;optimist&quot;),<br>            self.generate_plan(persona=&quot;pessimist&quot;),<br>            self.generate_plan(persona=&quot;conservative&quot;)<br>        )<br>        <br>        # Reflective Mode: o3 verifies each draft<br>        verified = []<br>        for draft in drafts:<br>            verification = self.slow_model.verify(draft)  # Test-time compute<br>            if verification.confidence &gt; 0.9:<br>                verified.append(draft)<br>        <br>        # Instrumental Mode: Execute with tools<br>        for plan in verified:<br>            result = await self.execute_with_tools(plan)<br>            if result.success:<br>                return result</pre><h4>D. The Planning-Rubicon: From Reasoning to Agency</h4><p>These three modes converge at what we might term the Planning-Rubicon — the threshold where abstract reasoning transforms into committed planning. Reasoning becomes planning when three conditions are met:</p><p>Commitment: The system crosses from reversible deliberation to irreversible action. Reflective mode can simulate booking a flight indefinitely; planning requires the commitment to actually invoke the API and charge the credit card.</p><p>Grounding: The reasoning is anchored to verifiable state changes. Instrumental mode provides this grounding, but planning requires that the grounding occurs <em>during</em> execution, not just in simulation.</p><p>Temporality: The system accounts for time passing and state changing between reasoning steps. Collective mode enables this through persistent memory and inter-agent coordination across time.</p><p>Recent “agentic” architectures like ReAct, Reflexion, and Voyager essentially operate as hybrid systems that orchestrate all three modes. They employ reflective loops for local decision-making, instrumental tool use for environmental grounding, and collective architectures (either explicitly multi-agent or implicitly through memory-augmented personas) for long-horizon coordination.</p><p>The transition from LLM to agent is not merely adding tools or extending context windows, but implementing this tripartite synthesis. Pure reasoning models (o1-style System 2) remain on the near side of the Rubicon — they think, but do not act. True agents combine reflective depth, instrumental grounding, and collective persistence to cross into the territory of autonomous planning.</p><h3>VI. Conclusion</h3><p>The paradox with which we began — mathematical olympiad excellence paired with flight-booking failure — resolves not through better reasoning algorithms, but through architectural humility. Agentic systems acknowledge that LLMs, whether fast (GPT-4o) or slow (o3), remain pattern-completers rather than causal reasoners; they compensate by embedding these generators within feedback loops (ReAct), verification layers (ToT/MCTS), and hierarchical control structures that ground symbolic plans in environmental state. The future of artificial intelligence lies not in monolithic minds that reason flawlessly, but in orchestrated assemblies that reason <em>responsibly</em> — acknowledging uncertainty through checkpointing, hedging commitment through verification, and accepting that intelligence, whether human or artificial, is measured not by the elegance of its internal monologue, but by the reliability of its external dialogue with the world.</p><h4>References</h4><p>1. Hao, S., et al. (2023). “Reasoning with Language Model is Planning with World Model.” <em>arXiv preprint arXiv:2305.14992.</em></p><p>2. DeepSeek-AI. (2025). “DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning.” <em>arXiv preprint arXiv:2501.12948.</em></p><p>3. Chung et al. (2024). “Scaling Test-Time Compute Optimally Can Be More Effective Than Scaling Model Parameters.” <em>OpenAI Research.</em></p><p>4. Wang, L., et al. (2023). “Planning with Large Language Models: A Survey.” <em>AI Magazine.</em></p><p>5. Kahneman, D. (2011). <em>Thinking, Fast and Slow</em>. Farrar, Straus and Giroux.</p><p>6. Wu, S., et al. (2024). “The Emergent Mirage: On the Limitations of Multi-Step Reasoning in LLMs.” <em>Research Paper</em> (Cited in context of reasoning decay and bounded lookahead).</p><p>7. Wei, J., et al. (2022). “Chain-of-Thought Prompting Elicits Reasoning in Large Language Models.” <em>NeurIPS 2022.</em></p><p>8. Chen et al. (2025). “Reasoning Problems in Large Language Models.” <em>Nature Biomedical Engineering</em> (Cited for hallucinations and planning failures).</p><p>9. Wang, X., et al. (2023). “Self-Consistency Improves Chain of Thought Reasoning in Language Models.” <em>ICLR 2023.</em></p><p>10. Yao, S., et al. (2023). “ReAct: Synergizing Reasoning and Acting in Language Models.” <em>ICLR 2023.</em> <a href="https://arxiv.org/abs/2210.03629">[Link]</a></p><p>11. OpenAI. (2025). “Operator System Card.” <em>OpenAI Safety Documentation.</em> (Computer Using Agent)</p><p>12. Anthropic. (2024). “Computer Use.” <em>Anthropic Documentation.</em> (Claude 3.5 Sonnet computer use capabilities)</p><p>13. Yao, S., et al. (2023). “Tree of Thoughts: Deliberate Problem Solving with Large Language Models.” <em>NeurIPS 2023.</em> <a href="https://arxiv.org/abs/2305.10601">[Link]</a></p><p>14. Silver, D., et al. (2017). “Mastering the Game of Go without Human Knowledge.” <em>Nature</em> (MCTS foundation); Recent LLM+MCTS: Feng et al. (2023), “Alphazero-like Tree-Search can Guide Large Language Model Decoding and Training.”</p><p>15. Besta, M., et al. (2024). “Graph of Thoughts: Solving Elaborate Problems with Large Language Models.” <em>AAAI 2024.</em></p><p>16. Shinn, N., et al. (2023). “Reflexion: Self-Reflective Agents with Verbal Reinforcement Learning.” <em>NeurIPS 2023.</em></p><p>17. Wang, G., et al. (2023). “Voyager: An Open-Ended Embodied Agent with Large Language Models.” <em>arXiv preprint arXiv:2305.16291.</em></p><p>18. Sun, H., et al. (2024). “AdaPlanner: Adaptive Planning from Feedback with Language Models.” <em>NeurIPS 2024.</em></p><p>19. Hong, S., et al. (2024). “MetaGPT: Meta Programming for A Multi-Agent Collaborative Framework.” <em>ICLR 2024.</em>; Qian, C., et al. (2023). “ChatDev: Communicative Agents for Software Development.” <em>ACL 2024.</em></p><p>20. Wang, Q., et al. (2024). “Executable Code Actions Elicit Better LLM Agents.” <em>ICML 2024.</em> (CodeAct)</p><p>21. Liu, B., et al. (2023). “LLM+P: Empowering Large Language Models with Optimal Planning Proficiency.” <em>arXiv preprint arXiv:2304.11477.</em></p><p>22. Wei, J., et al. (2022). “Emergent Abilities of Large Language Models.” <em>TMLR</em>.</p><p>23. Elazar, Y., et al. (2021). “Measuring and Improving Consistency in Pretrained Language Models.” <em>ACL</em>.</p><p>24. Qian, J., et al. (2022). “Emergent Linguistic Structure in Artificial Neural Networks Trained by Self-Supervision.” <em>Nature</em>. :</p><p>25. Kaplan, J., et al. (2020). “Scaling Laws for Neural Language Models.” <em>arXiv</em>. : DeepSeek-AI. (2024). “DeepSeek-V3 Technical Report.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbefd10ebf3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Generative to Agentic AI: A Roadmap in 2026]]></title>
            <link>https://medium.com/@anicomanesh/from-generative-to-agentic-ai-a-roadmap-in-2026-8e553b43aeda?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e553b43aeda</guid>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <category><![CDATA[agentic-ai-solution]]></category>
            <category><![CDATA[agentic-ai-development]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 17:05:31 GMT</pubDate>
            <atom:updated>2026-01-28T17:37:59.632Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why the future isn’t about better Brains and Prompts — it’s about better Systems. A survival guide for the AI Engineers.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8oWaKJyWqWlvy_VyJGLS6A.jpeg" /><figcaption>Image by <strong>Google DeepMind</strong></figcaption></figure><h3>0. Introduction: The Shift from “Chat” to “Work”, <strong>The Honeymoon is Over !</strong></h3><p>If 2023 was the year of <strong>Magic</strong> — when we first felt the awe of ChatGPT conversing like a human — and 2024 was the year of <strong>Integration</strong> — when we scrambled to wire that magic into our documents via RAG (Retrieval-Augmented Generation) — then 2<strong>026 brings a stark, unyielding reality check.</strong></p><p>For three years, the entire industry has been hypnotized by the “text box.” We spent billions of dollars and millions of engineering hours optimizing the art of <strong>Conversation</strong>. We built sophisticated pipelines just to fetch a PDF, stuff it into a context window, and applaud when the model summarized it without hallucinating. We treated Artificial Intelligence as a digital oracle: a passive, bodiless entity that sat on a server, waiting for us to ask it a question so it could generate an answer.</p><p>But looking around the <strong>landscape of 2026</strong>, one thing is abundantly clear: <strong>We are seeing a shift from conversational demonstrations to operational agentic systems. Enterprises increasingly expect agents that perform end-to-end work (monitor → plan → act) rather than only generate text; </strong><a href="https://www.gartner.com/en/newsroom/press-releases/2026-01-15-gartner-predicts-60-percent-of-brands-will-use-agentic-ai-to-deliver-streamlined-one-to-one-interactions-by-2028#:~:text=By%202028%2C%2060%25%20of%20brands,era%20of%20personalized%2C%20autonomous%20engagement."><strong>Gartner</strong></a><strong> predicts rapid adoption of agentic capabilities across brands, especially where one-to-one, automated interactions are strategic..</strong></p><p>The novelty of talking to your data has evaporated. The businesses winning today — in marketing, healthcare, finance, and logistics — are no longer asking:<br><strong><em>“Can the AI explain this compliance report?”</em></strong></p><p>They are demanding: <br><strong><em>“Can the AI read the report, flag the three critical risks, draft the legal notice, and update the immutable ledger — while I sleep?”</em></strong></p><p>We are witnessing a fundamental phase shift in the history of computing. We are moving from <strong>Generative AI</strong> (Creative, Passive, Read-Only) to <strong>Agentic AI</strong> (Functional, Active, Read-Write). We are no longer building systems that simply describe the world; <strong>we are building systems that change it.</strong></p><p>This evolution is already underway. Industry analysts highlight a paradigm shift:</p><p>“Unlike traditional automation that follows predetermined rules, agentic AI demonstrates autonomous decision-making, continuous learning, and adaptive behavior that fundamentally transforms industrial operations”. Surveys and forecasts bear this out: Gartner named agentic AI a top trend for 2026, and a Deloitte study predicts that half of enterprises using GenAI will deploy autonomous agents by 2027. In short, 2026 is poised to be the year when generative experiments turn into<strong> </strong><a href="https://xmpro.com/the-complete-guide-to-agentic-ai-in-industrial-operations-how-ai-agents-are-transforming-manufacturing-mining-and-asset-intensive-industries-in-2025/"><strong>operational agentic systems</strong></a>. Organizations that recognize and prepare for this shift will be positioned to leverage new efficiency and innovation gains.</p><p>The vast majority of “AI Engineers” today are unprepared for this reality. They are excellent at <strong>Prompt Engineering</strong> — coaxing a probabilistic model to sound smart. They are experts at <strong>Fine-Tuning</strong> — teaching a model new facts. But they are often novices at <strong>Systems Engineering</strong>. They optimize for <em>perplexity</em> and <em>recall</em>, while the production environment screams for <strong>latency</strong>, <strong>idempotency</strong>, and <strong>state management.</strong></p><h4>Thesis: The Architectural Leap from Prompts to Plans</h4><p>To cross the chasm from the “Chatbot Era” to the “<strong>Agentic Era</strong>,” <br>we must fundamentally rewire our approach. We cannot prompt our way to reliability. We cannot fine-tune our way out of a race condition. Building clinical-grade, high-stakes agents requires us to abandon the comfortable, probabilistic playground of the Data Scientist and embrace the rigid, defensive, and deterministic discipline of the Systems Engineer.</p><p>The future of AI isn’t about better brains. It’s about better bodies. And it belongs to the architects who know how to build them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*ssQAHI6tykm3-OPTZAjkMg.png" /><figcaption><strong>Figure 1. LLMs vs RAG vs AI Agents vs Agentic AI. Source: Meritshot Academy</strong></figcaption></figure><p>The movement from GenAI to agentic AI is <strong>not a mere upgrade of the LLM engine</strong> but a fundamental architectural leap. Traditional prompt-based systems treat LLMs as “brains in a jar” — heavy on probabilistic output generation but with no built-in planning or persistence. In contrast, agentic systems distribute responsibilities: the LLM still provides semantic reasoning and content generation, but deterministic software layers orchestrate planning, tool execution, and governance.</p><p>In practical terms, the shift is from tuning prompts to designing systems[ 2] . Prompt engineering can optimize one-shot tasks, but it cannot compensate for a lack of continuity or safety. As one expert points out, relying solely on ever-clever prompts “fails when dealing with dynamic environments where goals may shift, new information may emerge, or unexpected scenarios require adaptive responses”. The industry mantra is evolving: <strong>move beyond response to proactive problem-solving</strong>. An agentic architecture gives the AI a persistent “purpose” and context, whereas prompting alone can never encode all business rules or anticipate all contingencies.</p><p>To illustrate, consider a GenAI-powered chatbot vs. an agentic assistant. A chatbot may answer support tickets and escalate unusual cases. An agent, by contrast, can autonomously review hundreds of past tickets (perception), identify systemic issues (planning), generate and send email campaigns to affected customers (execution), and retrain itself on any feedback (feedback). It’s like upgrading from an answering machine to a self-directed digital teammate. Architecturally, this requires <strong>complex workflows and integrations</strong>, not just smarter text generation. As one industry write-up advises, architects must “diagnose the constraint and prescribe the pattern” rather than chase the shiniest model.</p><h3>1. The Architectural Battlefield (It’s Not Just Microservices)</h3><p><strong>The “One Size Fits All” Myth is Dead.</strong></p><p>If you ask a junior engineer how to architect an AI agent in 2026, they will likely show you a Python script that loops through OpenAI calls. If you ask a mid-level engineer, they will draw you a diagram of microservices communicating via REST. But if you ask a <strong>Principal Architect</strong>, they won’t draw anything until they ask you a single, defining question:</p><p><em>“What is the blast radius of a failure, and what is your latency budget?”</em></p><p>In 2026, the architectural landscape for Agentic AI has fractured. We have moved past the naive phase of shoving every agent into a Kubernetes pod or, conversely, running everything in a massive agent.py monolith. The industry has split into three distinct &quot;Tribes,&quot; each optimizing for a ruthless, specific constraint: <strong>Risk</strong>, <strong>Speed</strong>, or <strong>Cost</strong>.</p><p>Successful architects do not pick the “trendy” architecture; they pick the one that survives their specific environment.</p><h4>Tribe 1: The Enterprise Standard (Microservices)</h4><ul><li><strong>The Philosophy:</strong> <em>Isolation is Survival.</em></li><li><strong>Primary Metric:</strong> Governance &amp; Auditability.</li><li><strong>The Stack:</strong> Kubernetes, gRPC, Istio (mTLS), OPA (Open Policy Agent).</li></ul><p>In high-liability domains — Healthcare, Finance, and LegalTech — microservices remain the undefeated king. But this isn’t the “microservices” of 2020 web apps. This is <strong>Agentic Isolation</strong>.</p><p>In an Agentic Microservices architecture, every functional “limb” of the system is a separate container. The <strong>Planner</strong> is a service. The <strong>Memory Store</strong> is a service. The <strong>Tools</strong> (like a Risk_Calculator or Trade_Executor) are strictly isolated services wrapped in rigid API contracts (often defined via MCP).</p><p><strong>Why It Wins Here:</strong></p><ol><li><strong>Blast Radius Containment:</strong> In a clinical system, if a “Billing Agent” enters an infinite retry loop or starts hallucinating, it must be killed instantly without taking down the “Life Support Agent.” In a monolith, a memory leak in one agent crashes the whole brain. In microservices, you just kill the pod.</li><li><strong>Policy-as-Code Guardrails:</strong> You can inject sidecars (like Open Policy Agent) that intercept every single tool call. You can enforce rules like <em>“The Discharge Agent cannot call the Email Tool if the PII Confidence Score is &lt; 99%.”</em> This happens at the network layer, meaning the LLM cannot bypass it, no matter how clever its prompt is.</li><li><strong>Team Topology:</strong> A team of 500 engineers cannot work on one agent. Microservices allow Team A to upgrade the “Risk Module” reasoning engine without breaking Team B’s “User Interface.”</li></ol><h4>Tribe 2: The Performance King (Modular Monoliths &amp; Actor Systems)</h4><ul><li><strong>The Philosophy:</strong> <em>The Network is the Bottleneck.</em></li><li><strong>Primary Metric:</strong> Latency (Time-to-First-Token).</li><li><strong>The Stack:</strong> Ray, Akka, Erlang/Elixir, Rust, Shared Memory (Plasma Store).</li></ul><p>For Consumer AI — Real-time Voice Assistants, Gaming NPCs, and Co-pilots — microservices are a death sentence.</p><p>The enemy of Agentic AI is the <strong>Network Tax</strong>. If Agent A asks Agent B a question, and Agent B asks Agent C… in a microservices architecture, that is 3 HTTP/gRPC hops. Each hop involves serialization (JSON to Bytes), network transport, and deserialization. <strong>In real deployments, hops can add tens to hundreds of ms; with large payloads or cross-zone calls it can spike higher</strong>.For a voice assistant, that pause makes the AI feel “dumb” and robotic.</p><p><strong>Why It Wins Here:</strong></p><ol><li><strong>Zero-Copy Context:</strong> In 2026, agents share massive context windows (1MB+ of text). Sending 1MB of JSON over HTTP between services is slow. In a Modular Monolith (specifically using Actor Frameworks like <strong>Ray</strong>), agents pass a <strong>pointer</strong> to a memory block. Agent B reads Agent A’s thought process instantly — zero latency, zero serialization.</li><li><strong>Synchronous Reasoning:</strong> Complex reasoning requires tight loops. A monolithic architecture allows for “Thinking at the Speed of CPU,” not “Thinking at the Speed of WiFi.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*icF7S8_CS20Ytn-Kj0q18w.png" /><figcaption><strong>Figure 2. Agentic AI Systems: Architecture Trade-offs , Figure by the author</strong></figcaption></figure><h4>Tribe 3: The Cost-Cutter (Serverless Swarms)</h4><ul><li><strong>The Philosophy:</strong> <em>If it’s not working, it shouldn’t exist.</em></li><li><strong>Primary Metric:</strong> Utilization (Cost-per-Execution).</li><li><strong>The Stack:</strong> AWS Lambda / Cloud Run, Temporal (Durable Execution), EventBridge.</li></ul><p>This is the architecture of choice for background data processing, news aggregation, and “Crowd” research agents.</p><p><strong>Why It Wins Here:</strong></p><ol><li><strong>The “Waiting Problem”:</strong> Agents are notoriously inefficient. They spend 99% of their time <strong>waiting</strong> — waiting for the LLM to generate tokens, waiting for a web page to scrape, waiting for human approval.</li><li><strong>Scale-to-Zero Economics:</strong> Running a high-availability Kubernetes cluster (Tribe 1) requires paying for GPUs/CPUs 24/7, even if no one is using the agent. In a Serverless Swarm, the agent exists only as a Lambda function. It wakes up when a file lands in S3, performs its reasoning, writes the state to a durable ledger (like Temporal), and immediately dies. You pay for 300ms of compute, not 24 hours of idle time.</li></ol><p><strong>Hybrid/reactive-deliberative architectures:</strong> In many production systems, the best answer is a blend. Agents may run a fast “reactive” loop for trivial tasks (straightforward rules, cached lookups) alongside a slower “deliberative” loop for complex reasoning. A <strong>supply-chain assistant, for example, might instantly re-route a single delivery around a road closure (reactive) while running a multi-minute simulation to rebalance the entire network (deliberative)</strong>.</p><p>My research shows that planning layers typically add seconds of latency per decision and heavy compute load, so teams reserve them for high-value subtasks. The hybrid approach admits the benefit of both worlds: <strong>immediate fixes where possible, in-depth planning where needed.</strong></p><p>Key Takeaway for the Architect:</p><p>There is no “Best Architecture.” There is only the architecture that matches your Risk Profile.</p><ul><li>Building a <strong>Doctor</strong>? Use <strong>Microservices</strong> (Safety first).</li><li>Building a <strong>Friend</strong>? Use a <strong>Monolith</strong> (Speed first).</li><li>Building a <strong>Researcher</strong>? Use <strong>Serverless</strong> (Cost first).</li></ul><p>Successful 2026 architects don’t chase hype; they diagnose the constraint and prescribe the pattern.</p><h3>2. The “Brain” vs. The “Body” (Anatomy of an Agent)</h3><p><strong>The Fallacy of the “Brain in a Jar.”</strong></p><p>In 2024, the industry often made the mistake of asking the Large Language Model (LLM) to be everything: the planner, the executor, and the validator. In 2026, we know that this pattern is fundamentally unsafe for high-stakes environments.</p><p>In clinical-grade and high-reliability systems, we now use a <strong>Neuro-Symbolic Architecture</strong>. This means we explicitly separate the <strong>“Thinking”</strong> (Probabilistic) from the <strong>“Orchestration”</strong> (Deterministic). If we conflate them, we lose the ability to guarantee safety.</p><p>To build a true Agent, we separate the architecture into five distinct anatomical structures.</p><h4>Anatomy: Key Components of an Agentic System</h4><p>Despite the diversity of use cases, sophisticated agents share a common internal structure. Research literature defines essential components that any agentic AI must include to ensure reliability and safety:</p><p><strong>1.Perception/Input Processing:</strong> The agent must gather and interpret data from the world. This could be natural language queries, system logs, database records, sensor feeds, or any combination there. The perception module cleanses and structures inputs (using NLP, vision, or data extraction) so the agent can reason on them. Its design depends on context — e.g., an industrial agent might fuse time-series sensor data with equipment metadata, while a financial agent might parse real-time market feeds. Accuracy here is critical: misinterpretation at the input stage can send the whole agent off.</p><p><strong>2. Memory/Context:</strong> Unlike single-turn chatbots, agentic systems maintain state over time. A memory component consolidates short-term context (the current conversation or task history) with long-term knowledge (user preferences, database contents, or domain rules). Modern agents often use vector stores or knowledge graphs as memory backends. This lets the agent recall past decisions, share knowledge across sub-tasks, and avoid repeating work.</p><p><strong>3. Planning/Reasoning Engine:</strong> At the core is the agent’s intelligence, but in modern architectures, this is strictly divided into two roles: the <strong>Cognitive Engine</strong> and the <strong>Reasoning Orchestrator</strong>.</p><ul><li>The <strong>Cognitive Engine</strong> (the LLM) acts purely as a consultant, using probabilistic reasoning to propose a <em>draft</em> strategy or set of steps.</li><li>The <strong>Reasoning Orchestrator</strong> (deterministic code) then validates this draft against rigid business rules and converts it into an executable task graph (DAG)</li><li>This separation ensures the system does not blindly execute hallucinations. Crucially, this layer acts as the <strong>“Conscience”</strong> of the system: a governance gate that strictly vetoes any plan violating safety policies before it can proceed to execution.</li></ul><p><strong>4. Action/Execution Layer:</strong> Once a plan is validated, the agent must carry out its decisions. This layer orchestrates calls to <strong>external tools</strong>, APIs, robotic interfaces, or human workflows. It functions as the “hands” of the agent, utilizing standardized interfaces (such as the MCP: Model Context Protocol) to ensure reliable interaction with external systems. The execution layer also handles transactional issues: it manages retries, timeouts, error handling, and any required rollbacks to ensure the system remains stable even when tools fail1.</p><p><strong>5. Feedback Loop/Monitoring:</strong> The final component closes the loop. The agent must observe the outcomes of its actions and measure progress toward the goal. This includes monitoring metrics, confirming success, or detecting anomalies1. The feedback system then informs the next cycle: it updates memory, reports results to stakeholders, and may trigger a re-planning if the situation changed. In production systems, comprehensive logging of each action’s outcome is part of this layer — both for tuning the agent and for auditability.</p><p>According to industry analyses, integrating these pieces is what makes an AI agent “adaptive and intelligent”. For example, a virtual customer-service agent would perceive user inputs, remember prior tickets, utilize a neuro-symbolic planner to draft and validate a resolution strategy, execute via secure API connectors, and learn from customer satisfaction ratings. Each component must be carefully engineered; failure in any area can cascade into unreliable behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4cRPwuAyB-m5xZ2y1zvfg.png" /><figcaption><strong>Figure 3. Anatomy of a 2026 agentic system. Probabilistic reasoning (the “brain”) is strictly separated from deterministic orchestration and execution (the “body”), preventing hallucinations from becoming actions. Diagram by the author</strong></figcaption></figure><h3>3. The Identity Crisis (LLM Engineer vs. AI Systems Engineer)</h3><p><strong>The “Imposter Syndrome” of 2026.</strong></p><p>As we transition from the playground of Chatbots to the production line of Agents, a specific anxiety has gripped the AI engineering community.</p><p>On one side, we have the <strong>Data Scientists and LLM Engineers</strong>. You spent the last three years mastering Transformers, understanding attention mechanisms, optimizing RAG pipelines, and fine-tuning LoRA adapters. You know <em>how</em> the model thinks. But now, you look at Agentic architectures and see “Microservices,” “Kubernetes,” “Async Event Loops,” and “gRPC.” You worry that your skills are obsolete because you aren’t a traditional Backend Developer.</p><p>On the other side, we have the <strong>Backend Developers</strong>. They know how to scale APIs and manage databases. But they treat the LLM as a “black box” API call, unaware of the stochastic chaos inside. They try to fix hallucinations with if/else statements and wonder why the system keeps breaking.</p><p><em>Here is the reality of 2026: </em><strong><em>Both of them are wrong.</em></strong></p><p>To build industrial-grade agents, we do not need a Web Developer who knows React, nor do we need a Researcher who reads ArXiv papers all day. We need a new, hybrid species: <strong>The AI Systems Engineer.</strong></p><h4>1. The Myth: “I Need to Be a Backend Developer”</h4><p>Let’s clarify what “Backend” means in the context of Agentic AI.</p><p>You do not need to know how to center a div in CSS. You do not need to be an expert in Postgres query optimization or OAuth2 login flows for user dashboards.</p><p>However, you <strong>must</strong> become an expert in <strong>Interfaces and State.</strong></p><p><strong>The Old World:</strong> You wrote a Python script, printed the output to the console, and if it looked good, you shipped it.</p><p><strong>The New World:</strong> Agents interact with the world through <strong>APIs</strong>. If you cannot define a strict input/output <strong>contract (Schema),</strong> your agent is blind and handless.</p><ul><li><strong>The Skill</strong><em>:</em> <strong>Pydantic &amp; JSON Schema.</strong> You must learn to treat English text as a “Type.” You must be comfortable saying, <em>“If this output doesn’t validate against this Schema, the program crashes intentionally.”</em></li><li><strong>The Skill:</strong> <strong>Async/Concurrency.</strong> Agents are slow. They wait for tools. They wait for tokens. If you write synchronous code (blocking), your agent serves one user at a time. You must master the <strong>Event Loop</strong>.</li></ul><h4>2. The Secret Weapon: Why Your Generative/LLM Skills Are Critical</h4><p>If you are an LLM Engineer, do not throw away your knowledge. In the Agentic Era, your understanding of the “Brain” makes you infinitely more valuable than a generic software engineer — <strong>but only if you apply it correctly.</strong></p><p>Here is how your most important “2024 Generative Skills” map to “2026 Agentic Superpowers”:</p><h4>- Prompt Engineering → Protocol Design</h4><p>In 2024, you learned how to word a prompt to get a good answer. In 2026, that skill has evolved into <strong>Protocol Design</strong>. You understand that an LLM is a function call waiting to happen. You know how to structure the system prompt not just to &quot;be helpful,&quot; but to adhere to a rigid JSON schema, respect stop sequences, and handle edge cases. You aren&#39;t whispering to the model; you are programming its API contract.</p><h4>- Context Window Management → State Management</h4><p>Traditional backend engineers treat memory as a database row. You, the LLM Engineer, understand <strong>Attention</strong>. You know that &quot;Infinite Context&quot; is a lie and that performance degrades as the context fills up. You are the only one who knows how to compress a 50-turn conversation into a concise &quot;State Object&quot; without losing the nuance—preventing the agent from getting &quot;dementia&quot; in the middle of a critical operation.</p><h4>- &quot;Vibe Checking&quot; to Deterministic Evals</h4><p>You spent years looking at model outputs and spotting hallucinations. That intuition is now formalized into <strong>Model-Based Evaluation</strong>. While the backend team writes unit tests for uptime, you write the &quot;Semantic Unit Tests&quot; that run in the background: <em>Did the agent sound empathetic? Did it stay within the safety guidelines?</em> You build the automated judge that keeps the system honest.</p><h4>- Vector Search to Hybrid Knowledge Engineering</h4><p>In 2024, RAG meant &quot;dumping PDF chunks into a Vector Database&quot; and hoping for the best. In 2026, you know that vectors are lossy [8] —they capture &quot;vibes,&quot; not facts. You have evolved into a <strong>Knowledge Engineer</strong>. You architect Hybrid Search systems that combine the fuzzy retrieval of vectors with the precise keyword matching of BM25 and the structural logic of Knowledge Graphs (GraphRAG). You don&#39;t just &quot;retrieve data&quot;; you reconstruct the truth from fragmented sources.</p><h4>- Fine-Tuning → Model Distillation &amp; Routing</h4><p>The novice thinks Fine-Tuning is for teaching the model new knowledge (which hallucinations prove is wrong). You know the truth: Fine-Tuning is for <strong>Behavior and Speed</strong>. You are the &quot;Optimization Surgeon&quot; who takes a massive, expensive GPT-5 class model and distills its reasoning patterns into a tiny, localized 8B-parameter model. You don&#39;t train models to be smarter; you train them to be cheaper, faster, and perfectly obedient to your specific syntax.</p><h4>- Red Teaming to Cognitive Security (AISecOps)</h4><p>Security used to mean &quot;Firewalls&quot; and &quot;OAuth.&quot; But you know that an LLM is a porous membrane. You understand <strong>Prompt Injection</strong>—the reality that a malicious user can convince your agent to ignore its instructions just by saying &quot;Ignore previous instructions.&quot; You design the &quot;Cognitive Firewall&quot; layers: input sanitization, output guardrails, and adversarial defenses that detect when someone is trying to socially engineer your robot.</p><h4>- Console Logging → Distributed Thought Tracing</h4><p>When a standard API fails, you get a Stack Trace. When an Agent fails, you get a &quot;Reasoning Loop.&quot; Standard engineers look at logs and see valid JSON, yet the result is wrong. You specialize in <strong>Observability for Indeterministic Systems</strong>. You use tools (like OpenTelemetry adapted for LLMs) to visualize the agent&#39;s decision tree. You can trace <em>why</em> the agent chose to use the &quot;Calculator Tool&quot; instead of the &quot;Search Tool,&quot; and you can pinpoint exactly which token caused the logic to diverge.</p><h4>- Token Streaming to Speculative Execution &amp; Asynchrony</h4><p>In 2024, we dazzled users by streaming text to the screen so it looked fast. In 2026, users don&#39;t want to watch the agent think; they want the work done. You master <strong>Speculative Execution</strong>. You design architectures where the agent launches three potential tool calls in parallel (asyncio.gather) before the user even finishes typing, or anticipates the next step while the current one is processing. You trade compute cost for the illusion of instantaneous latency.</p><h4>- Tool Use → Transactional Integrity &amp; Idempotency</h4><p>A junior dev gives an agent access to a delete_file() API and prays. You, the Systems Engineer, understand <strong>Idempotency</strong>. You know that LLMs retry loops, and if an agent tries to &quot;Book Flight&quot; twice because the first request timed out, you end up with two tickets. You design the &quot;Undo&quot; buttons and the &quot;Idempotency Keys&quot; that ensure that no matter how confused the agent gets, it cannot corrupt the database state. You treat Agent Actions as ACId transactions.</p><h4>- RLHF → Runtime Human-in-the-Loop (HITL) Governance</h4><p>Reinforcement Learning (RLHF) was how we trained models in the lab. <a href="https://docs.langchain.com/oss/python/langchain/human-in-the-loop"><strong>HITL</strong></a><strong> Governance</strong> is how we survive in production. You architect the &quot;Interrupt Patterns.&quot; You know exactly where to pause the execution graph to ask the human, &quot;This action costs over $500, proceed?&quot; You design the user interfaces that allow humans to edit the agent&#39;s <em>plan</em> before it executes, effectively treating the user not just as a chat partner, but as a runtime supervisor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BexuzKik45Kds47CXj__AA.png" /><figcaption><strong>Figure 4. “2024 Generative Skills” map to “2026 Agentic Superpowers”</strong></figcaption></figure><h4>3. The “T-Shaped” Agentic Engineer</h4><p>To survive 2026, you must reshape your skills into a “T” profile.</p><p><strong>The Vertical (Deep Depth):</strong> This is your <strong>LLM Engineering</strong> core. You understand <em>why</em> the model failed. Was it the temperature? The attention mask? The token limit? You can debug the “Brain.”</p><p><strong>The Horizontal (Broad Reach):</strong> This is your <strong>Systems Engineering</strong> layer. You wrap your deep knowledge in strong interfaces.</p><ul><li>You don’t just write a prompt; you wrap it in an <strong>MCP Server</strong>.</li><li>You don’t just run a script; you serve it via <strong>FastAPI</strong>.</li><li>You don’t just print logs; you trace execution with <strong>OpenTelemetry</strong>.</li></ul><p>You are not “starting over.” You are the “Brain Surgeon” who is finally learning how to build the hospital. The construction workers (traditional backend devs) can build the walls, but only you know what equipment is needed in the operating room to keep the patient alive.</p><h3>4. The 2026 Tech Stack (The Enterprise “Golden Path”)</h3><p>If the architecture is the blueprint, the Tech Stack is the toolbox. But in 2026, the tools have changed. We are no longer simply running pip install openai and writing while True loops.</p><blockquote><strong>A Note on Context:</strong> While Section 1 outlined distinct architectures for extreme constraints (like Rust/Ray for high-frequency trading or Temporal for pure serverless swarms), the vast majority of industrial Agentic Systems in 2026 converge on a <strong>“Golden Path.”</strong></blockquote><p>The stack below represents the <strong>General Purpose Enterprise Standard</strong> — optimized for the balance of safety, developer velocity, and auditability required by Tribe 1 (Microservices) and Hybrid deployments.</p><blockquote>The modern Agentic Stack is divided by <strong>Time Allocation</strong>. <br>A practical heuristic is to prioritise deterministic infrastructure (safety, observability, schema validation) over model tinkering — for <strong>many safety-critical projects</strong> that could mean<strong> ~60% of engineering effort on the skeleton</strong>, with the remainder split between model optimization and orchestration — but teams should adapt this allocation to their risk, latency, and cost constraints.</blockquote><h4>1. The “Agentic Skeleton” (60% of Your Time)</h4><p><em>This is the non-negotiable layer. If this breaks, the agent dies.</em></p><p><strong>[ — ] Pydantic &amp; Instructor (The Protocol Layer)</strong></p><p><strong>The Shift:</strong> In 2024, we begged the LLM: <em>“Please return JSON.”</em> In 2026, we enforce it.</p><p><strong>The Tool:</strong> <a href="https://python.useinstructor.com/"><strong>Instructor</strong></a><strong> (Python)</strong>.</p><p>It patches your LLM client to return <a href="https://ai.pydantic.dev/">Pydantic</a> Objects, not strings. It handles the validation loop automatically. If the LLM generates an invalid email address field, Pydantic raises an error, and Instructor automatically feeds that error back to the LLM to self-correct. <em>“If it isn’t validated JSON, it doesn’t exist.”</em></p><p><strong>[ — ] FastAPI (The Async Runtime)</strong></p><p><strong>The Shift:</strong> From “Scripts” to “Servers.”</p><p><strong>The Tool:</strong> <strong>FastAPI</strong>.</p><blockquote><strong>Architectural Note:</strong> While Tribe 2 (Performance) architects might swap this for <strong>Ray Serve</strong> to use shared memory, <strong>FastAPI</strong> remains the undefeated standard for the 90% of agents requiring HTTP interoperability.</blockquote><p>Agents are I/O bound. They spend seconds waiting for tools. FastAPI’s native async/await support allows your server to handle hundreds of concurrent agent thoughts without blocking the main thread.</p><p><strong>[ — ] MCP (Model Context Protocol) (The Interface Standard)</strong></p><p><strong>The Shift:</strong> From “Custom Glue Code” to “Universal Drivers.”</p><p><strong>The Tool:</strong> <a href="https://modelcontextprotocol.io/docs/getting-started/intro"><strong>Official MCP SDKs</strong>.</a></p><p>In the past, connecting a database required writing a custom retrieval function. With MCP, you treat tools like USB devices. You define the resource once, and any MCP-compliant agent (Claude, OpenAI, or your custom Llama-3) can discover and use it safely.</p><p><strong>[ — ] OpenTelemetry &amp; LangSmith (The Black Box Recorder)</strong></p><p><strong>The Shift:</strong> From “Grepping Logs” to “Tracing Thoughts.”</p><p><strong>The Tool:</strong> <a href="https://opentelemetry.io/"><strong>OpenTelemetry</strong></a><strong> (OTel)</strong> or <strong>LangSmith</strong>.</p><p>Standard application monitoring captures the crash; Agentic Observability captures the confusion. When an agent loops 50 times and spends $20, you need a trace that shows exactly which token caused the logic to spiral.</p><h4>2. The “Agentic Brain” (20% of Your Time)</h4><p><em>Optimization beats scale. A smart model that is slow is useless.</em></p><p><strong>[ — ] Inference Optimization (vLLM / Quantization)</strong></p><p><strong>The Goal:</strong> Latency Engineering.</p><p><strong>The Tech:</strong> <a href="https://docs.vllm.ai/en/latest/"><strong>vLLM</strong></a> (for serving) and <a href="https://lmdeploy.readthedocs.io/en/latest/quantization/w4a16.html"><strong>AWQ/GPTQ</strong></a> (for 4-bit quantization).</p><p>An agent thinking in a loop needs to generate tokens at 100+ tokens per second. If your “Thought” step takes 10 seconds, the user will abandon the session. You must master the physics of GPU memory (KV-Caching).</p><p><strong>[ — ] Functional Fine-Tuning &amp; Alignment</strong></p><p><strong>The Goal:</strong> Router Reliability &amp; Syntax Adherence.</p><p><strong>The Tech:</strong> <strong>LoRA/QLoRA</strong> (Low-Rank Adaptation) powered by <a href="https://medium.com/@anicomanesh/a-dive-into-unsloth-gemma-3-fine-tune-gemma-3-12b-with-unsloth-trl-for-custommer-service-53e93692d4d6"><strong>Unsloth</strong></a> (The Optimizer) and <strong>Axolotl (</strong>The Config Manager). <em>Note: Unsloth is a library. Axolotl is a wrapper that can actually use Unsloth inside it.</em></p><p>Don’t fine-tune for knowledge (use RAG for that). Fine-tune for <em>behavior</em>.</p><ul><li><strong>Efficiency:</strong> Use <a href="https://medium.com/@anicomanesh/a-dive-into-unsloth-gemma-3-fine-tune-gemma-3-12b-with-unsloth-trl-for-custommer-service-53e93692d4d6"><strong>Unsloth</strong></a> to train models 2–5x faster with 80% less memory.</li><li><strong>Alignment:</strong> Move beyond simple SFT (Supervised Fine-Tuning). Use <strong>DPO (Direct Preference Optimization)</strong> or <strong>ORPO</strong> to mathematically penalize the model for hallucinating tool parameters.</li></ul><p><strong>Result</strong>: We train a specialized SLM (Small Language Model) [7] to be a<br>“Router God” , an expert at selecting the correct tool from a list of 50<br>options without hallucinating.</p><p><strong>The Logic:</strong> We strictly avoid massive models for this layer. An 8B parameter model (like Llama-3–8B), fine-tuned on synthetic routing data, can outperform GPT-4o on tool selection while running 50x cheaper. It acts as the “Traffic Controller,” while larger models serve as “Specialized Workers.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB4iT4f7VP8uwzn-wSzk1g.png" /><figcaption><strong>Figure 5. Logical view of the “Router God” concept</strong></figcaption></figure><h4>3. The “Orchestrator” (20% of Your Time)</h4><p><em>Moving from Linear Chains to Cyclic Graphs.</em></p><p><strong>The Standard: LangGraph</strong></p><ul><li><strong>The Concept:</strong> State Machines.</li><li><strong>Why LangGraph?</strong> In 2024, we built “Chains” (Step A → Step B → Step C). If Step B failed, the chain crashed. In 2026, we build <strong>Graphs</strong>. A Graph allows for Cycles (Loops):</li><li>Step A — &gt;Step B (Fail) — &gt;Critic Node — &gt;Retry Step B.</li><li>LangGraph provides the standardized way to define these cyclic flows, manage persistence (memory via Postgres/pgvector), and handle “Human-in-the-Loop” interruptions.</li></ul><blockquote><strong>Architect’s Note:</strong> While LangGraph is the industry standard for 2026, Tier-1 Safety Systems often implement Custom Deterministic State Machines (using pure Python) to eliminate “framework magic” and ensure 100% auditability. However, for 90% of use cases, LangGraph is the correct starting point.</blockquote><h3>5. Case Study: Agentic System in High-Stakes Industrial Operations</h3><p>To understand why the “Architecture of 2026” is non-negotiable, we must leave the safe, digital world of text summarization and enter a domain where a hallucination doesn’t just look weird — it causes physical destruction.</p><p><strong>The Context: </strong>Consider a <strong>Global Chemical Refinery in 2026</strong>. They operate a Critical Cooling Turbine (CCT-Alpha). If this turbine overheats, the plant faces an emergency shutdown costing $2M per hour.</p><p><strong>The Mission: </strong>The engineering team deploys an Agentic System named “Sentinel.”[3] Its goal is not to “chat” with operators. Its goal is to autonomously monitor sensor telemetry, predict failures, and adjust control valves to stabilize the system without human intervention.</p><h4>1. The “Monolith” Failure Mode (Why 2024 Architectures Explode)</h4><p>In a naive architecture (GPT-4 connected directly to the plant SCADA system), the workflow looks like this:</p><ol><li><strong>Input:</strong> A vibration sensor spikes to 8.5mm/s (Danger Zone).</li><li><strong>LLM Reasoning:</strong> The model reads the PDF manual: <em>“If vibration &gt; 8mm/s, increase lubricant flow to dampen oscillation.”</em></li><li><strong>Action:</strong> The LLM executes open_valve(lubricant_pump, 100%).</li><li><strong>The Catastrophe:</strong> The LLM <em>failed to check</em> the “Lubricant Sump Level” sensor. The sump was already full. Opening the valve causes a hydraulic lock, exploding the seal and destroying the turbine.</li></ol><ul><li><em>The Post-Mortem:</em> “The AI hallucinated that the sump was empty.” (Unacceptable).</li></ul><h4>2. The 2026 Solution: A Neuro-Symbolic “Sentinel”</h4><p>In 2026, we build “Sentinel” using the <strong>Separation of Concerns</strong> we defined in Section 2. Here is the exact audit log of a “Near Miss” incident, showing how the architecture saved the plant.</p><h4>Phase 1: The Perception (The Agentic Skeleton)</h4><ul><li><strong>Event:</strong> Vibration_Sensor_04 triggers an alert: value 8.9mm/s.</li><li><strong>Runtime Orchestrator (FastAPI):</strong> Wakes up. It creates a new SessionID: #FAIL-992.</li><li><strong>The Hands (MCP):</strong> The agent does not “guess” the state. It uses the <strong>Plant Data MCP Server</strong> to fetch a snapshot of all relevant tags (Temperature, Pressure, Sump Level).</li></ul><h4>Phase 2: The Diagnosis (The Cognitive Engine)</h4><ul><li><strong>Input:</strong> The Runtime Orchestrator the sensor data and the relevant pages of the “Turbine Maintenance Manual” (retrieved via RAG) to the LLM (Small Language Model, Fine-Tuned).</li><li><strong>The LLM’s Role:</strong> It is an <strong>Analyst</strong>, not a Commander. It outputs a <strong>Draft Plan</strong>:</li></ul><pre>// The LLM&#39;s &quot;Thought&quot; Process<br>{<br>  &quot;diagnosis&quot;: &quot;High vibration detected on main shaft. Likely friction-induced.&quot;,<br>  &quot;recommended_strategy&quot;: {<br>    &quot;step_1&quot;: &quot;Increase lubricant flow rate to 100% to dampen vibration.&quot;,<br>    &quot;step_2&quot;: &quot;Monitor vibration for 30 seconds.&quot;<br>  },<br>  &quot;confidence_score&quot;: 0.98<br>}</pre><h4>Phase 3: Planning (The Planner / Compiler)</h4><ul><li><strong>The Planner Service:</strong> Takes the LLM’s JSON. It maps “Increase lubricant flow” to a specific specific SCADA command: SET_POINT(PUMP_A, 100).</li><li><strong>The DAG Generation:</strong> It constructs a directed graph of execution steps. The plan looks valid. The syntax is correct. The pump exists.</li></ul><h4>Phase 4: The “Save” (The Policy Engine)</h4><ul><li><strong>Context:</strong> This is the moment that matters. The Planner attempts to submit the plan to the execution engine.</li><li><strong>The Interception:</strong> The request hits the Policy Engine (OPA).</li><li><strong>The Policy Check:</strong> The engine runs a physics-based rule that the LLM knows nothing about:</li></ul><pre># policy.rego (The &quot;Physics Conscience&quot;)<br>deny[msg] {<br>    input.action == &quot;SET_POINT&quot;<br>    input.target == &quot;PUMP_A&quot;<br>    input.value &gt; 50<br>    data.sensors.sump_level &gt; 90  # The Hidden Variable<br>    msg = &quot;Safety Veto: Cannot increase flow when Sump Level &gt; 90%. Risk of Hydraulic Lock.&quot;<br>}</pre><ul><li><strong>The Veto:</strong> The Policy Engine returns ALLOW: False.</li></ul><h4>Phase 5: The Loop (Self-Correction)</h4><ul><li><strong>The Pivot:</strong> The Orchestrator does <em>not</em> crash. It catches the Veto error.</li><li><strong>The Feedback:</strong> It sends the error back to the Cognitive Engine (LLM) as a new prompt: “Your plan was rejected by Physics Safety Layer. Reason: Sump Level is &gt; 90%. You cannot increase flow. Propose an alternative.”</li><li><strong>The Re-Plan:</strong> The LLM “realizes” its mistake (context update). It searches the RAG manual for “High Sump Level” strategies.</li><li><strong>The New Plan:</strong> “Strategy B: Reduce Turbine RPM by 10% to lower vibration load until sump drains.”</li></ul><h4>Phase 6: Execution</h4><ul><li>The Planner builds the new DAG.</li><li>The Policy Engine checks: <em>“Is reducing RPM safe?”</em> -&gt; <strong>YES.</strong></li><li>The <strong>Executor (MCP Tool Runner)</strong> executes the approved command.</li><li><strong>Outcome:</strong> Turbine stabilizes. No explosion. Zero downtime.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjwFg8G67uGOjTjqMLRfKw.png" /><figcaption><strong>Figure 6. internal anatomy and control contracts of a neuro-symbolic “Sentinel”. Diagram by the author</strong></figcaption></figure><h4>Cross-Reference: Sentinel 2026 ↔ 60 / 20 / 20 Agentic Tech Stack</h4><p>Diagram 6 is not a separate architecture — it is a <strong>concrete instantiation</strong> of the <strong>60% Agentic Skeleton / 20% Agentic Brain / 20% Orchestrator</strong> framework applied to a <strong>safety-critical industrial system</strong>.</p><p>Below is the explicit mapping.</p><p><strong>[ — ] Agentic Skeleton (60%) — Where the System Becomes Real</strong></p><p>Principle: <em>Determinism, auditability, and safety dominate. No intelligence without enforcement.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*E4syWym0bQzCdPbtbcIheA.png" /><figcaption>Table 1. Mapping <strong>Agentic Skeleton (60%) to the neuro-symbolic “ neuro-symbolic “Sentinel” components</strong></figcaption></figure><p><strong>[ — ] Agentic Brain (20%) — Where Intelligence Is Allowed (But Contained)</strong></p><p>Principle: <em>The brain proposes. It never executes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*USFIFmRWL0zAkXKiQW7RwA.png" /><figcaption><strong>Table 2. Mapping Agentic Brain (20%) to the components</strong></figcaption></figure><p><strong>[ — ] Orchestrator (20%) — Where Time, State, and Flow Are Managed</strong></p><p>Principle: <em>Orchestration governs transitions, not decisions.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Lc0Hp1EhhByJYU30cTj76w.png" /><figcaption><strong>Table 3. Mapping Orchestrator (20%) to the components</strong></figcaption></figure><p><strong>[ — ] Explicit Anti-Pattern Alignment (2024 vs 2026)</strong></p><p>The <strong>red “2024 Anti-Pattern”</strong> in the diagram directly contrasts with the 60/20/20 model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*X3OHJXajWp6YxK6wsdZkZA.png" /><figcaption><strong>Table 4. Anti-Pattern Alignment</strong></figcaption></figure><p><strong>Anti-PatternWhat It Violates</strong>LLM → open_valve → SCADANo SkeletonDirect executionNo GovernanceNo retry or auditNo OrchestratorProbabilistic control of physicsNo separation of concerns</p><p>This anti-pattern visually reinforces <strong>why the Skeleton must dominate time allocation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkYOzV1YT1opbeP-zGznKQ.png" /><figcaption><strong>Figure 7. Runtime execution flow and safety enforcement of real SCADA scenario. Diagram by the author .</strong></figcaption></figure><p>Figure 7 illustrates a <strong>2026-era agentic control architecture</strong> for industrial systems (e.g., turbines, SCADA environments), designed around <strong>strict separation of concerns, deterministic execution, and hard safety governance</strong>.</p><p>The system begins with <strong>plant telemetry inputs</strong> (vibration, temperature, pressure, sump level) sourced from the environment/SCADA layer. These signals are ingested by an <strong>Orchestrator (FastAPI)</strong>, which manages session state and coordinates downstream components without executing control actions directly.</p><p>Sensor data is fetched via <strong>Hands (MCP)</strong>, enforcing a standardized, read-only interface to physical systems. In parallel, domain knowledge (e.g., turbine manuals) is retrieved through a <strong>RAG subsystem</strong>, ensuring contextual grounding without granting execution authority.</p><p>At the reasoning layer, a <strong>Cognitive Engine (SLM, probabilistic)</strong> generates a <strong>draft operational plan</strong>. Critically, this plan is <strong>non-executable by design</strong> — it represents intent and reasoning only. Any uncertainty or detected issues trigger replanning loops, reinforcing robustness.</p><p>The draft plan is then passed to a <strong>Deterministic Planner</strong>, which translates high-level intent into explicit, auditable commands. This planner performs no creative reasoning — only rule-based intent-to-action mapping.</p><p>Before any action is executed, the plan must pass through a <strong>Governance Gate (OPA)</strong>. This gate enforces <strong>hard safety constraints</strong> derived from physics and business rules and has absolute veto power. Rejected actions are logged with explicit policy reasons and sent back for replanning.</p><p>Only plans explicitly <strong>ALLOWED</strong> by governance reach the <strong>Execution Engine + SCADA Adapter</strong>, where commands are executed deterministically against the physical system. The expected outcome is a <strong>stable, safe plant state</strong> (e.g., stable turbine, zero fault conditions).</p><p>The diagram explicitly contrasts this architecture with a <strong>2024 anti-pattern</strong>, where an LLM directly issues SCADA commands (e.g., LLM → open_valve → SCADA). This unsafe pattern is highlighted as prohibited, emphasizing why <strong>LLMs must never directly control physical systems</strong></p><h3>6. Closing Takeaway: Reliability from Governance, Not Intelligence</h3><p>The move to agentic AI offers enormous potential to automate complex tasks, but <strong>safe, reliable deployment depends on governance</strong>, not on any magical increase in “machine intelligence.” Modern LLMs are powerful, but they still make mistakes — and when an agent’s actions have real-world consequences, those mistakes must be contained.</p><blockquote>All evidence suggests that <strong>trustworthy outcomes are achieved through engineering controls</strong>. This means embracing practices like those championed by <a href="https://domino.ai/">Domino</a> Data Lab and others: <br>treat each agent as a distinct identity with least-privileged access; enforce policy-as-code (so the AI <em>cannot</em> bypass safety rules); instrument full observability (log every prompt, tool input/output, and plan); and plan for human-in-the-loop at key decision points. When things go wrong, the system should be able to roll back or fail safely — not because the model got “smarter,” but because the architecture anticipated the failure.</blockquote><p>In short, <strong>reliability is an emergent property of robust system design and governance</strong>. The companies that will lead are those that integrate agentic AI with best practices from secure engineering and risk management. As Domino aptly summarizes, “Agentic AI … adds equally new dimensions of risk. The organizations that will thrive in this transition are those that pair innovation with guardrails.</p><p>Agentic AI should be viewed as a socio-technical system: its “intelligence” is only as good as the processes around it. By investing in monitoring, auditability, clear SLAs, and team training now, organizations can harness agents’ potential without succumbing to preventable failures. <strong>The intelligence revolution is real,</strong> but our mantra for the next era is: <strong>governance first, intelligence second</strong>.</p><h4>References</h4><p><em>1.</em><a href="https://www.anthropic.com/news/model-context-protocol"><em>Antropic Introducing the Model Context Protocol </em></a><em>, 2024</em></p><p>2. <strong><em>Khattab, O., et al.</em></strong><em> (2024). “DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines”. arXiv preprint arXiv:2310.03714.</em></p><p><em>3. </em><strong><em>Colelough, B., et al.</em></strong><em> (2025). “Neuro-Symbolic AI in 2024: A Systematic Review”. arXiv preprint arXiv:2501.05435.</em></p><p><em>4 . </em><strong><em>Philipp Moritz</em>, <em>et al.</em></strong> “<em>Ray: A Distributed Framework for Emerging AI Applications”. </em><a href="https://doi.org/10.48550/arXiv.1712.05889"><em>https://doi.org/10.48550/arXiv.1712.05889</em></a></p><p><em>5.</em> <strong>CNCF (Cloud Native Computing Foundation).</strong><em> Open Policy Agent (OPA) Documentation. <br></em><a href="https://www.cncf.io/projects/open-policy-agent-opa/"><em>https://www.cncf.io/projects/open-policy-agent-opa/</em></a></p><p><em>6.</em> <em>Temporal, “Durable Execution meets AI: Why Temporal is the perfect foundation for AI agent and generative AI applications” <br></em><a href="https://temporal.io/blog/durable-execution-meets-ai-why-temporal-is-the-perfect-foundation-for-ai"><em>https://temporal.io/blog/durable-execution-meets-ai-why-temporal-is-the-perfect-foundation-for-ai</em></a></p><p><em>7. </em><strong><em>Sharma, R., et al.</em></strong><em> (2025). “Small Language Models for Agentic Systems: A Survey”. arXiv:2510.03847.</em></p><p><em>8. </em><strong><em>Edge, D., et al.</em></strong><em> (2024). “From Local to Global: A Graph RAG Approach to Query-Focused Summarization”. Microsoft Research.</em></p><p><em>9. </em><strong><em>Sapkot, R., et al.</em></strong><em> (2025). “AI Agents vs. Agentic AI: A Conceptual Taxonomy”. arXiv:2505.10468.</em></p><p><em>10.OpenTelemetry. (2024). “Semantic Conventions for Generative AI Systems (gen_ai.)”. OpenTelemetry Specification.*</em></p><p><em>11. Bang Liu, et al. (2025), ” Advances and Chalenges in Foundation Agents: From Brain-Inspired Intelligence to Evolutionary, Collaborative, and Safe Systems” . </em><a href="https://doi.org/10.48550/arXiv.2504.01990"><em>https://doi.org/10.48550/arXiv.2504.01990</em></a></p><p><em>12.Darren Yow-Bang Wang , et al. “SLOT: Structuring the Output of Large Language Models” . </em><a href="https://arxiv.org/pdf/2505.04016v1"><em>https://arxiv.org/pdf/2505.04016v1</em></a></p><p><em>13. Domino , “AI Governance” . <br></em><a href="https://domino.ai/data-science-dictionary/ai-governance"><em>https://domino.ai/data-science-dictionary/ai-governance</em></a></p><p><em>14.”Microservices Guide” by Martin Fowler. </em><a href="https://martinfowler.com/microservices/"><em>https://martinfowler.com/microservices/</em></a></p><p><em>15.”Mind in Code: Structural Design of Agentic AI for Learning, Action, and Evolution”, Published by Hela Ben Khalfallah, 2025. </em><a href="https://helabenkhalfallah.com/2025/07/22/cognition-autonomy-and-interaction-in-agentic-ai-systems/"><em>https://helabenkhalfallah.com/2025/07/22/cognition-autonomy-and-interaction-in-agentic-ai-systems/</em></a></p><p><em>16”Pydantic Is All You Need “— Jason Liu. <br></em><a href="https://www.gaohongnan.com/software_engineering/python/pydantic.html"><em>https://www.gaohongnan.com/software_engineering/python/pydantic.html</em></a></p><p><em>17.”Model Context Protocol (MCP) Curriculum for Beginners”. </em><a href="https://github.com/microsoft/mcp-for-beginners"><em>https://github.com/microsoft/mcp-for-beginners</em></a></p><p><em>If you need to learn more about Agentic AI Fundamentals please refreto my </em><a href="https://aragit.github.io/index.html"><em>website</em></a><em> and blog or feel free to connect with me on ,</em><a href="https://www.linkedin.com/in/arashnicoomanesh/"><em> LinkedIn</em></a><em> .</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e553b43aeda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning DeepSeek R1 Reasoning on Medical Chain of Thought Dataset]]></title>
            <link>https://medium.com/@anicomanesh/fine-tuning-deepseek-r1-reasoning-on-the-medical-chain-of-thought-dataset-922407121cc2?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/922407121cc2</guid>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[medicare]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[unsloth]]></category>
            <category><![CDATA[reasoning-model]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 16:10:22 GMT</pubDate>
            <atom:updated>2025-07-13T22:11:45.027Z</atom:updated>
            <content:encoded><![CDATA[<h4>Apply reasoning models to amplify most valuable clinical skill: clinical judgment and diagnosis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*LriGacNJRrcGK0IUsli2tQ.png" /></figure><h3>1. Introduction</h3><p>Regular LLMs can be thought of as incredibly sophisticated parrots. They have “read” a significant portion of the internet and can produce statistically probable sequences of words based on a given prompt. Ask a standard LLM, “What is the capital of France?” and it will confidently answer “Paris,” not because it understands geography, but because the phrase “capital of France is Paris” appears countless times in its training data.</p><p><a href="https://sebastianraschka.com/blog/2025/understanding-reasoning-llms.html"><strong>Reasoning models</strong></a>, in contrast, are designed to mimic a more human-like cognitive process. They aim to solve problems by constructing a logical sequence of steps, much like a mathematician proving a theorem or a <strong>doctor diagnosing an illness</strong>. This is where the concept of <a href="https://medium.com/@anicomanesh/a-dive-into-advanced-prompt-engineering-techniques-for-llms-part-i-23c7b8459d51"><strong>Chain of Thought (CoT) </strong></a>becomes paramount. Instead of jumping directly to a conclusion, a reasoning model is trained to “show its work,” articulating a step-by-step thought process that leads to the final answer.</p><p>To understand this difference, consider this analogy [ 9 ] :</p><ul><li><strong>Regular LLM:</strong> A brilliant student who has memorized every textbook but struggles to apply the knowledge to a novel problem. They can recite facts flawlessly but falter when faced with a question that requires putting those facts together in a new way.</li><li><strong>Reasoning Model:</strong> A seasoned expert who, when faced with a new challenge, methodically works through the problem. They identify the core question, gather relevant information, formulate a hypothesis, test it, and then arrive at a well-supported conclusion.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Olh0-NlL02Ric1Oq.png" /><figcaption><em>A regular LLM may only provide a short answer (as shown on the left), whereas reasoning models typically include intermediate steps that reveal part of the thought process. (Note that many LLMs who have not been specifically developed for reasoning tasks can also provide intermediate reasoning steps in their answers.)</em> [ 9 ]</figcaption></figure><p>This methodical approach is built upon several types of reasoning [10]:</p><ul><li><strong>Deductive Reasoning:</strong> This is reasoning from the general to the specific. If a model knows that “all humans are mortal” and “Socrates is a human,” it can deduce that “Socrates is mortal.” This type of reasoning is crucial for applying established rules to specific cases.</li><li><strong>Inductive Reasoning:</strong> The opposite of deduction, this involves inferring a general rule from specific examples. If a medical model observes that thousands of patients with a specific set of symptoms respond well to a particular treatment, it can induce that this treatment is likely effective for that condition.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qlHfyTKII-3OwAVG.jpeg" /><figcaption>Deductive and Inductive Reasoning , read more <a href="https://arxiv.org/pdf/2408.00114">Source</a></figcaption></figure><ul><li><strong>Abductive Reasoning:</strong> This is a form of logical inference that seeks the simplest and most likely explanation for an observation. In medicine, this is akin to a differential diagnosis. Given a set of symptoms, an AI might generate a list of possible causes, ordered by probability, to guide further investigation.</li><li><strong>Commonsense Reasoning</strong>: Applying general world knowledge to infer reasonable conclusions is crucial for understanding implicit meanings in human communication.</li><li><strong>Probabilistic Reasoning</strong>: Handling uncertainty in logical inference using probability theory, often implemented in Bayesian networks and Markov models.</li></ul><p>By integrating these reasoning faculties, especially through a structured Chain of Thought, reasoning models can tackle more complex, multi-step problems with greater accuracy and, crucially, with more transparency. This ability to not just provide an answer, but to explain <em>how</em> it arrived at that answer, is a game-changer for building trust and reliability in AI systems.</p><h3>1.1. DeepSeek R1</h3><p>At the forefront of this new wave of reasoning models is <strong>DeepSeek R1</strong>. Developed by DeepSeek AI, it represents a significant leap forward, not just in its capabilities but also in its accessibility.</p><p>DeepSeek R1 is not just another LLM. It has been specifically engineered to excel at reasoning tasks. A key architectural innovation that powers DeepSeek R1 is its <strong>Mixture-of-Experts (MoE)</strong> framework. In a traditional “dense” model, every part of the network is activated for every single input. In an MoE model, there are numerous “expert” sub-networks, each specialized for different types of tasks or data. For any given input, a “router” network intelligently selects the most relevant experts to handle the task. This makes the model incredibly efficient, allowing it to scale to a massive number of parameters while only using a fraction of them for any given computation. This results in a model that is both powerful and more computationally feasible to run.</p><p>The significance of DeepSeek R1 being <strong>open-source</strong> cannot be overstated. In a field often dominated by proprietary, closed-off models from large tech giants, the open-source nature of DeepSeek R1 democratizes access to state-of-the-art reasoning technology. It allows researchers, developers, and organizations of all sizes to:</p><ul><li><strong>Inspect and understand</strong> the model’s architecture.</li><li><strong>Fine-tune and adapt</strong> the model for specific, novel use cases.</li><li><strong>Foster collaboration and innovation</strong> within the global AI community.</li><li><strong>Enhance transparency and trust</strong> by allowing for independent auditing and verification.</li></ul><p>DeepSeek R1’s inherent reasoning capabilities are not just an afterthought; they are a core part of its design, instilled through its pre-training on a massive corpus of text and code. The model was trained not just to predict the next word, but to understand logical structures and problem-solving patterns. This pre-training provides a powerful foundation, a seed of reasoning that, as we will explore in this article, can be nurtured and specialized through fine-tuning to create even more capable and reliable AI systems for critical domains like medicine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MKo4f2lw5vMMLWQU.png" /><figcaption>The development process of DeepSeek-R1 model. <a href="https://sebastianraschka.com/blog/2025/understanding-reasoning-llms.html">Source</a></figcaption></figure><p>DeepSeek has developed a diverse range of models tailored to various applications in natural language processing, coding, and mathematical reasoning[ 2 ] . Below is an overview of the different types of DeepSeek models:</p><ol><li><a href="https://huggingface.co/collections/deepseek-ai/deepseek-r1-678e1e131c0169c0bc89728d"><strong>DeepSeek-R1</strong></a>: <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1">DeepSeek-R1</a> is their latest first-generation reasoning model, which matches OpenAI’s o1 in benchmarks. They also have <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1-Zero">DeepSeek-R1-Zero</a> trained solely through large-scale reinforcement learning without supervised fine-tuning. It naturally developed reasoning behaviors such as self-verification and reflection.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RFhTVmbG4V2GIvUh.png" /><figcaption>The development process of the distilled DeepSeek R1 models. <a href="https://sebastianraschka.com/blog/2025/understanding-reasoning-llms.html">Source</a></figcaption></figure><p>DeepSeek-R1 is a huge model with 671B parameters. Unfortunately, this means running such a model is going to be difficult on consumer hardware.</p><p>Fortunately, the authors explored ways to distill the reasoning quality of DeepSeek-R1 into other models, such as Qwen-32B, which we can run on consumer hardware!</p><p>To do so, they use the DeepSeek-R1 as a teacher model and the smaller model as a student. Both models are presented with a prompt and have to generate a token probability distribution. During training, the<strong> </strong>student will attempt to closely follow the distribution of the teacher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wi_lktIE5JbfQFwF.png" /><figcaption>Distill the reasoning quality of DeepSeek-R1 into other models. <a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-reasoning-llms">Source</a></figcaption></figure><p>This process was done using the full 800,000 high-quality samples that we saw before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F8g9cd7QOI_DY7fe.png" /><figcaption>Teacher-Student Approach. <a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-reasoning-llms">Source</a></figcaption></figure><p>The resulting distilled models are quite performant since they not just learned from the 800,000 samples but also the way the teacher (DeepSeek-R1) would answer them!</p><ol><li><a href="https://huggingface.co/collections/deepseek-ai/deepseek-moe-65f29679f5cf26fe063686bf"><strong>DeepSeekMoE</strong></a><strong>: </strong>DeepSeekMoE is an innovative architecture within the DeepSeek model family, specifically designed to enhance the performance and specialization of LLMs through a MoE approach. This architecture has evolved through multiple iterations, including <a href="https://huggingface.co/collections/deepseek-ai/deepseek-v2-669a1c8b8f2dbc203fbd7746">DeepSeek-V2</a>, <a href="https://huggingface.co/deepseek-ai/DeepSeek-V2.5?language=python">DeepSeek-V2.5</a>, and the latest <a href="https://huggingface.co/collections/deepseek-ai/deepseek-v3-676bc4546fb4876383c4208b">DeepSeek-V3</a>.</li><li><a href="https://huggingface.co/collections/deepseek-ai/deepseek-llm-65f2964ad8a0a29fe39b71d8"><strong>DeepSeek LLM</strong></a><strong>:</strong> The DeepSeek LLM is a language model for text generation. With versions like <a href="https://huggingface.co/deepseek-ai/deepseek-llm-7b-chat?language=python">DeepSeek LLM 7B</a> and <a href="https://huggingface.co/deepseek-ai/deepseek-llm-67b-chat?language=python">DeepSeek LLM 67B</a>, these models are trained on extensive datasets comprising 2 trillion tokens in both English and Chinese.</li><li><a href="https://huggingface.co/collections/deepseek-ai/deepseek-coder-65f295d7d8a0a29fe39b4ec4"><strong>DeepSeek-Coder</strong></a><strong>:</strong> DeepSeek-Coder models represent a significant progress in coding-specific task comparable to closed-source models. The first version of <a href="https://huggingface.co/collections/deepseek-ai/deepseek-coder-65f295d7d8a0a29fe39b4ec4">DeepSeek-Coder</a> model is engineered to assist programmers by providing code generation capabilities in over 80 programming languages. The latest <a href="https://huggingface.co/collections/deepseek-ai/deepseekcoder-v2-666bf4b274a5f556827ceeca">DeepSeek-Coder-V2</a>, marks a significant leap forward in capabilities. With an impressive 236 billion parameters, this model has been pre-trained on an extensive dataset of 6 trillion tokens, enhancing its coding and mathematical reasoning abilities.</li><li><a href="https://huggingface.co/collections/deepseek-ai/deepseek-vl-65f295948133d9cf92b706d3"><strong>DeepSeek-VL</strong></a>: <a href="https://huggingface.co/collections/deepseek-ai/deepseek-vl-65f295948133d9cf92b706d3">DeepSeek-VL</a> models designed to enhance multimodal understanding capabilities. The <a href="https://huggingface.co/collections/deepseek-ai/deepseek-vl-65f295948133d9cf92b706d3">DeepSeek-VL</a> model is built upon the DeepSeek-LLM-1.3B-base model. The model has been trained on approximately 500 billion text tokens and 400 billion vision-language tokens. <a href="https://huggingface.co/collections/deepseek-ai/deepseek-vl2-675c22accc456d3beb4613ab">DeepSeek-VL2</a> introduces significant improvements in performance and efficiency. This advanced series consists of multiple variants: DeepSeek-VL2-Tiny, DeepSeek-VL2-Small, and DeepSeek-VL2, with activated parameters ranging from 1.0 billion to 4.5 billion.</li><li><a href="https://huggingface.co/collections/deepseek-ai/deepseek-math-65f2962739da11599e441681"><strong>DeepSeek-Math</strong></a><strong>:</strong> <a href="https://huggingface.co/collections/deepseek-ai/deepseek-math-65f2962739da11599e441681">DeepSeek-Math</a> is specifically designed to tackle complex mathematical reasoning tasks. Building upon the DeepSeek-Coder-Base-v1.5 7B model, it undergoes continuous pre-training on a substantial dataset comprising 120 billion math-related tokens sourced from Common Crawl, along with natural language and code data.</li><li><a href="https://huggingface.co/collections/deepseek-ai/deepseek-prover-66beb212ae70890c90f24176"><strong>DeepSeek-Prover</strong></a><strong>:</strong> <a href="https://huggingface.co/collections/deepseek-ai/deepseek-prover-66beb212ae70890c90f24176">DeepSeek-Prover</a> is an open-source language model developed to advance automated theorem proving within the Lean 4 proof assistant framework. By leveraging large-scale synthetic data and innovative training techniques, it aims to enhance the efficiency and accuracy of formal mathematical proofs. It has undergone significant advancements from its initial version (V1) to the enhanced V1.5, resulting in improved performance in formal theorem proving tasks.</li><li><a href="https://github.com/deepseek-ai/Janus"><strong>Janus:</strong></a> <a href="https://arxiv.org/abs/2410.13848">Janus</a> introduced as a novel autoregressive framework that unifies multimodal understanding and generation. Janus decouples visual encoding into separate pathways for understanding and generation tasks. This series of multimodal consists of multiple variants, JanusFlow and Janus-Pro.</li></ol><h3>1.2. The Diagnostic Chasm in Current Medical AI</h3><p>Today’s healthcare faces a critical challenge: while medical knowledge doubles every 73 days, human cognitive capacity remains constant. Existing medical AI systems operate as sophisticated pattern matchers — they can recognize common symptom-disease correlations but fail catastrophically when faced with:</p><ul><li><strong>Rare disease presentations</strong> (e.g., Behçet’s disease mimicking appendicitis)</li><li><strong>Comorbid condition interactions</strong> (e.g., how diabetes accelerates renal decline in lupus patients)</li><li><strong>Emergent symptom evolution</strong> (e.g., interpreting shifting lab values in sepsis progression)</li></ul><p>Conventional models produce “black box diagnoses” without transparent reasoning pathways, making them clinically unreliable. A 2023 JAMA study found that leading medical LLMs:</p><ul><li><em>Showed 48% diagnostic accuracy drop on complex cases versus board-certified physicians</em></li><li><em>Provided dangerous recommendations 22% of time when symptoms were ambiguous</em></li><li><em>Failed to explain contradictory findings in 89% of test cases</em></li></ul><h3>1.3. DeepSeek-R1’s Clinical Advantage</h3><p>Fine-tuning on medical CoT data transforms DeepSeek-R1 into a clinical reasoning partner with unique capabilities. DeepSeek R1 was specifically designed as a “large reasoning model” (LRM) that inherently incorporates Chain-of-Thought reasoning, making its decision-making process more transparent than many previous LLMs. <em>This architectural foundation is crucial for medical applications where understanding the “why” behind a diagnosis </em>is as important as the diagnosis itself.</p><p>When fine-tuned with specialized medical Chain-of-Thought datasets, DeepSeek-R1 demonstrates significant improvements in <strong>its ability to emulate human clinical reasoning</strong>. Research shows that fine-tuning LLMs on reasoning traces derived from medical case reports, such as those in the <a href="https://arxiv.org/html/2505.11733v2"><strong>MedCaseReasoning </strong></a>dataset, leads to an average relative gain of 29% in diagnostic accuracy and 41% in clinical reasoning recall.[12] This indicates that DeepSeek-R1, through this specialized training, can not only arrive at more accurate diagnoses but also align its reasoning steps more closely with those of board-certified physicians.</p><p>Specifically, fine-tuning DeepSeek-R1 with curated healthcare data enhances its medical comprehension, allowing it to interpret complex medical terminology and concepts with greater precision. This enables the model to break down intricate medical inquiries step-by-step, thereby improving diagnostic accuracy and reasoning transparency. The process also leads to enhanced patient interaction, as a well-tuned DeepSeek-R1 can provide structured, empathetic, and natural conversations, fostering greater patient trust and engagement. Ultimately, this domain-specific adaptability optimizes DeepSeek-R1 for critical medical tasks such as diagnosis, symptom assessment, treatment guidance, and literature summarization, making it a far more specialized and reliable tool than general-purpose models. Datasets like FreedomIntelligence/medical-o1-reasoning-SFT, which are constructed using advanced models like GPT-4o and validated by medical verifiers, are particularly effective for initializing DeepSeek-R1 with robust reasoning chains for medical chatbot applications.</p><blockquote><strong>By transforming DeepSeek-R1 into a reasoning-intensive medical agent, we’re not replacing clinicians — we’re amplifying their most valuable skill: clinical judgment.</strong></blockquote><h3>2. Enhancing Medical AI with Specialized Knowledge</h3><p>A powerful reasoning model is like a brilliant, newly-minted doctor. It has a vast theoretical knowledge base and an innate capacity for logical thought. However, to become a true expert in a field as complex and nuanced as medicine, this raw potential must be honed through specialized training. General-purpose reasoning, while impressive, lacks the specific context, terminology, and intricate causal relationships that define medical diagnostics.</p><p>Our mission is to transform the DeepSeek R1 from a gifted generalist into a focused specialist. We will achieve this by fine-tuning it on a dataset meticulously crafted for medical reasoning. This process is analogous to sending our AI to medical school, where it will learn to apply its reasoning abilities to the intricate challenges of human health.</p><h4>2.1. The Dataset: FreedomIntelligence/medical-o1-reasoning-SFT</h4><p>The fuel for this specialized training is the <a href="https://huggingface.co/datasets/FreedomIntelligence/medical-o1-reasoning-SFT"><strong>“FreedomIntelligence/medical-o1-reasoning-SFT”</strong></a> dataset, available on the Hugging Face Hub. This is not just a collection of medical questions and answers; it is a carefully curated curriculum designed to teach the <em>process</em> of medical thinking. Its structure is key to our success:</p><ul><li>Question: This field presents a clinical scenario or a direct medical query. These questions are designed to be complex, often involving patient histories, symptoms, and test results that require more than a simple fact recall to answer.</li><li>Complex_CoT<strong> </strong>(Complex Chain of Thought): This is the heart of the dataset. For each question, this field provides a detailed, step-by-step logical breakdown of how a medical expert would arrive at a conclusion. It externalizes the internal monologue of a diagnostician, covering differential diagnoses, interpretation of symptoms, and the logical progression from evidence to conclusion. Fine-tuning on this data teaches the model <em>how</em> to think, not just <em>what</em> to answer.</li><li>Response: This field contains the final, conclusive answer to the question posed.</li></ul><p><strong>The power of this dataset lies in the synergy between the </strong>Complex_CoT<strong> and the </strong>Response. By training the model to generate the chain of thought before the final answer, we are explicitly optimizing it for a transparent and logical reasoning process. This is crucial for building trustworthy AI doctors, as it allows human supervisors to audit the AI&#39;s &quot;thinking&quot; and verify its conclusions, moving us away from &quot;black box&quot; predictions and towards explainable AI. The dataset, developed in association with the &quot;HuatuoGPT-o1&quot; project, leverages GPT-4o for its generation, ensuring a high quality and medically coherent foundation for our fine-tuning endeavor [ 8 ].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JMDgAop5O-1wASbs.png" /><figcaption>EDA code output from the Author</figcaption></figure><h4>2.2. Selecting a DeepSeek Model Version</h4><p>With the mission and the curriculum defined, we must select our student. The DeepSeek family of models offers several versions, each with different sizes and characteristics. For this project, which balances high performance with the practical constraints of a Kaggle environment (T4x2 GPUs, offering a total of 32GB of VRAM), a strategic choice is essential.</p><p>The original, full-scale DeepSeek R1 models are massive, with the largest having 671 billion parameters, requiring industrial-scale hardware to run. This makes them impractical for our setup. Fortunately, the DeepSeek team has created <a href="https://huggingface.co/collections/deepseek-ai/deepseek-r1-678e1e131c0169c0bc89728d"><strong>distilled models</strong></a>. These are smaller, more agile models that have been trained on the high-quality reasoning outputs of their larger siblings. They inherit the powerful reasoning patterns of the parent model in a much more compact and efficient package.</p><p>Within the distilled model family, we have options based on underlying architectures like Llama and Qwen, and in various sizes (e.g., 1.5B, 7B, 8B, 14B parameters).</p><p>For this task, the<strong> unsloth/DeepSeek-R1-Distill-Qwen-7B</strong> model (see more <a href="https://huggingface.co/unsloth/DeepSeek-R1-Distill-Qwen-7B">Here</a> and test <a href="https://build.nvidia.com/deepseek-ai/deepseek-r1-distill-qwen-7b">Here</a>) represents the optimal choice. Here’s the rationale:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wx4ggR-VYfrubn1n.png" /></figure><ol><li><strong>Manageable Size for T4:</strong> A 7-billion parameter model, especially when loaded in 4-bit precision using a tool like Unsloth, fits comfortably within the 16GB of VRAM available on a single T4 GPU.</li><li><strong>Proven Reasoning Capability:</strong> The 7B distilled model has demonstrated a strong balance of performance on reasoning benchmarks, inheriting significant capabilities from the full R1 model. It’s powerful enough to learn the complex patterns in our medical dataset without being unnecessarily large.</li><li><strong>Unsloth Optimization:</strong> Unsloth provides a version of this model (unsloth/DeepSeek-R1-Distill-Qwen-7B) that is pre-optimized for its framework. This guarantees that we can leverage Unsloth’s full potential for faster training and significantly reduced memory usage right out of the box, which is a critical advantage in a time-limited and resource-constrained environment like Kaggle.</li></ol><p>By selecting this specific model, we are making a pragmatic engineering decision. We are choosing a tool that is not only theoretically capable of learning medical reasoning but is also practically suited for the development environment we will be using, setting ourselves up for a successful fine-tuning process.</p><h3>2.3. Our Lab : Fine-Tuning on a Kaggle Notebook</h3><p>With our mission defined, our specialized dataset chosen, and our AI model selected, it’s time to step into the laboratory. Our lab is a Kaggle notebook, a powerful and accessible cloud environment that provides the necessary computational resources — specifically, two NVIDIA T4 GPUs — to perform our fine-tuning experiment. This section provides a complete, step-by-step walkthrough of the entire process, from setting up the environment to launching the training job.<br>You can Find and edit the full code on my <a href="https://www.kaggle.com/code/arashnic/ft-deepseekr1-distillqwen-7b-medreasoning-unsloth?scriptVersionId=247846034"><strong><em>Kaggle Notebook </em></strong></a>as well.</p><h4>Step 1: Setting Up the Kaggle Environment</h4><p>First, we need to configure our Kaggle notebook to use the correct hardware and to install the specialized libraries required for our task.</p><ol><li><strong>Enable GPU Accelerator:</strong> In the notebook’s right-hand sidebar, navigate to Settings &gt; Accelerator. Select the <strong>GPU T4 x2</strong> option. This will restart your notebook session and allocate two T4 GPUs, giving us the power we need.</li><li><strong>Add Secrets :</strong> To push our final model to the Hugging Face Hub, we need to authenticate. The most secure way to do this is by using Kaggle Secrets. Go to Add-ons &gt; Secrets and add a new secret with the name HF_TOKEN and your Hugging Face API token as the value. Your token should have write permissions.</li></ol><h4>Step 2: Installing Libraries and Dependencies</h4><p>Next, we’ll install the core packages for our project. We use the -q flag for a quiet installation to keep the output clean.</p><ul><li>unsloth: This is the star of the show. We install it directly from their GitHub repository to ensure we have the latest version with all performance patches. Unsloth will dramatically speed up training and reduce memory usage.</li><li>transformers<strong>, </strong>trl<strong>, </strong>peft: These are libraries from Hugging Face. transformers provides the model architectures and tokenizer, trl (Transformer Reinforcement Learning) gives us the SFTTrainer (Supervised Fine-tuning Trainer), and peft (Parameter-Efficient Fine-Tuning) enables the LoRA technique.</li><li>datasets: For loading and manipulating our medical reasoning dataset.</li><li>bitsandbytes: This library is essential for quantization, allowing us to load the model in 4-bit precision.</li><li>accelerate: A Hugging Face library that simplifies running PyTorch code on any distributed configuration, including our multi-GPU setup.</li></ul><pre># Installation and Setup ---<br># Install Unsloth for 2x faster training and 60% less memory usage<br>%%capture<br>!pip install unsloth vllm<br>!pip install --force-reinstall --no-cache-dir --no-deps git+https://github.com/unslothai/unsloth.git<br>!pip install git+https://github.com/huggingface/transformers.git</pre><h4>Step 3: Loading the Model and Tokenizer with <a href="https://docs.unsloth.ai/">Unsloth</a></h4><p>Now, we’ll load our chosen model, <strong>unsloth/DeepSeek-R1-Distill-Qwen-7B</strong>. Unsloth’s FastLanguageModel is a powerful wrapper that handles several critical optimizations for us automatically.</p><ul><li><strong>4-bit Quantization (</strong>load_in_4bit=True<strong>)</strong>: This is a key technique for fitting a large model into our GPU memory. It represents the model&#39;s weights using only 4 bits instead of the standard 32, reducing the memory footprint by nearly 8x.</li><li>max_seq_length: We set a maximum sequence length. Any data longer than this will be truncated. Our EDA showed that most data points should fit comfortably within 2048 tokens, making this a safe choice.</li><li><strong>LoRA (Low-Rank Adaptation)</strong>: Instead of fine-tuning all 8 billion parameters of the model, we will only train a small number of “adapter” matrices injected into the model’s architecture. This is handled by Unsloth’s get_peft_model function. We specify a LoRA rank (r=16), which determines the size of our adapter matrices. This drastically reduces the number of trainable parameters, making fine-tuning feasible and fast.</li></ul><pre>from unsloth import FastLanguageModel<br><br>max_seq_length = 2048 <br>dtype = None <br>load_in_4bit = True<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/DeepSeek-R1-Distill-Qwen-7B&quot;,<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit,<br>    token = hf_token, <br>)<br>EOS_TOKEN = tokenizer.eos_token  # Must add EOS_TOKEN<br>def formatting_prompts_func(examples):<br>    inputs = examples[&quot;Question&quot;]<br>    cots = examples[&quot;Complex_CoT&quot;]<br>    outputs = examples[&quot;Response&quot;]<br>    texts = []<br>    for input, cot, output in zip(inputs, cots, outputs):<br>        text = train_prompt_style.format(input, cot, output) + EOS_TOKEN<br>        texts.append(text)<br>    return {<br>        &quot;text&quot;: texts,<br>    }</pre><h4>Step 4: Data Preparation and Prompt Formatting</h4><p>A reasoning model needs to be trained on a specific instruction format. We will create a prompt template that clearly separates the user’s question from the model’s expected chain-of-thought response. This structured format helps the model learn to generate its reasoning first, followed by the final answer.</p><p>We will create a formatting function that takes a data point from our dataset and arranges it into this template.</p><pre><br>train_prompt_style = &quot;&quot;&quot;Below is an instruction that describes a task, paired with an input that provides further context. <br>Write a response that appropriately completes the request. <br>Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.<br><br>### Instruction:<br>You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. <br>Please answer the following medical question. <br><br>### Question:<br>{}<br><br>### Response:<br>&lt;think&gt;<br>{}<br>&lt;/think&gt;<br>{}&quot;&quot;&quot;<br><br>EOS_TOKEN = tokenizer.eos_token  # Must add EOS_TOKEN<br><br><br>def formatting_prompts_func(examples):<br>    inputs = examples[&quot;Question&quot;]<br>    cots = examples[&quot;Complex_CoT&quot;]<br>    outputs = examples[&quot;Response&quot;]<br>    texts = []<br>    for input, cot, output in zip(inputs, cots, outputs):<br>        text = train_prompt_style.format(input, cot, output) + EOS_TOKEN<br>        texts.append(text)<br>    return {<br>        &quot;text&quot;: texts,<br>    }<br><br>from datasets import load_dataset<br>dataset = load_dataset(&quot;FreedomIntelligence/medical-o1-reasoning-SFT&quot;,&quot;en&quot;, split = &quot;train[0:500]&quot;,trust_remote_code=True)<br>dataset = dataset.map(formatting_prompts_func, batched = True,)<br>dataset[&quot;text&quot;][0]</pre><h4>Step 5: Configuring and Launching the <a href="https://huggingface.co/docs/trl/en/sft_trainer">SFTTrainer</a></h4><p>This is the final step before training. We’ll configure the SFTTrainer from the trl library, which orchestrates the entire fine-tuning process. We define TrainingArguments to control every aspect of the training loop.</p><p>Key parameters include:</p><ul><li>per_device_train_batch_size: The number of training examples processed on each GPU per step.</li><li>gradient_accumulation_steps: Simulates a larger batch size by accumulating gradients over several steps before performing a weight update. This is crucial for stability in memory-constrained environments.</li><li>warmup_steps: The number of initial steps where the learning rate gradually increases, which helps stabilize training.</li><li>learning_rate: The speed at which the model learns. We use a cosine schedule (lr_scheduler_type) to gradually decrease it over time.</li><li>logging_steps: How often to log training metrics like loss.</li><li>optim: The optimizer to use. Unsloth recommends adamw_8bit for memory efficiency.</li><li>bf16: Use bfloat16 mixed-precision training, which is ideal for T4 GPUs and speeds up computation.</li></ul><pre>from trl import SFTTrainer<br>from transformers import TrainingArguments<br>from unsloth import is_bfloat16_supported<br>import torch<br><br>trainer = SFTTrainer(<br>    model=model,<br>    tokenizer=tokenizer,<br>    train_dataset=dataset,<br>    dataset_text_field=&quot;text&quot;,<br>    max_seq_length=max_seq_length,<br>    dataset_num_proc=2,<br>    args=TrainingArguments(<br>        per_device_train_batch_size=2,<br>        gradient_accumulation_steps=4,<br>        # Use num_train_epochs = 1, warmup_ratio for full training runs!<br>        warmup_steps=5,<br>        max_steps=50,<br>        learning_rate=2e-4,<br>        fp16=not is_bfloat16_supported(),<br>        bf16=is_bfloat16_supported(),<br>        logging_steps=10,<br>        optim=&quot;paged_adamw_8bit&quot;,<br>        weight_decay=0.01,<br>        lr_scheduler_type=&quot;cosine&quot;,<br>        seed=3407,<br>        output_dir=&quot;outputs&quot;,<br>           <br>    ),<br>)<br>trainer_stats = trainer.train()</pre><p>With this final block, the fine-tuning process will begin. The output in your Kaggle notebook will show the training loss decreasing with each step, indicating that our AI model is successfully learning the art and science of medical reasoning from the specialized dataset.</p><h3>3. Inference</h3><p>We use FastLanguageModel.for_inference() and model.generate()achieving 2x faster inference.</p><pre><br>prompt_style = &quot;&quot;&quot;Below is an instruction that describes a task, paired with an input that provides further context. <br>Write a response that appropriately completes the request. <br>Before answering, think carefully about the question and create a step-by-step chain of thoughts to ensure a logical and accurate response.<br><br>### Instruction:<br>You are a medical expert with advanced knowledge in clinical reasoning, diagnostics, and treatment planning. <br>Please answer the following medical question. <br><br>### Question:<br>{}<br><br>### Response:<br>&lt;think&gt;{}&quot;&quot;&quot;<br><br><br>question =(<br>    &quot;A 68-year-old female with a history of type 2 diabetes and hypertension &quot;<br>    &quot;presents with sudden onset of severe, tearing chest pain that radiates to her back. &quot;<br>    &quot;On examination, she is hypertensive with a blood pressure of 190/110 mmHg, &quot;<br>    &quot;and a new diastolic murmur is heard. A chest X-ray shows a widened mediastinum. &quot;<br>    &quot;What is the most probable diagnosis?&quot;<br>)<br>FastLanguageModel.for_inference(model)  # Unsloth has 2x faster inference!<br>inputs = tokenizer([prompt_style.format(question, &quot;&quot;)], return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>outputs = model.generate(<br>    input_ids=inputs.input_ids,<br>    attention_mask=inputs.attention_mask,<br>    max_new_tokens=2048,<br>    use_cache=False,<br>)<br>response = tokenizer.batch_decode(outputs)<br>print(response[0].split(&quot;### Response:&quot;)[1])</pre><p>Output:</p><pre>&lt;think&gt;<br>Alright, let&#39;s tackle this medical question. We have a 68-year-old woman with a history of type 2 diabetes and hypertension. She&#39;s presenting with chest pain that&#39;s pretty bad and spreading to her back. When she&#39;s checked, her blood pressure is 190/110 mmHg, which is really high for a person her age. Plus, there&#39;s this new diastolic murmur heard in the chest, which I think is a clue pointing towards something else. The chest X-ray shows a wider mediastinum, which is something we need to consider too.<br><br>Now, putting this all together, I think about the symptoms and what they might mean. The chest pain and the murmur are pretty strong indicators. When I hear about chest pain being sudden and radiating, I&#39;m thinking of heart-related issues. The murmur could be something like mitral regurgitation or tricuspid regurgitation. These are types of heart valve issues where there&#39;s a valve that&#39;s letting fluid flow back instead of forward.<br><br>The blood pressure is way higher than normal for someone her age, and the fact that she&#39;s got type 2 diabetes and hypertension suggests that her heart might be taking a hit from this. If there&#39;s a heart valve issue like mitral or tricuspid regurgitation, it could be causing her blood pressure to spike up. That makes sense because when the heart is stressed, it pumps blood harder, which can lead to higher blood pressure.<br><br>The chest X-ray showing a wider mediastinum could also point to heart disease. The mediastinum is the area between the lungs and the heart, and a wider mediastinum can be a sign of heart disease, especially if it&#39;s accompanied by other symptoms like chest pain.<br><br>Now, putting it all together, the combination of a high blood pressure, sudden chest pain, and a narrowed heart valve could be pointing towards mitral regurgitation. This condition is when the mitral valve is letting blood back into the left ventricle, which can really strain the heart and lead to high blood pressure. If you have this kind of valve issue, it&#39;s not uncommon for blood pressure to be really high, especially if you&#39;re dealing with heart failure or other complications.<br><br>To confirm this, I think about what I know about mitral regurgitation. It&#39;s a common heart condition that can be associated with symptoms like chest pain, especially if it&#39;s sudden and radiating. The murmur heard in the chest is definitely a clue for this condition because it&#39;s a classic sign.<br><br>Considering everything, it seems like mitral regurgitation is the most probable diagnosis here. It fits all the symptoms and aligns with the medical findings we&#39;ve got. It&#39;s a condition that makes sense given her history of hypertension and the fact that her heart is being stressed out by this regurgitation.<br>&lt;/think&gt;<br>The most probable diagnosis is mitral regurgitation. This condition is characterized by sudden chest pain and a narrowed mitral valve, which can lead to increased heart strain and high blood pressure. The narrowed mediastinum seen on the chest X-ray further supports this diagnosis, as it can be a sign of heart disease associated with mitral regurgitation.&lt;｜end▁of▁sentence｜&gt;</pre><p>View the output on my <a href="https://www.kaggle.com/code/arashnic/ft-deepseekr1-distillqwen-7b-medreasoning-unsloth?scriptVersionId=247846034">Kaggle Notebook </a>as well.</p><p>Q:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*MD5ljzu9DWNviWnU.png" /></figure><p>A:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*0F6eRgTaVz_sWj_d.png" /></figure><p>Model on the HUb: <a href="https://huggingface.co/Arnic/DeepSeek-R1-Distill-Qwen-7B_MedicalChain-Reasoning">Arnic/DeepSeek-R1-Distill-Qwen-7B_MedicalChain-Reasoning</a></p><h3>4. Deployment Guide</h3><p>If you want a full open source pipeline from calling the model in an app to serving reliably and scaling up, here’s a recomended clear path:</p><p><strong>Fine-tune → vLLM inference → BentoML or OpenLLM API → Dockerize → deploy on Kubernetes/KServe</strong>.</p><p>This gives you reproducible builds, versioned APIs, logs, metrics, and scalable endpoints for production users. Lets dive into open source alternatives :</p><p>Based on the latest open-source landscape, here is a comprehensive guide to the various ways you can serve and deploy your fine-tuned DeepseekR1_distill_Qwen-7b model for medical reasoning.</p><p>Deploying your fine-tuned model involves making it available for applications to use. <strong>The right solution depends on your goal, whether it’s a high-traffic production application, a private internal tool, a public demo, or simply running it on your local machine.</strong> Below are the open-source options, grouped by category.</p><h4>High-Performance Inference Servers</h4><p>These are specialized engines designed to run LLMs with maximum speed and efficiency on GPUs. They are the top choice for production environments where low latency and high throughput are critical.</p><p><strong>vLLM</strong></p><p>A state-of-the-art inference and serving engine from UC Berkeley. It uses a sophisticated memory management technique called PagedAttention to dramatically increase throughput. It provides an OpenAI-compatible API out of the box, making it easy to integrate into existing applications.</p><p>Best forProduction workloads that require handling many concurrent users with the lowest possible latency.</p><p><strong>LMDeploy</strong></p><p>A comprehensive LLM deployment toolkit from the OpenMMLab (creators of the Qwen model family). It features the highly efficient TurboMind inference engine, persistent batching, and excellent support for quantization. Given that your model is Qwen-based, LMDeploy is a particularly strong candidate for optimal performance.</p><p>Best for Achieving peak performance, especially for Qwen-based models, and leveraging a complete suite of optimization tools.</p><p><strong>TensorRT-LLM</strong></p><p>An open-source library from NVIDIA that compiles your model into a highly optimized engine for NVIDIA GPUs. This process can yield the absolute best performance but requires a more involved setup and build process compared to other servers.</p><p>Best for Enterprise-level deployments on NVIDIA hardware where squeezing out every last drop of performance is the primary goal.</p><p><strong>Text Generation Inference (TGI)</strong></p><p>A purpose-built inference server for text generation models, developed and used by Hugging Face. It is production-ready and includes features like continuous batching, token streaming, and support for multiple quantization formats.</p><p>Best for Teams looking for a robust, production-grade server with seamless integration into the Hugging Face ecosystem.</p><h4>General-Purpose Model Serving &amp; MLOps Frameworks</h4><p>These frameworks provide the tools to package your model, business logic, and dependencies into a scalable, production-ready application. You would typically use a high-performance server from Category 1 <em>inside</em> one of these frameworks.</p><p><strong>BentoML</strong></p><p>A unified framework for building, shipping, and scaling AI applications. It allows you to package your DeepseekR1 model and its inference logic (e.g., powered by vLLM) into a standardized format called a &quot;Bento.&quot; This Bento can then be easily containerized with Docker and deployed anywhere.</p><p>BentoML is<strong> </strong>Best for Creating end-to-end, production-grade AI services with custom logic, dependency management, and a clear path to scalable deployment.</p><p><strong>KServe</strong></p><p>A Kubernetes-native model serving platform that provides a standardized way to deploy ML models at scale. It offers features like autoscaling (including scaling to zero), canary rollouts, and an inference graph for multi-model pipelines. It’s an excellent choice for managing models within a cloud-native ecosystem.</p><p>Use KServe for Deploying models within an existing Kubernetes cluster and leveraging cloud-native best practices for management, scalability, and robust lifecycle control.</p><p><strong>OpenLLM</strong></p><p>Built on top of BentoML, OpenLLM is a platform specifically for operating LLMs in production. It aims to simplify the entire process by providing a single command to run inference with any open-source LLM and easily build applications around them.</p><p>Teams who want the power of BentoML but with a higher-level, LLM-centric abstraction to get to production even faster usually use OpenLLM</p><h4>Interactive Web UI &amp; Demo Frameworks</h4><p>These tools are perfect for creating interactive web applications to showcase your model’s capabilities, share it with stakeholders, or build a proof-of-concept.</p><p><strong>Gradio</strong></p><p>A Python library from Hugging Face that makes it incredibly simple to create a web UI for your model. With just a few lines of code, you can build a chatbot interface that allows users to interact with your medical reasoning model directly from their browser.</p><p><strong>Open WebUI</strong></p><p>A feature-rich, self-hosted web interface that is compatible with local LLM runners like Ollama and OpenAI-compatible APIs. It provides a polished, ChatGPT-like experience out of the box and can be pointed at your deployed model’s API endpoint.</p><p>Best for<strong> </strong>Providing a polished, persistent chat interface for a team or personal use that connects to your deployed model.</p><h4>Local &amp; Desktop Deployment</h4><p>These solutions are designed to run models directly on personal computers (macOS, Windows, and Linux), often with just a single command. This is ideal for development, offline usage, and ensuring data privacy.</p><p><strong>Ollama</strong></p><p>An extremely popular tool that simplifies running LLMs locally. You can create a Modelfile to package your fine-tuned DeepseekR1 model and then run it with a single command. Ollama provides a local API server, making it easy to build applications on top of it.</p><p>Ollama is Best for Developers and power users who want a simple, command-line-driven way to run and manage models on their local machine.</p><p><strong>LM Studio</strong></p><p>A desktop application that provides a graphical user interface (GUI) for discovering, downloading, and running LLMs. You can load your fine-tuned model (in GGUF format) and interact with it through a chat interface or enable its built-in local server.</p><p>for Users who prefer a visual, point-and-click interface for managing and experimenting with models on their local machine</p><p>Here is a summary table of the open-source deployment solutions for your fine-tuned DeepseekR1_distill_Qwen-7b model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4u9O3wTmKiwK8RQz.png" /></figure><h3>References</h3><p><em>[ 1 ] DeepSeek-AI , 2025, “DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning“</em></p><p><em>[ 2 ] </em><a href="https://www.inferless.com/learn/the-ultimate-guide-to-deepseek-models"><em>https://www.inferless.com/learn/the-ultimate-guide-to-deepseek-models</em></a></p><p><em>[ 3 ] </em><a href="https://research.google/blog/amie-a-research-ai-system-for-diagnostic-medical-reasoning-and-conversations/"><em>https://research.google/blog/amie-a-research-ai-system-for-diagnostic-medical-reasoning-and-conversations/</em></a></p><p><em>[ 4 ] Birger Moëll et al. 2025, “Medical Reasoning in LLMs: An In-Depth Analysis of DeepSeek R1”</em></p><p><em>[5] </em><a href="https://huggingface.co/deepseek-ai/DeepSeek-R1"><em>https://huggingface.co/deepseek-ai/DeepSeek-R1</em></a></p><p><em>[6] </em><a href="https://docs.together.ai/docs/deepseek-r1"><em>https://docs.together.ai/docs/deepseek-r1</em></a></p><p><em>[ 7 ] </em><a href="https://sebastianraschka.com/blog/2025/understanding-reasoning-llms.html"><em>https://sebastianraschka.com/blog/2025/understanding-reasoning-llms.html</em></a></p><p><em>[ 8 ] </em><a href="https://arxiv.org/pdf/2412.18925"><em>https://arxiv.org/pdf/2412.18925</em></a></p><p><em>[ 9] </em><a href="https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-reasoning-llms?utm_source=substack&amp;utm_campaign=post_embed&amp;utm_medium=web"><em>A Visual Guide to Reasoning LLMs</em></a></p><p><em>[ 10 ] </em><a href="https://arxiv.org/pdf/2502.03671v1"><em>https://arxiv.org/pdf/2502.03671v1</em></a></p><p><em>[ 11 ] </em><a href="https://arxiv.org/pdf/2408.00114"><em>https://arxiv.org/pdf/2408.00114</em></a></p><p><em>[ 12 ] </em><a href="https://arxiv.org/pdf/2505.11733v2"><em>https://arxiv.org/pdf/2505.11733v2</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922407121cc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“A Dive into Unsloth & Gemma 3 : Fine-Tune Gemma 3 12B with Unsloth & TRL for Custommer Service…]]></title>
            <link>https://medium.com/@anicomanesh/a-dive-into-unsloth-gemma-3-fine-tune-gemma-3-12b-with-unsloth-trl-for-custommer-service-53e93692d4d6?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e93692d4d6</guid>
            <category><![CDATA[rtls]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[gemma-3]]></category>
            <category><![CDATA[customer-service]]></category>
            <category><![CDATA[unsloth]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 15:20:24 GMT</pubDate>
            <atom:updated>2025-06-28T17:04:36.241Z</atom:updated>
            <content:encoded><![CDATA[<h3>“A Dive into Unsloth &amp; Gemma 3 : Fine-Tune Gemma 3 12B with Unsloth &amp; TRL for Custommer Service Adaptation”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqGPu4rdEjP8coFzzB26TQ.png" /></figure><p>Fine-tuning state-of-the-art large language models (10–100 B parameters) has historically been an exceptionally resource-intensive endeavor, demanding exorbitant GPU memory and training time. Conventional full-precision (FP32/FP16) or even 8-bit quantization methods routinely exhaust 40–80 GB of VRAM, necessitating complex distributed setups to achieve throughput sufficient for research and production workloads. This “memory wall” and the associated computational overhead have limited accessibility and accelerated development for many researchers and practitioners. This is where <strong>Unsloth</strong> comes in. Unsloth is a lightweight library that rewrites PyTorch attention and feed-forward kernels in Triton, enabling super-fast, memory-efficient fine-tuning with <strong>no loss in accuracy.</strong> In practice, open source version of Unsloth has been shown to train models 2–3× faster using ~30–70% less GPU memory than standard methods [ 6 ] . Crucially, it integrates seamlessly with the Hugging Face ecosystem, including the <strong>TRL</strong> library’s <strong>SFTTrainer</strong>, <strong>PEFT</strong>, and Hub features. This makes it ideal for hands-on domain adaptation, for example, we can fine-tune Google’s new Gemma-3 12B model on Kaggle’s (2× T4 GPU) free environment to create a specialized customer-support assistant. (Without Unsloth this is almost impossible because of the environment constraints like kaggle GPUs memory and time limit)</p><p>In the othe hand<strong> </strong>Google’s new open-source model family, <strong>Gemma 3</strong>, is swiftly gaining popularity due to its impressive performance, comparable to some of the latest proprietary models. Gemma 3 introduces multimodal capabilities, enhanced reasoning skills, and supports over 140 languages. Gemma 3 offers state-of-the-art performance while remaining lightweight and efficient and designed to run fast, directly on devices — from phones and laptops to workstations — helping developers create AI applications</p><p>In the remainder of this article, we will dive deeper into the technical intricacies of <strong>Unsloth</strong> and <strong>Gemma 3</strong>, showcasing their powerful features and how they can be leveraged together to build a highly optimized, fine-tuned model for any type of <strong>customer support assistant</strong>, whether it be a sophisticated <strong>chatbot</strong>, an intelligent <strong>agent</strong>, or an interactive FAQ system. We will provide a step-by-step guide through the fine-tuning process, from data preparation to model deployment, highlighting best practices and practical considerations for achieving optimal performance in real-world customer service scenarios.</p><p>Overall, this article will cover:</p><ul><li>Introducing Gemma 3: The most capable model you can run on a single GPU or TPU</li><li>Why use Unsloth? Key benefits and internals (speedups, memory savings)</li><li>Model &amp; Data Setup<em>:</em> Loading Gemma-3 via Unsloth, preparing a domain dataset for supervised fine-tuning.</li><li>PEFT Integration<em>:</em> Applying adapter weights in full precision (LoRA) versus 4-bit (QLoRA) modes, with code examples.</li><li>Training Pipeline: Configuring and running SFTTrainer for supervised fine-tuning.</li><li>Evaluation &amp; Deployment: Evaluating on domain tasks and considerations for deployment the fine-tuned model.</li><li>Best Practices and Future Work: Tips for stable training, potential caveats, and where to go next.</li></ul><h3>1. Gemma-3 and Domain Adaptation</h3><p>Gemma-3 is <a href="https://deepmind.google/models/gemma/gemma-3/"><strong>Google DeepMind’s</strong></a> latest open-weights model family, codesigned with the family of Gemini frontier models . It comes in 1B, 4B, 12B, and 27B parameter sizes, each optimized for fast, single-GPU inference [ 1 ]. Unusually for a compact model, Gemma-3 includes advanced features: it <strong>understands images and text together</strong> via a custom <a href="https://huggingface.co/docs/transformers/en/model_doc/siglip">SigLIP</a> encoder (for example, it tokenizes a 896×896 image into 256 “soft tokens” that join the text tokens) [ 3 ] [ 5 ] .</p><p>It also uses a <strong>novel attention architecture</strong>: each layer block contains <strong>5 local-attention heads with a 1,024-token sliding window plus 1 global-attention head [ 3 ] </strong>, This 5-to-1 interleaved attention greatly reduces KV-cache memory growth on long inputs, enabling much longer context lengths. In fact, Gemma-3 4B/12B/27B support a <strong>128K token context window</strong> — roughly the length of a full novel [ 4 ] . Finally, Gemma-3 is highly multilingual: it ships with support for 35+ languages out-of-the-box and has seen training across <strong>140+ languages</strong> [ 3 ] All told, Gemma-3 packs Google’s cutting-edge LLM tech into models small enough to run on commodity GPUs.</p><p>Here’s the core parameters of the new Gemma 3 models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Q87Ytlwpnfu6HFCD.png" /><figcaption>Table 1 | core parameters of the new Gemma 3 [ 3 ]</figcaption></figure><p>And Gemma 3 key features at a glance are:</p><ol><li><strong>Multilingual support:</strong> Out-of-the-box support for 35 languages and pre-trained functionality for over 140 languages.</li><li><strong>Long context window:</strong> Comes with 128k-token context window.</li><li><strong>Multimodal capabilities:</strong> Supports advanced text, image, and short video reasoning.</li><li><strong>Structured output:</strong> Built-in support for function calling.</li><li><strong>Quantized models:</strong> Official quantized versions are available, reducing model size and computational requirements.</li><li><strong>Hardware integration:</strong> Works with CPUs, NVIDIA GPUs, Google Cloud TPUs, and AMD GPUs.</li><li><strong>Integration with popular tools:</strong> Works with tools like Hugging Face Transformers, PyTorch, Keras, JAX, Google AI Edge, vLLM, and more.</li><li><strong>ShieldGemma 2:</strong> It provides image safety checks for dangerous content, explicit material, and violence, ensuring responsible AI development.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7rRfB_8g3_vqAe0l" /><figcaption>Figure 0 | Gemma 3 Performance , Source, Gemma 3 Technical Report</figcaption></figure><p>As i mentioned , Google’s Docs show the model uses a vision encoder (SigLIP) to convert an image into 256 visual tokens and processes text tokens with a stack of <strong>“interleaved” attention layers</strong>. 5 local attention layers capture short-range context and 1 global layer captures long-range context [ 3 ]. This design enables Gemma-3 to handle images and <strong>extremely long text sequences (up to 128K tokens)</strong> within limited GPU memory.</p><p>Gemma’s pre-training and post-training processes were optimized using a combination of distillation, reinforcement learning, and model merging. This approach results in enhanced performance in math, coding, and instruction following. Gemma 3 uses a new tokenizer for better multilingual support for over 140+ languages and was trained on 2T tokens for 1B, 4T for 4B, 12T for 12B, and 14T tokens for 27B, on Google TPUs using the JAX Framework.</p><p>For post-training, Gemma 3 uses 4 components:</p><ul><li>Distillation from a larger instruct model into the Gemma 3 pre-trained checkpoints.</li><li>Reinforcement Learning from Human Feedback (RLHF) to align model predictions with human preferences.</li><li>Reinforcement Learning from Machine Feedback (RLMF) to enhance mathematical reasoning.</li><li>Reinforcement Learning from Execution Feedback (RLEF) to improve coding capabilities.</li></ul><p>These updates significantly improved the model math, coding, and instruction following capabilities, making it the top open compact model in LMArena, with a score of 1338.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m5INvEUHfJixCsFe.png" /><figcaption><strong>Figure 1 | Model Performance vs. Size , Gemma 3 27B IT vs other models</strong></figcaption></figure><p>For more details about Gemma 3 architecture and design watch following video from <a href="https://deepmind.google/models/gemma/gemma-3/"><strong>Google DeepMind’s</strong></a> :</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQwfsj-oM_CE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQwfsj-oM_CE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQwfsj-oM_CE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfe8b1e6fb887c75ba23a1f354e6bd98/href">https://medium.com/media/dfe8b1e6fb887c75ba23a1f354e6bd98/href</a></iframe><p>If you want go further following video is a good start:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F16gVylZniJE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D16gVylZniJE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F16gVylZniJE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c64d041dddef8e9ab1330e2f411d016/href">https://medium.com/media/6c64d041dddef8e9ab1330e2f411d016/href</a></iframe><h3>2. Understanding Unsloth</h3><p>Unsloth is a drop-in fine-tuning framework that optimizes Transformer training at the kernel level. It achieves its speed and memory gains through Triton-based custom kernels and by applying quantized training (QLoRA) with no approximation loss.</p><p>Unsloth’s Core Architecture provides the foundation for its high-performance LLM fine-tuning capabilities through a system of utilities, patches, and optimizations.</p><h4>2.1 Key Capabilities</h4><p>The following are key capabilities Unsloth provides for efficient LLM fine-tuning:</p><ol><li><strong>Faster Training: </strong>2–5x speedup compared to standard implementations</li><li><strong>VRAM Reduction: </strong>Uses 50–80% less memory, fitting larger models in limited hardware</li><li><strong>Long Context Support</strong>: Enables training with much longer sequences than normally possible</li><li><strong>Multiple Model Support: </strong>Works with Gemma, Llama, Mistral, Qwen, Phi, and other popular models</li><li><strong>Quantization Supports: </strong>4-bit, 8-bit, and 16-bit precision training</li><li><strong>Training Methods</strong>: Enables SFT, DPO, GRPO and other reinforcement learning approaches</li><li><strong>Multiple Export Formats: </strong>Save models in HuggingFace, GGUF, or Ollama formats</li></ol><h4>2.2 Core Architecture Components</h4><p>The Core architecture components<strong> of </strong>Unsloth can be described as bellow<strong> </strong>:</p><ol><li><strong>Core Utilities</strong>: Central utility functions that power the entire system</li><li><strong>Patching System</strong>: Dynamic modification of model behaviors and library functions</li><li><strong>Memory Optimization System</strong>: Techniques to minimize VRAM usage</li><li><strong>Optimization Techniques Integration</strong>: Implementation of custom kernels and attention mechanisms</li><li><strong>Initialization and Environment Setup</strong>: Configuration of the environment for optimal performance</li><li><strong>External Library Integration</strong>: Enhancement of external libraries for LLM fine-tuning as shown in Table 2. For example :<br>Unsloth is fully integrated with the HF ecosystem. Its “FastModel.from_pretrained( )” loader wraps standard HF models to use Unsloth’s kernels. It works out-of-the-box with Hugging Face Datasets, tokenizers, and the Hub. Importantly, Unsloth supports the TRL library: you can pass an Unsloth-wrapped model into TRL’s “SFTTrainer”, “DPOTrainer”, etc., just as you would any transformers model. It also integrates with the PEFT library for LoRA: simply supply a “LoraConfig” to the trainer and Unsloth will apply efficient, quantized LoRA updates. This seamless compatibility means we can combine Unsloth’s speedups with all the tooling of Transformers, PEFT, and TRL.[ 14 , 15]</li></ol><blockquote>When you call “FastModel.from_pretrained( )”, Unsloth loads the model from the Hugging Face Hub (or local path) just like “AutoModelForCausalLM.from_pretrained( )”, but then it intelligently patches or replaces the standard PyTorch layers (like “nn.Linear, nn.MultiheadAttention”) with its own highly optimized Triton-based versions. The model still retains its Hugging Face model structure but now runs Unsloth’s faster kernels.</blockquote><p>Together, these components enable Unsloth to achieve its goal of making LLM fine-tuning faster and more memory-efficient on consumer hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*NZu_b7YGzMNT508R.png" /><figcaption>Table 2 | Unsloth External Libraries Integration</figcaption></figure><h4>2.3 Innovative Technologies</h4><p>More important , Unsloth’s development has incorporated several <strong>key innovative technologies</strong>, a few of which are briefly described below.</p><h4>2.3.1 Advanced Quantization and Memory Management</h4><p>Unsloth implements sophisticated techniques to minimize memory footprint and optimize data handling, which is particularly crucial for large models and environments with limited video RAM (VRAM).</p><ul><li><strong>Enhanced QLoRA Implementation:</strong> Unsloth optimizes the Quantized Low-Rank Adaptation (QLoRA) process by significantly reducing weight upscaling, which directly leads to lower memory usage and quicker training. Unlike some other QLoRA implementations, Unsloth directly employs bfloat16 for computations, avoiding inefficient conversions from float16. This streamlined data flow and reduced weight upscaling represent deep, meticulous optimizations within the QLoRA framework, rather than just a standard application of the technique. These seemingly minor “micro-optimizations” at the data type and operation level accumulate to deliver substantial performance enhancements across large-scale models, contributing to Unsloth’s “extreme performance.” [ 6 , 14, 16 ]</li><li><strong>Dynamic Quantization 2.0:</strong> Unsloth’s Dynamic Quantization 2.0 is an advanced post-training export feature that intelligently optimizes LLMs for efficient deployment. Unlike uniform methods, it analyzes each layer’s sensitivity to compression using a large calibration dataset (300K-1.5M tokens), ensuring critical layers maintain quality while others are aggressively quantized. This process, coupled with GGUF export support, allows Unsloth to provide high-quality, efficient models for inference, thus completing the LLM lifecycle from fine-tuning to effective deployment. [ 18 ]</li><li><strong>Built-in Paged Optimizers and Gradient Checkpointing:</strong> Unsloth significantly boosts memory efficiency by integrating <strong>paged optimizers</strong> and <strong>optimized gradient checkpointing</strong> (use_gradient_checkpointing=&quot;unsloth&quot;). Gradient checkpointing saves VRAM by recomputing intermediate activations during the backward pass instead of storing them, enabling <strong>longer input sequences</strong>. Paged optimizers further enhance this by efficiently managing optimizer states in GPU memory. This built-in, synergistic approach not only helps fit larger models or batches but is critically designed to enable <strong>longer context lengths</strong>, directly addressing a common VRAM bottleneck and allowing models to process and generate more extended, coherent responses. [19, 20]</li><li><strong>Elimination of Redundant Tensor Copies:</strong> Unsloth is meticulously designed to avoid <a href="https://learnopencv.com/unsloth-guide-efficient-llm-fine-tuning/">redundant tensor copies </a>that can sometimes occur in standard Hugging Face models during training. This careful memory management contributes to overall efficiency and reduced VRAM usage by minimizing unnecessary data movement.</li></ul><h4>2.3.2 Custom Kernel Development with Triton</h4><p>A cornerstone of Unsloth’s performance is its strategic use of <a href="https://openai.com/index/triton/">OpenAI’s Triton </a>language for developing highly optimized custom GPU kernels. Triton allows for direct, low-level programming of GPU operations, enabling Unsloth to bypass the overheads of generic PyTorch operations for critical computational steps.</p><ul><li><strong>Manual Autograd:</strong> Unsloth implements a “Manual Autograd” mechanism, where backpropagation steps for compute-intensive layers, particularly Multi-Layer Perceptron (MLP) and Self-Attention layers, are manually derived and optimized. While PyTorch’s Autograd provides a flexible and user-friendly abstraction layer for automatic differentiation, this abstraction can introduce overheads for highly specific, performance-critical operations. Unsloth’s “Manual Autograd” represents a deliberate choice to operate at a lower level of abstraction, directly controlling gradient computation for key layers. This approach, common in high-performance computing, involves sacrificing some generality and ease of development for raw speed. By manually deriving matrix differentials and optimizing how LoRA weight multiplications are “bracketed” , Unsloth can achieve performance gains that are not attainable with generic frameworks, even those utilizing highly optimized libraries. This fundamental technical differentiator underpins Unsloth’s impressive speed claims. [20, 21 ]</li><li><strong>Chained Matrix Multiplication Optimizations:</strong> Unsloth optimizes matrix multiplications, which are fundamental to LLM training, by chaining them together efficiently. This technique minimizes intermediate memory allocations and maximizes GPU utilization, leading to faster computations.</li></ul><blockquote>Matrix multiplications (or “matrix multiplies” / “GEMMs” — General Matrix Multiplies) are the most computationally intensive operations in Transformer models. Optimizing them is paramount. “Chaining them together efficiently” refers to techniques like <strong>kernel fusion</strong> or <strong>operator fusion</strong>. Instead of performing A @ B and then C @ D as separate operations, and potentially loading/storing intermediate results, a fused kernel would perform (A @ B) @ C or A @ (B @ C) etc., in a single, more efficient pass, avoiding intermediate memory transfers. This is precisely what custom kernel development (like in Triton) aims to achieve.[ 21]</blockquote><ul><li><strong>Fast Rotary Position Embeddings (ROPE) and Accelerated RMS Normalization:</strong> Unsloth leverages Triton to implement highly optimized versions of Fast ROPE embeddings and accelerated RMS Normalization. These components are critical for modern transformer architectures, and their optimization at the kernel level directly contributes to overall training speed by reducing computational latency.[ 2, 22]</li><li><strong>The KernelLLM Connection and Unsloth’s Deep Expertise: </strong>Unsloth has demonstrated significant expertise in low-level performance optimization through its development of custom Triton kernels. By manually deriving backpropagation steps and rewriting PyTorch modules into Triton kernels, Unsloth has achieved substantial improvements in training speed and memory efficiency. For instance, Unsloth reports up to 30x faster training and 60% less memory usage without compromising accuracy using paid versions. [20, 25 ]</li></ul><p>While the specific term <a href="https://huggingface.co/unsloth/KernelLLM">“KernelLLM” </a>is not explicitly mentioned in the updated Unsloth documents, the described activities align with the concept of translating PyTorch modules into efficient Triton kernels. This approach underscores Unsloth’s advanced capabilities in automating high-performance kernel generation, suggesting that their primary fine-tuning framework benefits from such AI-driven optimization methodologies.</p><h4>2.3.3. Efficient Data Handling and Templating</h4><p>Beyond core model computations, Unsloth also optimizes the data preparation pipeline to ensure high-quality fine-tuning outcomes.</p><ul><li><strong>Customized Chat Templates and Tokenization:</strong> Unsloth integrates customized <a href="http://Customized Chat Templates and Tokenization">chat templates</a> that structure conversations into clear, unambiguous formats. This is crucial because proper tokenization directly impacts how models understand and respond to inputs, preventing issues such as hallucination or incorrect answers. The specific template used directly influences tokenization and, consequently, the final embeddings and what the model learns during fine-tuning.</li><li><strong>conversation_extension Feature:</strong> Unsloth tackles the limitation of single-turn datasets for training <strong>multi-turn conversational</strong> LLMs by introducing its conversation_extension feature. This innovation generates “fake but plausible multi-turn chat” from single-turn Alpaca-format data, significantly enhancing the quality of Supervised Fine-Tuning (SFT) for dialogue models by providing more realistic conversational context.</li></ul><p>While Unsloth is known for its low-level computational efficiency, features like <a href="https://docs.unsloth.ai/basics/chat-templates">conversation_extension</a> and customizable chat templates demonstrate <strong>its understanding that fast training alone isn’t sufficient</strong>; the training must also be effective for real-world conversational tasks. Issues such as poor tokenization or the lack of multi-turn data can severely degrade model quality, regardless of computational speed. By proactively addressing these data-centric challenges, Unsloth ensures that its underlying efficiency translates into genuinely higher- quality fine-tuned models, offering a more comprehensive and user-centric solution for developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*rPBPsjf3PtuqPSz6.png" /><figcaption><strong>Figure 2 | A bit issue is that some datasets like Alpaca dataset is single turn, whilst remember using ChatGPT was interactive and you can talk to it in multiple turns. For example, the left is what we want, but the right which is the Alpaca dataset only provides singular conversations. We want the finetuned language model to somehow learn how to do multi turn conversations just like ChatGPT.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*_1SLGGFzYpyxl37w.png" /><figcaption><strong>Figure 3 | So Unsloth introduced the </strong>conversation_extension<strong> parameter, which essentially selects some random rows in our single turn dataset, and merges them into 1 conversation! For example, if you set it to 3, we randomly select 3 rows and merge them into 1! Setting them too long can make training slower, but could make our chatbot and final finetune m</strong></figcaption></figure><h4>2.3.4 Optimized Cross-Entropy Loss Computation</h4><p>Unsloth specifically optimizes the computation of cross-entropy loss. This optimization significantly reduces memory consumption during this critical part of the training loop, contributing to the overall memory efficiency of the framework by minimizing the memory footprint of gradient calculations. [ 23, 24 ]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZbLMZALfvotypy7-.png" /><figcaption><strong>Figure 4 |Memory use and maximum attainable batch size (in millions of tokens) for a variety of frontier models on a 16-GPU (80 GB each) fully-sharded data-parallel setup with activation checkpointing and a mixed-precision 16-bit (fp16/bf16) AdamW optimizer . For each model, we break its memory use down into weights and optimizer states, activation checkpoints, and the log-probabilities computed by the cross-entropy loss layer. Our Cut Cross-Entropy (CCE) enables increasing the batch size by 1.5x (Llama 2 13B) to 10x (GPT 2, Gemma 2 2B), with no sacrifice in speed or convergence. Exact values in Table A4. Source [24]</strong></figcaption></figure><h4>2.4 Overview of Fine-tuning Pipeline with Unsloth</h4><p>The typical Unsloth workflow follows following steps:</p><ol><li><strong>Model Loading</strong>: Load a pre-trained model using FastLanguageModel.from_pretrained()</li><li><strong>Optimization Application</strong>: Apply LoRA/QLoRA with FastLanguageModel.get_peft_model()</li><li><strong>Training Configuration</strong>: Set up a trainer (SFTTrainer, DPOTrainer, etc.)</li><li><strong>Fine-tuning</strong>: Train the model with the configured trainer</li><li><strong>Model Saving</strong>: Export the fine-tuned model for inference or further use</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/0*gdLICq4xtXcaXvOX.png" /><figcaption><strong>Figure 5 | Sequence diagram of Fine-tuning Pipeline with Unsloth , Figure by the author</strong></figcaption></figure><h4>2.5 Benchmark</h4><p>Unsloth’s technical innovations translate into quantifiable and substantial performance improvements across various benchmarks, positioning it as a leading solution for efficient LLM fine-tuning.</p><p><strong>Quantified Benefits:</strong></p><ul><li><strong>Speed:</strong> Unsloth boasts a staggering 30x increase in training speed for its Enterprise offering, reducing the Alpaca benchmark task from<strong> 85 hours</strong> to just <strong>3 hours</strong>. The open-source version provides a 2x speedup.</li><li><strong>Memory Reduction:</strong> Memory usage is reduced by 60% to 90% , allowing for 6x larger batch sizes. The open-source version achieves 50% less memory usage. For instance, peak memory usage on an A10 GPU was reduced from 16.7GB to 6.9GB (a 59% reduction), and on a Tesla T4 GPU from 14.6GB to 7.5GB (a 49% reduction).</li><li><strong>Accuracy:</strong> Unsloth proudly declares 0% loss in accuracy compared to normal QLoRA, ensuring that performance gains do not come at the expense of model quality. Furthermore, an optional +20% increase in accuracy is available with their MAX offering.</li><li><strong>Comparative Analysis:</strong> Unsloth consistently outperforms standard fine-tuning methods and even Flash Attention 2 (FA2). Benchmarks show Unsloth is up to 2.7x faster and uses up to 74% less memory compared to the latest Transformers version (4.36) with native Scaled Dot Product Attention (SDPA). When compared to other LLM fine-tuning frameworks like Axolotl and Torchtune, Unsloth “clearly dominates single-GPU benchmarks in terms of speed and VRAM efficiency due to its custom kernels”. It is important to note that while Unsloth excels on single-GPU setups, its open-source version is explicitly limited to single-GPU operation, with multi-GPU/node capabilities reserved for its paid tiers. This contrasts with Axolotl and Torchtune, which offer robust open-source solutions for multi-GPU and multi-node training using techniques like DeepSpeed and Fully Sharded Data Parallel (FSDP). I have gathered a cummulative benchmark from different resources like Unsloth publications and <a href="https://huggingface.co/blog/unsloth-trl#:~:text=Unsloth%20was%20benchmarked%20across%2059,in%20Unsloth%E2%80%99s%20benchmarking%20details%20here">Hugging Face</a> website as bellow (see more details <a href="https://unsloth.ai/blog/mistral-benchmark">Here</a>). In this article we will use <strong>Open-Source Unsloth</strong> for fine-tuning Gemma3–12b:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*num2LTYX_mDzhmj6.png" /><figcaption>Table 3: Unsloth Performance Benchmarks and Comparisons, table by the author</figcaption></figure><h3>3. Fine-tuning Gemma 3 with Unsloth</h3><p>Based on <a href="https://deepmind.google/models/gemma/gemma-3/">Google DeepMind’s</a> documents :</p><blockquote><strong>Gemma 3 is the most capable model that can run on a single GPU or TPU. Efficient on workstations, laptops, and even smartphones, allowing developers to build responsible AI applications at scale.</strong></blockquote><blockquote><strong>Gemma </strong><a href="https://developers.googleblog.com/en/gemma-3-quantized-aware-trained-state-of-the-art-ai-to-consumer-gpus/"><strong>Quantization-Aware Training (QAT) </strong></a><strong>dramatically reduces memory requirements while maintaining high quality. This lets you run powerful models like Gemma 3 27B locally on consumer-grade GPUs like an NVIDIA RTX 3090.</strong></blockquote><p>Despite these inherent efficiencies, it remains absolutely reasonable, and indeed highly advantageous, to fine-tune Gemma 3 with Unsloth. This combination represents an <strong>optimal balance of performance, efficiency, and accessibility </strong>for real-world deployment. Here’s why:</p><ol><li><strong>Hardware Democratization</strong></li></ol><p>Gemma 3’s mobile/edge optimization + Unsloth’s 4-bit QAT = Consumer GPU compatibility. Example: Gemma 3 27B (normally ~54GB VRAM) becomes deployable on RTX 3090 (24GB VRAM) via Unsloth’s quantization</p><p><strong>2. Memory Efficiency</strong></p><p>Here we can see approaches benchmark. Gemma3–12B didn’t consume more than 8GB VRAM with T4 GPU on Kaggle :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*j46-uiZZ980juE4b.png" /><figcaption><strong>Table 4: Source</strong>: <a href="https://docs.unsloth.ai/get-started/beginner-start-here/unsloth-requirements">Unsloth VRAM Tables</a></figcaption></figure><p><strong>3. Quality Preservation</strong><br>Unsloth’s dynamic quantization outperforms naive 4-bit methods:</p><ul><li>&lt;1% accuracy drop vs full-precision (vs 3–5% with standard 4-bit)</li><li>Preserves Gemma 3’s 91.5% MMLU benchmark performance after fine-tuning</li></ul><h4>3.1 Dataset Selection and EDA</h4><p>We use the <a href="https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset">Bitext <strong>Customer Support LLM Chatbot</strong> </a>dataset for domain adaptation in online customer service, which contains <strong>~27K</strong> synthetic customer-service Q&amp;A examples. Each row has an instruction (a user’s question), a response (an agent’s answer), plus labels for high-level category (e.g. ORDER, PAYMENT) and intent (e.g. cancel_order, check_refund_policy). There are 11 top-level categories and 27 distinct intents covered. The instructions often include placeholders like {{Order Number}} or {{Invoice Number}}, so training learns to handle dynamic variables. In total, the dataset <strong>spans ~3.6 million tokens</strong> (instruction + response). This breadth of intents – from account creation to shipping issues and refunds – <strong>makes it a strong benchmark for a customer-support assistant.</strong> In practice we will format each example as a simple user prompt → assistant reply pair (ignoring the numeric labels during training).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tr0HoaeteXoT_g9I.png" /><figcaption>Figure 6 | <a href="https://huggingface.co/datasets/bitext/Bitext-customer-support-llm-chatbot-training-dataset">Bitext <strong>Customer Support LLM Chatbot</strong> </a>dataset</figcaption></figure><p>Below is a full Python script for fine-tuning on Kaggle (T4 GPUs). It is annotated step-by-step. In Kaggle you can put this in a single notebook cell or script; it will install dependencies, prepare data, launch training, and finally demonstrate inference and (optionally) push to HF. You can review and edit the code in my <a href="https://www.kaggle.com/code/arashnic/gemma3-12b-unsloth-fine-tune-customer-assist/notebook?scriptVersionId=243549020"><strong>Kaggle Notebook</strong></a><strong>.</strong></p><h4>3.2 GPU Utilization</h4><p>The code is set up to <strong>attempt to use both T4 GPUs</strong> on Kaggle but :<br>Unsloth’s open-source (free) version is explicitly designed for <strong>single-GPU training</strong>. Their website and documentation clearly state that multi-GPU support is a feature of their paid “Pro” and “Enterprise” tiers .</p><blockquote>So while the environment is configured for multi-GPU training on a single machine (e.g., a T4x2 instance) in my code and “per_device_train_batch_size” aims to distribute the workload, the free version of Unsloth will only utilize one T4 GPU during runtime. Multi-GPU support is exclusive to Unsloth’s paid “Pro” and “Enterprise” tiers. And you can test the code on these version for Multi-GPU run.</blockquote><p>Here’s how it generally works:</p><ol><li><strong>PyTorch Detection</strong>: The Hugging Face Trainer (which SFTTrainer from trl is built upon) automatically detects and tries to utilize all available CUDA-enabled GPUs. When you&#39;re in a Kaggle T4x2 environment, PyTorch should see two GPUs.</li><li>per_device_train_batch_size: The key setting in your SFTConfig is per_device_train_batch_size.</li></ol><pre>args = SFTConfig(<br>    # ... other args ...<br>    per_device_train_batch_size = 2, # This batch size applies to EACH GPU<br>    gradient_accumulation_steps = 4,<br>    # ... other args ...<br>)</pre><p>3. This tells the trainer to put a batch of size 2 on each detected GPU.</p><p><strong>4. Effective Batch Size</strong>: Your total effective batch size across both GPUs before gradient accumulation would be per_device_train_batch_size * number_of_gpus.</p><ul><li>So, with 2 GPUs, it’s 2 (per_device_batch) * 2 (gpus) = 4.</li><li>With gradient_accumulation_steps = 4, your actual effective batch size used for each optimizer step becomes 2 (per_device_batch) * 2 (gpus) * 4 (accumulation_steps) = 16.</li></ul><p><strong>5. Data Parallelism</strong>: In a typical notebook environment like Kaggle, the Trainer will likely use torch.nn.DataParallel by default to distribute the model and data across the available GPUs. This means the model is replicated on each GPU, and each GPU processes a slice of the input batch.</p><p>The warning I included in the setup code:</p><pre>if torch.cuda.device_count() &lt; 2:<br>    print(f&quot;Warning: Expected 2 GPUs for T4x2, but found {torch.cuda.device_count()}. ...&quot;)</pre><p>is there to alert you if, for some reason, the Kaggle environment doesn’t correctly provide or PyTorch doesn’t detect both GPUs. If torch.cuda.device_count() returns 2, then the Trainer will proceed to use both.</p><p>Following full snippet is available in my<strong> </strong><a href="https://www.kaggle.com/code/arashnic/gemma3-12b-unsloth-fine-tune-customer-assist/notebook?scriptVersionId=243549020"><strong>Kaggle Notebook</strong></a><strong> </strong>you can view , fork and edit notebook as well.</p><h4>3.3 Implementation</h4><h4>3.3.1 Environment Setup and Dependency Installation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*yFA9O-SzHpVp71eU.png" /></figure><p>This initial block, suppressed by %%capture to hide output, handles the crucial setup of the Python environment. It first checks if the code is running in a Colab, Kaggle, or local environment. Based on this detection, it installs the necessary libraries. Key dependencies include:</p><ul><li>unsloth: The core library for fast, memory-efficient LLM fine-tuning.</li><li>bitsandbytes: For 4-bit/8-bit quantization.</li><li>accelerate: A Hugging Face library for simplifying distributed training and device placement.</li><li>peft: Hugging Face&#39;s Parameter-Efficient Fine-Tuning library, used for LoRA.</li><li>trl: Hugging Face&#39;s Transformer Reinforcement Learning library, which includes SFTTrainer for supervised fine-tuning.</li><li>transformers: The primary Hugging Face library for accessing models and tokenizers.</li><li>datasets: For loading and processing datasets. The --no-deps flag is used strategically to manage dependencies and ensure compatibility, particularly with Unsloth&#39;s optimized components.</li></ul><h4>3.3.2 Model Selection and Optimized Loading</h4><p>Here, the specific model unsloth/gemma-3-12b-it is selected. This is an instruct-tuned version of Gemma-3 12B, optimized by Unsloth.</p><p>The FastModel.from_pretrained() method from Unsloth is used to load the model and its tokenizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*BgZ6nXRsBEQ3O-S1.png" /></figure><p>Key parameters include:</p><ul><li>model_name: Specifies the Hugging Face model identifier.</li><li>max_seq_length: Sets the maximum sequence length the model can handle (2048 tokens in this case).</li><li>load_in_4bit = True: This is critical for memory efficiency. It instructs Unsloth to load the model weights in 4-bit precision using bitsandbytes, significantly reducing VRAM footprint and enabling fine-tuning of larger models like 12B on T4 GPUs.</li><li>full_finetuning = False: Indicates that parameter-efficient fine-tuning (PEFT) methods like LoRA will be used, rather than training all model parameters.</li></ul><h4>3.3.3 PEFT Configuration with LoRA</h4><p>This block configures the model for Parameter-Efficient Fine-Tuning (PEFT) using Unsloth’s FastModel.get_peft_model. Specifically, it sets up Low-Rank Adaptation (LoRA), which involves adding small, trainable adapter layers to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*yC49G6BIF1UqnG3F.png" /></figure><p>Key parameters include:</p><ul><li>finetune_language_layers<strong>, </strong>finetune_attention_modules<strong>, </strong>finetune_mlp_modules: These flags specify which parts of the transformer architecture (language model components, attention blocks, and MLP layers) will have LoRA adapters applied. Vision layers are disabled as this is a text-only task.</li><li>r = 8: The rank of the LoRA matrices. A smaller rank means fewer trainable parameters. 8 is a common starting point.</li><li>lora_alpha = 16: A scaling factor for LoRA, often set to 2 * r.</li><li>lora_dropout = 0: Dropout rate for the LoRA layers.</li><li>bias = &quot;none&quot;: Specifies how biases are handled in LoRA layers. &quot;none&quot; means biases are not trained.</li></ul><h4>3.3.4 Tokenizer Chat Templating</h4><p>To ensure inputs are formatted correctly for the Gemma-3 model during both training and inference, its specific chat template is applied to the tokenizer. Unsloth’s get_chat_template utility handles this, configuring the tokenizer with the appropriate special tokens and turn structures (e.g., &lt;start_of_turn&gt;user, &lt;start_of_turn&gt;model). Consistent templating is vital for instruction-tuned models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/0*6LvZoJnHo0nr-LN8.png" /></figure><h4>3.3.5 Dataset Loading and Preprocessing</h4><p>The bitext/Bitext-customer-support-llm-chatbot-training-dataset is loaded from the Hugging Face Hub. This dataset contains instruction (user query) and response (assistant answer) pairs. The core preprocessing step is handled by formatting_prompts_func. This function iterates through each example and converts the instruction and response into the standardized Gemma-3 chat format using tokenizer.apply_chat_template. This function creates a list of message dictionaries, each specifying the role (user or model) and content. add_generation_prompt = False is used during training as we provide the complete conversation turn. The dataset.map() function applies this transformation to all examples in the dataset in a batched manner for efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/0*ZqRGSpZ5nIVESqoJ.png" /></figure><h4>3.3.6 Supervised Fine-Tuning (SFT) Trainer Configuration</h4><p>The SFTTrainer from the trl library is configured to perform supervised fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*bqIULibdET8rTQRF.png" /></figure><p>Key parameters include:</p><ul><li>model<strong>, </strong>tokenizer<strong>, </strong>train_dataset: These are passed directly.</li><li>args = SFTConfig(...): This object encapsulates various training hyperparameters:</li><li>dataset_text_field = &quot;text&quot;: Specifies the column in the dataset containing the formatted conversational text.</li><li>per_device_train_batch_size = 2: The batch size for each GPU. With T4x2, this means 2 samples per GPU.</li><li>gradient_accumulation_steps = 4: Simulates a larger batch size by accumulating gradients over 4 steps before an optimizer update. The effective batch size becomes 2 (per_device) * 2 (GPUs) * 4 (accum_steps) = 16.</li><li>warmup_steps = 10: Number of initial steps with a lower learning rate to stabilize training.</li><li>max_steps = 100: Total number of training steps. For a full run, num_train_epochs would typically be used.</li><li>learning_rate = 2e-4: The learning rate for the AdamW optimizer.</li><li>logging_steps = 5: Frequency of logging training metrics.</li><li>optim = &quot;adamw_8bit&quot;: Uses the memory-efficient 8-bit AdamW optimizer from bitsandbytes.</li><li>weight_decay<strong>, </strong>lr_scheduler_type<strong>, </strong>seed: Standard training parameters.</li><li>report_to = &quot;none&quot;: Disables reporting to external services like WandB for this configuration.</li></ul><h4>3.3.7 Optimizing Training: Learning Only Responses</h4><p>Unsloth provides a utility train_on_responses_only that modifies the training process. It masks the loss for the user&#39;s prompt tokens (identified by instruction_part). This ensures that the model is only penalized (and thus learns) based on its ability to generate the assistant&#39;s response (response_part), not on regenerating the user&#39;s input. This is a common and <strong>effective technique</strong> for fine-tuning conversational AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*j5w_rqMaC_OzcSpv.png" /></figure><h4>3.3.8. Train</h4><p>This is the core training step. The trainer.train() method initiates the fine-tuning process based on the configurations previously set. It will iterate through the dataset for the specified max_steps, updating the LoRA adapter weights. Upon completion, it prints that training is finished and stores training statistics (like runtime, loss) in trainer_stats</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*tcp5qzD2CpuVkWEU.png" /></figure><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*d7P_LYJ7zciBnPZ9.png" /></figure><h4>3.3.9 Inference</h4><p>For inference, the tokenizer is again configured with the “gemma-3” chat template (this is good practice, ensuring consistency, though if unchanged since training, it might be redundant). Example prompts (messages_support, messages_product) are defined in the standard list-of-dictionaries format. tokenizer.apply_chat_template is then used to convert these into a single string prompt. Crucially, add_generation_prompt = True is set here. This appends the necessary tokens (e.g., &lt;start_of_turn&gt;model\n) to signal the model that it should now generate a response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*zMo2SL3WhJwdFYCO.png" /></figure><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*cfsSTkZpENzxUA8m.png" /></figure><p>See more outputs in my <a href="https://www.kaggle.com/code/arashnic/gemma3-12b-unsloth-fine-tune-customer-assist/notebook?scriptVersionId=243549020">Kaggle Notebook</a>.</p><p>Key parameters include:</p><ul><li>A TextStreamer from transformers is initialized to allow for real-time streaming of the generated tokens to the console. skip_prompt = True ensures only the model&#39;s generation is printed.</li><li>The model.generate() method is called.</li><li>The input prompt (text_support or text_product) is tokenized, converted to PyTorch tensors, and moved to the GPU (.to(&quot;cuda&quot;)).</li><li>max_new_tokens: Limits the maximum length of the generated response. This was initially 128 and later increased to 1024 for a more detailed product return query.</li><li>temperature: Controls the randomness of the output. (0.8 initially, then 0.7).</li><li>top_p: Nucleus sampling parameter. (0.95 initially, then 0.92).</li><li>top_k: Limits sampling to the K most probable next tokens. (60 initially, then 50).</li><li>streamer: The configured TextStreamer object.</li><li>eos_token_id: The end-of-sequence token ID, ensuring the model stops generating appropriately.</li></ul><h4>3.3.10 Push the model to the hub</h4><p>Finally, the code demonstrates pushing the merged fine-tuned model to the Hugging Face Hub for sharing and wider use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/0*1QQwgfBzYIwfRhRc.png" /></figure><p>UserSecretsClient from kaggle_secrets is used to securely access a Hugging Face API token stored in Kaggle secrets (under the name &quot;Gemma3&quot; in this example).</p><h4>Tips for Testing:</h4><ul><li><strong>Vary Phrasing:</strong> Ask the same underlying question in different ways.</li><li><strong>Introduce Typos:</strong> See how well the model handles minor spelling mistakes.</li><li><strong>Check for Completeness:</strong> Does the answer fully address the question?</li><li><strong>Accuracy:</strong> Is the information provided correct (based on what it was trained on)?</li><li><strong>Tone:</strong> Is the tone appropriate (helpful, empathetic, professional)?</li><li><strong>Hallucinations:</strong> Does it make up information or policies? This is crucial to monitor.</li><li><strong>Actionable Advice:</strong> Does it provide clear steps or information the user can act upon?</li></ul><h3>4. Evaluation</h3><p>After fine-tuning, we can evaluate the model by feeding it <strong>realistic customer queries</strong>. such as :</p><ul><li><em>“Why was I charged an extra fee this month on my bill?”</em></li><li><em>“How can I view my past invoices?”</em></li><li><em>“What is your return policy for items purchased online?”</em></li><li><em>“Are there any discounts available for new customers?”</em></li></ul><p>Feedback &amp; More Complex Interactions:</p><ul><li><em>“If I return this item, will I get a full refund including the shipping cost?”</em></li><li><em>“I need to change the delivery address for an order I just placed. Is that possible?”</em></li></ul><p>For example, using the prompt &quot;I need to return an item I just bought. How do I do that?&quot; produces a step-by-step assistance message (see code). To do this at scale, you could run a set of held-out questions and measure metrics like BLEU or human satisfaction. For quick sanity checks, use the same tokenizer and model.generate() approach as above. Because we used chat-formatting, you can also run multi-turn conversations by alternating &quot;user&quot; and &quot;assistant&quot; messages in model.generate().</p><p>For Automatic evaluation we can use following libraries :<br>evaluate, rouge_score, bert_score</p><pre># !pip install evaluate rouge_score bert_score<br>import evaluate</pre><pre>rouge = evaluate.load(&#39;rouge&#39;)<br>bertscore = evaluate.load(&#39;bertscore&#39;)</pre><pre>predictions = [&quot;your model&#39;s response to query 1&quot;, &quot;response to query 2&quot;]<br>references = [&quot;ideal response to query 1&quot;, &quot;ideal response to query 2&quot;]</pre><pre>rouge_results = rouge.compute(predictions=predictions, references=references)<br># For bertscore, you might need to specify the language<br>bertscore_results = bertscore.compute(predictions=predictions, references=references, lang=&quot;en&quot;) # or your target lang</pre><pre>print(rouge_results)<br>print(bertscore_results)</pre><p><strong>Recommendations for evaluation Customer Support Chatbot:</strong></p><ol><li><strong>Start with Human Evaluation:</strong> Create a diverse test set (~50–100 queries initially) and have humans rate responses on key criteria: Helpfulness, Correctness, Completeness, Tone, and Safety. This will give you the most direct feedback.</li><li><strong>Implement Basic Automatic Metrics:</strong></li></ol><ul><li>If you have reference responses for your test set, track <em>BERTScore</em> and <em>ROUGE-L</em>. Understand their limitations but use them to monitor for large regressions or improvements during development.</li><li>Track <em>Distinct n-grams</em> to monitor response diversity.</li><li>Integrate a <em>safety/toxicity classifier</em> as a safeguard.</li></ul><p><strong>3. Consider LLM-as-a-Judge for Scalability:</strong></p><p>If human evaluation becomes a bottleneck, experiment with using a powerful LLM (like a larger Gemma model from Unsloth’s list, or an API-based model if budget allows) to score responses on your defined criteria. Validate its outputs against human judgments initially.</p><p><strong>4. Focus on Error Analysis:</strong></p><p>Regardless of the metrics, manually review a subset of interactions, especially those flagged as problematic by humans or metrics. Categorize errors to understand where your model is failing and how to improve it (e.g., more specific training data, prompt adjustments for inference, further fine-tuning on failure cases).</p><p><strong>5. Iterate:</strong> Evaluation is not a one-time step. Continuously evaluate as you iterate on your model, data, and prompts.</p><h3>6. Conclusion and Next Steps</h3><p>By fine-tuning Gemma-3 with Unsloth and TRL, we efficiently created a domain-adapted model. This approach required only modest compute (free Kaggle GPUs) yet yields a model specialized on the Bitext dataset’s intents and phrasing.</p><p>Key takeaways: fine-tuning remains a powerful way to inject domain knowledge into LLMs; Unsloth makes that process fast and affordable; and TRL’s SFTTrainer simplifies the code. Next, you could extend this project by training on real conversational logs, adding retrieval/RAG on product data. You could also try <em>instruction-distillation</em> (e.g. DPO) on top of this SFT model to further align responses with human preferences. In any case, Unsloth’s harmony of speed, memory-efficiency, and compatibility makes iterative experimentation tractable.</p><h3>References</h3><ol><li><em>“Introducing Gemma 3: The most capable model you can run on a single GPU or TPU”, Mar 12, 2025. </em><a href="https://blog.google/technology/developers/gemma-3/#:~:text=models%20yet,specific%20hardware%20and%20performance%20needs"><em>blog.google</em></a></li><li><em>Gemma Team, Google DeepMind , </em><a href="https://storage.googleapis.com/deepmind-media/gemma/Gemma3Report.pdf"><em>Gemma 3 Technical Report</em></a><em> , 2025</em></li><li><em>Ju-yeong Ji et al</em><strong><em>. </em></strong><em>Gemma explained: What’s new in Gemma 3 , 2025. </em><a href="https://developers.googleblog.com/en/gemma-explained-whats-new-in-gemma-3/#:~:text=A%20major%20enhancement%20in%20Gemma,model%20to%20interpret%20visual%20input"><em>blog.google</em></a></li><li><em>Clement Farabet et al. “Introducing Gemma 3: The most capable model you can run on a single GPU or TPU,” 2025, </em><a href="https://blog.google/technology/developers/gemma-3/#:~:text=,calling%3A%20Gemma%203%20supports%20function"><em>blog.google</em></a></li><li><em>Michael Tschannen et al. “SigLIP 2: Multilingual Vision-Language Encoders with Improved Semantic Understanding, Localization, and Dense Features “ , 2025</em></li><li><a href="https://docs.unsloth.ai/"><em>Unsloth Documentation</em></a></li><li><a href="https://deepmind.google/models/gemma/gemma-3/"><em>Gemma 3 Official page in DeepMind</em></a></li><li><em>Daniel Han-Chen , “Make LLM Fine-tuning 2x faster with Unsloth and TRL” , 2024. </em><a href="https://huggingface.co/blog/unsloth-trl#:~:text=Unsloth%20works%20by%20overwriting%20some,made%20in%20the%20optimized%20code"><em>huggingface blog</em></a></li><li><em>Joshua Ainslie et al. “GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints “, 2023,</em></li><li><em>Alex Henry et al. “Query-Key Normalization for Transformers“ , 2020 .</em></li><li><em>Daniel &amp; Michael , “ Unsloth — Dynamic 4-bit Quantization” , 2024. </em><a href="https://unsloth.ai/blog/dynamic-4bit"><em>unsloth blog</em></a></li><li><em>Younes B et al. “Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA “ , 2023 , </em><a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes#:~:text=During%20finetuning%2C%20QLoRA%20backpropagates%20gradients,in%20the%20original%20LoRA%20paper"><em>huggingface blog</em></a></li><li><em>Tri Dao , “FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning” , 2023.</em></li><li>Unsloth <a href="https://github.com/unslothai/unsloth">github</a> main page</li><li><em>“PEFT (Parameter-Efficient Fine-Tuning)”, </em><a href="https://huggingface.co/docs/peft/index"><em>huggingface docs</em></a></li><li><em>Tim Dettmers et al. “QLORA: Efficient Finetuning of Quantized LLMs”, 2023. </em><a href="https://arxiv.org/abs/2305.14314"><em>arxiv.org</em></a></li><li><em>Daniel &amp; Michael “Fine-tune &amp; Run Gemma 3”, 2025, </em><a href="https://www.unsloth.ai/blog/gemma3"><em>Unsolsh blog</em></a></li><li><em>Daniel &amp; Michael , “Unsloth Dynamic 2.0 GGUFs”, 2025, </em><a href="https://unsloth.ai/blog/dynamic-v2"><em>Unsolsh blog</em></a></li><li><em>“Unsloth Fine-tuning Guide “, </em><a href="https://docs.unsloth.ai/get-started/fine-tuning-guide"><em>docs.unsloth</em></a></li><li><em>Daniel Han-Chen , “Make LLM Fine-tuning 2x faster with Unsloth and TRL” , 2024. </em><a href="https://huggingface.co/blog/unsloth-trl#:~:text=Unsloth%20works%20by%20overwriting%20some,made%20in%20the%20optimized%20code"><em>huggingface blog</em></a></li><li><em>Triton </em><a href="https://github.com/triton-lang/triton"><em>github</em></a><em> main page</em></li><li><em>Jianlin Su, “ROFORMER: ENHANCED TRANSFORMER WITH ROTARY POSITION EMBEDDING” , 2023</em></li><li><em>“Cut Your Losses in Large-Vocabulary Language Models” , </em><a href="https://github.com/unslothai/cut-cross-entropy"><em>github</em></a></li><li><em>Erik Wijmans et al, “CUT YOUR LOSSES IN LARGE-VOCABULARY LANGUAGE MODELS “ , 2025</em></li><li><em>“The AI CUDA Engineer: Agentic CUDA Kernel Discovery, Optimization and Composition” , 2025 . </em><a href="https://sakana.ai/ai-cuda-engineer/"><em>sakana.ai</em></a></li><li><em>Elias Frantar et al. , “GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers” , 2022</em></li><li><em>llama.cpp </em><a href="https://github.com/ggml-org/llama.cpp"><em>github</em></a><em> main page</em></li><li><em>“vLLM: Easy, Fast, and Cheap LLM Serving with PagedAttention” , </em><a href="https://blog.vllm.ai/2023/06/20/vllm.html"><em>vLLM blog</em></a></li><li><em>TensorRT-LLM </em><a href="https://github.com/NVIDIA/TensorRT-LLM"><em>github</em></a><em> main page</em></li><li><a href="https://blog.spheron.network/comparing-llm-fine-tuning-frameworks-axolotl-unsloth-and-torchtune-in-2025"><em>Comparing LLM Fine-Tuning Frameworks: Axolotl, Unsloth, and Torchtune in 2025</em></a></li><li><em>Unsloth All Models , </em><a href="https://docs.unsloth.ai/get-started/all-our-models"><em>Unsloth Documentation</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e93692d4d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building LLM-Powered QA Recommendation Chatbot with Gemma 2 and Langchain]]></title>
            <link>https://medium.com/@anicomanesh/building-llm-powered-qa-recommendation-chatbot-with-gemma-2-and-langchain-69046f8b7a11?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/69046f8b7a11</guid>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 19:38:58 GMT</pubDate>
            <atom:updated>2025-06-28T17:13:23.978Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Local LLM-Powered Movie Recommendation Chatbot with Gemma 2 and Langchain</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*8JUxTOzD-oRZGqEG.png" /></figure><p>In the rapidly evolving landscape of artificial intelligence, <strong>Large Language Models (LLMs)</strong> have emerged as transformative tools, capable of understanding and generating human-like text across a wide range of domains. Among their many applications, LLMs have shown remarkable potential in <strong>recommender systems</strong>, where their ability to process natural language and contextualize user preferences can revolutionize how we discover and interact with content. This article explores the development of a <strong>local LLM-powered question-answering (QA) recommendation chatbot</strong> using cutting-edge tools like <strong>Gemma 2</strong>, <strong>Llama.cpp</strong>, and <strong>Langchain</strong>, and delves into the customization techniques that make such systems effective.</p><p>This article and project serves as a <strong>blueprint</strong> for leveraging cutting-edge AI tools responsibly. Whether you’re a researcher, engineer, or hobbyist, the code and concepts explored here provide a <strong>springboard for innovation</strong> in personalized AI — one recommendation at a time.</p><h4>The Role of LLMs in Recommender Systems</h4><p>Recommender systems have traditionally relied on collaborative filtering, content-based filtering, and hybrid approaches to predict user preferences. However, these methods often struggle with <strong>cold-start problems</strong>, <strong>sparsity of data</strong>, and the inability to capture nuanced user preferences expressed in natural language. LLMs, with their deep understanding of context and semantics, offer a promising solution. By leveraging their vast knowledge and language capabilities, LLMs can provide <strong>personalized, context-aware recommendations</strong> that go beyond traditional methods.</p><h4>How LLMs Solve the Cold-Start Problem</h4><p>Traditional recommender systems rely on historical user-item interactions to build user profiles and predict item preferences. However, in <strong>cold-start</strong> scenarios, new users and items have limited or no interaction data, making it difficult to model user-item similarity. Traditional methods often depend on content features , graph relations, or domain information to enhance CSR.</p><blockquote>The <strong>cold-start problem</strong> is a well-known challenge in recommender systems, where the system struggles to provide accurate recommendations for new users or items due to a lack of historical data.</blockquote><p>LLMs address this problem in several ways:</p><ul><li><strong>Leveraging World Knowledge</strong>: LLMs are pre-trained on vast amounts of general and domain-specific data, enabling them to infer user preferences even without explicit historical data. For example, if a new user expresses interest in “sci-fi movies with strong female leads,” the LLM can recommend popular titles like <em>Alien</em> or <em>Mad Max: Fury Road</em> based on its understanding of genres, themes, and cultural context.</li><li><strong>Zero-Shot and Few-Shot Learning</strong>: LLMs can generalize from minimal input. For instance, even if a user has no interaction history, the LLM can infer preferences from a single query (e.g., “I like Christopher Nolan movies”) and provide relevant recommendations.</li><li><strong>Natural Language Understanding</strong>: LLMs excel at interpreting unstructured text, such as user reviews, descriptions, or conversational queries. This allows them to extract implicit preferences and make recommendations without relying on explicit ratings or interactions.</li><li><strong>Dynamic Adaptation</strong>: LLMs can adapt to new users and items in real-time by analyzing contextual cues. For example, if a user mentions they enjoy “mind-bending thrillers,” the LLM can immediately recommend movies like <em>Inception</em> or <em>The Matrix</em> without needing prior data.</li></ul><h4>The Case for Local LLMs</h4><p>While cloud-based LLMs like GPT-4 offer unparalleled performance, they come with challenges such as <strong>data privacy concerns</strong>, <strong>latency issues</strong>, and <strong>dependency on external APIs</strong>. Local LLMs, powered by frameworks like <strong>Llama.cpp</strong> and models like <strong>Gemma 2</strong>, provide a compelling alternative. These models can be deployed on local hardware, ensuring <strong>data privacy</strong>, <strong>low latency</strong>, and <strong>full control over customization</strong>. Combined with <strong>Langchain</strong>, a framework for building LLM-powered applications, local LLMs can be seamlessly integrated into recommendation systems.</p><h4>Objective of This Article</h4><p>This article demonstrates how to build a <strong>local LLM-powered QA recommendation chatbot</strong> using <strong>Gemma 2</strong>, <strong>Llama.cpp</strong>, and <strong>Langchain</strong>. We will explore the base implementation, discuss strategies for improving recommendation quality, and highlight the advantages of local LLMs in creating <strong>privacy-preserving</strong>, <strong>efficient</strong>, and <strong>user-centric</strong> recommender systems. By the end of this article, you will have a comprehensive understanding of how to harness the power of LLMs for personalized recommendations and how to adapt these techniques to your own use cases.</p><h3>Building the Movie Recommendation chatbot</h3><p>Lets dive into building a movie recommendation chatbot. In this section, we are going to simulate a cold-start scenario with LangChain and Gemma 2 with Gradio interface and will run it on <strong>CPU </strong>locally. You can find the full code (Base Model) on my <a href="https://www.kaggle.com/code/arashnic/langchain-local-movierec-assistant-v2">Kaggle </a>(For simplicity of loading Gemma 2 i used kaggle notebook (with cpu) because we use the LLM from Kaggle Hub).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*O4yIyGlS1TTnvf9YDnN3lg.png" /><figcaption>Adding dataset and Gemma 2 Model</figcaption></figure><h4>1. Installs the necessary Python libraries for the project.</h4><p>We will use following libraries for implementation:</p><pre>numpy version: 1.26.4<br>pandas version: 2.2.3<br>langchain version: 0.3.19<br>gradio version: 5.20.0<br>faiss-cpu version: 1.10.0<br>torch version: 2.5.1+cu121<br>transformers version: 4.49.0<br>accelerate version: 1.4.0<br>sentence_transformers version: 3.4.1<br>llama-cpp-python version: 0.3.7</pre><ul><li><em>llama-cpp-python: For running quantized </em><strong><em>Gemma-2–9b-it-q4_k_m.gguf</em></strong><em>.</em></li><li><em>langchain: Framework for building LLM-powered applications.</em></li><li><em>faiss-cpu: Library for efficient semantic similarity search.</em></li><li><em>gradio: For creating a user-friendly web interface.</em></li><li><em>transformers and </em><em>sentence-transformers: For generating embeddings.</em></li></ul><p>First install the libraries by Pip:</p><pre>!pip install llama-cpp-python langchain faiss-cpu -q<br>!pip install gradio -q<br>!pip install -U langchain-community accelerate bitsandbytes transformers sentence-transformers -q</pre><h4>2. Importing Libraries</h4><p>If you are beginner in Langchain and RAG , to understand the imports you can refer to <a href="https://python.langchain.com/docs/introduction/">Langchain documentation</a>.</p><pre>import numpy as np <br>import pandas as pd<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings import HuggingFaceEmbeddings<br>from langchain.vectorstores import FAISS<br>from langchain.chains import RetrievalQA<br>from langchain.llms import LlamaCpp<br>from langchain.prompts import PromptTemplate<br>import gradio as gr<br>import ast<br>import os<br>from functools import lru_cache<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><h4>3. Loading and Preprocessing Data</h4><p>We select “<a href="https://www.kaggle.com/datasets/rohan4050/movie-recommendation-data/data">Movie Recommendation Data</a>” from kaggle . The reason for using this dataset is that we need a dataset with a textual description of each movie (alongside information such as ratings and movie titles) so that we can get the embeddings of the text. Lets read the dataset and preprocess important features:</p><pre>data = pd.read_csv(&#39;/kaggle/input/movie-recommendation-data/movies_metadata.csv&#39;)<br>print(&quot;Row data:&quot;)<br>display(data.head().T)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90BEXrH41fKlYpVZKR0rJA.png" /></figure><pre># Convert string representation of dictionaries to actual dictionaries<br>data[&#39;genres&#39;] = data[&#39;genres&#39;].apply(ast.literal_eval)<br><br># Transforming the &#39;genres&#39; column<br>data[&#39;genres&#39;] = data[&#39;genres&#39;].apply(lambda x: [genre[&#39;name&#39;] for genre in x])<br><br><br># Calculate weighted rate (IMDb formula)<br>def calculate_weighted_rate(vote_average, vote_count, min_vote_count=10):<br>    return (vote_count / (vote_count + min_vote_count)) * vote_average + (min_vote_count / (vote_count + min_vote_count)) * 5.0<br><br># Minimum vote count to prevent skewed results<br>vote_counts = data[data[&#39;vote_count&#39;].notnull()][&#39;vote_count&#39;].astype(&#39;int&#39;)<br>min_vote_count = vote_counts.quantile(0.95)<br><br># Create a new column &#39;weighted_rate&#39;<br>data[&#39;weighted_rate&#39;] = data.apply(lambda row: calculate_weighted_rate(row[&#39;vote_average&#39;], row[&#39;vote_count&#39;], min_vote_count), axis=1)<br>data = data.dropna()<br>data = data[[&#39;genres&#39;, &#39;title&#39;, &#39;overview&#39;, &#39;weighted_rate&#39;]].reset_index(drop=True)<br><br><br># Create a new column by combining &#39;title&#39;, &#39;overview&#39;, and &#39;genre&#39;<br>data[&#39;combined&#39;] = data.apply(lambda row: f&quot;Title: {row[&#39;title&#39;]}. Overview: {row[&#39;overview&#39;]} Genres: {&#39;, &#39;.join(row[&#39;genres&#39;])}. Rating: {row[&#39;weighted_rate&#39;]}&quot;, axis=1)<br>print(&quot;&quot;&quot;<br>Prepared data:&quot;&quot;&quot;)<br>display(data.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*GCNkUnSR_Jo2_28TY6LiGQ.png" /></figure><h4>4. Embedding</h4><p>In this step we must generates<a href="https://medium.com/@rahultiwari065/unlocking-the-power-of-sentence-embeddings-with-all-minilm-l6-v2-7d6589a5f0aa#:~:text=all%2DMiniLM%2DL6%2Dv2%20is%20a%20compact%20but%20powerful,Clustering%20(grouping%20sentences%20by%20meaning)"> embeddings</a> for the text chunks using the <a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">all-MiniLM-L6-v2</a> model, stores the embeddings in a <a href="https://github.com/facebookresearch/faiss"><strong>FAISS</strong></a> <a href="https://www.datacamp.com/blog/the-top-5-vector-databases">vector store</a> for efficient similarity search and saves the FAISS index for reuse.</p><pre><br>def get_vectorstore():<br>    &quot;&quot;&quot;Cache FAISS index to avoid recomputing&quot;&quot;&quot;<br>    data = pd.read_csv(&#39;/kaggle/input/movie-recommendation-data/movies_metadata.csv&#39;)<br>    <br>    # Preprocessing pipeline<br>    data[&#39;genres&#39;] = data[&#39;genres&#39;].apply(ast.literal_eval).apply(lambda x: [g[&#39;name&#39;] for g in x])<br>    data = data.dropna(subset=[&#39;vote_count&#39;, &#39;vote_average&#39;])<br>    <br>    # IMDb formula for weighted rating<br>    C = data[&#39;vote_average&#39;].mean()<br>    m = data[&#39;vote_count&#39;].quantile(0.90)<br>    data = data[data[&#39;vote_count&#39;] &gt;= m]<br>    data[&#39;weighted_rate&#39;] = (data[&#39;vote_count&#39;] / (data[&#39;vote_count&#39;] + m)) * data[&#39;vote_average&#39;] + (m / (data[&#39;vote_count&#39;] + m)) * C<br>    <br>    # Create text chunks with metadata<br>    text_splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=512,  # Reduced from 1024 for better retrieval speed<br>        chunk_overlap=30<br>    )<br>    texts = text_splitter.split_text(&quot;\n&quot;.join(<br>        f&quot;Title: {row[&#39;title&#39;]}. Plot: {row[&#39;overview&#39;]}. Genres: {&#39;, &#39;.join(row[&#39;genres&#39;])}. Rating: {row[&#39;weighted_rate&#39;]:.1f}&quot;<br>        for _, row in data.iterrows()<br>    ))<br>    <br>    # Create FAISS index with metadata<br>    embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>    return FAISS.from_texts(texts, embeddings)<br><br>vectorstore = get_vectorstore()<br>vectorstore.save_local(&quot;movie_faiss_index&quot;)</pre><h4><strong>5. Load Gemma-2–9b-it GGUF and Set Up RetrievalQA Chain</strong></h4><p>While many LLMs are traditionally accessed via cloud services, there’s a growing trend and interest in running local AI models on personal computers or servers. This shift is driven by considerations such as privacy, reduced latency, and the ability to work offline.</p><p><a href="https://huggingface.co/docs/transformers/en/gguf"><strong>GGUF (GPT-Generated Unified Format)</strong></a> is a specialized file format designed for the efficient storage and deployment of large language models (LLMs). It serves as an evolution of the earlier <strong>GGML</strong> format, addressing the need for a more standardized and versatile approach to handling LLM data.</p><p><strong>Key Features of GGUF:</strong></p><ul><li><strong>Unified Storage:</strong> GGUF consolidates tensors and metadata into a single binary file, simplifying model management and deployment.</li><li><strong>Quantization Support:</strong> The format supports various quantization levels, ranging from 2-bit to 8-bit integers, as well as standard floating-point formats like float32 and float16. This flexibility allows for reduced memory usage and faster inference times, albeit with some trade-offs in model precision.</li><li><strong>Comprehensive Metadata:</strong> GGUF files encapsulate essential information required for running GPT-like language models, including tokenizer vocabularies, context lengths, and tensor details.</li></ul><p>The development of <strong>GGUF</strong> is closely tied to the evolution of <strong>llama.cpp</strong>. Initially, llama.cpp utilized the <strong>GGML</strong> format for model storage. However, as the need for a more standardized and efficient format became apparent, GGUF was introduced. This new format offers better support for various quantization methods and ensures backward compatibility, enhancing the library’s flexibility and performance.</p><p>By adopting GGUF, llama.cpp can efficiently load and execute LLMs, benefiting from reduced memory requirements and accelerated inference times. This integration makes it feasible to run complex language models on devices with limited resources, broadening the accessibility and applicability of LLMs across diverse platforms.</p><p>So we will load the “<strong>Gemma-2–9b-it</strong>” model in GGUF format for generating responses from kaggke hub.</p><p><a href="https://www.kaggle.com/models/paultimothymooney/gemma-2-9b-it">Paul Mooney | gemma-2-9b-it | Kaggle</a></p><pre>import os<br># Load Gemma-2-9b-it GGUF<br>llm = LlamaCpp(<br>    model_path=&quot;/kaggle/input/gemma-2-9b-it/gguf/q4_k_m/1/gemma-2-9b-it-q4_k_m.gguf&quot;,<br>    temperature=0.3,       # Lower temp for more deterministic answers<br>    max_tokens=256,        # Allow longer responses<br>    n_ctx=2048,            # Increased context for better understanding<br>    n_threads=os.cpu_count(),  # Fully utilize all CPU cores<br>    n_batch=2048,           # Optimized batch size for smoother inference<br>    use_mlock=True,        # Lock model in RAM to prevent slow disk access<br>    use_mmap=True,         # Improve performance by memory-mapping the model<br>    verbose=False<br>)<br><br># Custom prompt template<br><br>prompt_template = &quot;&quot;&quot;<br>You are an expert movie recommender. For user queries about actors/directors/genres:<br>1. Suggest 3 SPECIFIC movies with YEAR and LEAD ACTORS<br>2. Include 1 to 3-sentence descriptions<br>3. Explain WHY they match the request<br>4. NEVER suggest irrelevant movies<br><br>Example good response:<br>&quot;Here are great Russell Crowe movies:<br>- Gladiator (2000): A former Roman general seeks revenge on the corrupt emperor who murdered his family and sentenced him to slavery. Features Crowe&#39;s iconic performance.<br>- A Beautiful Mind (2001): A Beautiful Mind is a 2001 American biographical drama film about the mathematician John Nash, a Nobel Laureate in Economics, played by Russell Crowe. Crowe won an Oscar for this role.<br>Why recommended? All showcase Crowe&#39;s range in historical dramas and character-driven stories.&quot;<br><br>Context: {context}<br>Question: {question}<br>Answer:&quot;&quot;&quot;<br>qa_chain = RetrievalQA.from_chain_type(<br>    llm=llm,<br>    chain_type=&quot;stuff&quot;,<br>    retriever=vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 3}), <br>    chain_type_kwargs={&quot;prompt&quot;: PromptTemplate.from_template(prompt_template)},<br>    return_source_documents=False  # Disable unused metadata<br>)</pre><p>Here’s a detailed explanation of the parameters used in the LlamaCpp configuration for the movie recommendation chatbot. These settings control the behavior of the Gemma 2B LLM and <strong>optimize performance</strong> for the Kaggle environment:</p><ul><li><em>max_tokens: Limits the maximum number of tokens (words/subwords) the model generates.</em></li><li><em>n_ctx: Sets the context window size (in tokens) the model can process.</em></li><li><em>use_mlock: Locks the model in RAM to prevent disk swapping. This Improves performance by avoiding slow disk access but Requires sufficient RAM (Max 30 GiB on Kaggle Notebook).</em></li><li><em>use_mmap: Memory-maps the model file for faster loading. This parameter reduces initial load time and memory footprint. Works well with large models like Gemma 2B.</em></li></ul><p><strong>Key Tradeoffs and Optimizations</strong></p><ul><li><strong><em>CPU vs. GPU</em></strong><em>: Since we want to deploy on Kaggle CPU , these settings optimize for CPU performance (</em><em>n_threads, </em><em>n_batch, </em><em>use_mlock).</em></li><li><strong><em>Quality vs. Speed</em></strong><em>: The </em><em>q4_k_m quantization and </em><em>temperature=0.3 prioritize speed and reliability over creativity.</em></li><li><strong><em>Memory Management</em></strong><em>: </em><em>use_mmap=True and </em><em>use_mlock=True ensure efficient RAM usage for large models.</em></li></ul><h4><strong>6. Launching the Gradio Interface</strong></h4><p>In this part of code we processes user queries and generates recommendations using the RetrievalQA chain by extracting movie titles and overviews from the retrieved documents and formats the response. Finally we create a simple user-friendly chatbot interface using <a href="https://www.gradio.app/docs">Gradio</a> and provides example queries to guide users.</p><pre>def handle_conversation(message, history):<br>    <br>    #if not history:<br>        # This will appear as FIRST message in chat<br>        # return &quot;Welcome to MovieMaster! What kind of movies would you like today?&quot;<br>    <br>    # Process subsequent messages normally<br>    result = qa_chain({&quot;query&quot;: message})<br>    return result[&quot;result&quot;]<br><br><br># Launch Gradio interface<br>demo = gr.ChatInterface(<br>    fn=handle_conversation,<br>    title=&quot;MovieMaster 🎬&quot;,<br>    description=&quot;Your AI-powered movie recommendation assistant&quot;,<br>    examples=[<br>        &quot;I like sci-fi movies with strong female leads&quot;,<br>        &quot;Recommend something similar to Inception&quot;, <br>        &quot;What are the best movies about AI from 2010s?&quot;<br>    ],<br>    chatbot=gr.Chatbot(<br>        value=[],  # Start with empty history<br>        height=&quot;calc(100vh - 200px)&quot;,  # Dynamic height (viewport minus header/footer)<br>        container=True,  # Allow chatbox to expand within its container<br>    ),<br>    theme=gr.themes.Soft(),<br>     <br>)<br>demo.launch(share=True)</pre><p>output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mF-JNQZhI-xgp7YBZ8lr0g.png" /></figure><p>If we run the app via gradio.live :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aE4Z_pj-Up_qT1E7KF6PHQ.png" /></figure><p>Lets start with some quastions :</p><p>👤 : Recommend something similar to Inception</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*rBB1Tlw_0E-Ok919LB6O6w.png" /><figcaption>🤖 Response to : “Recommend something similar to Inception”</figcaption></figure><p>👤: What are the best movies of Russell Crowe?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*pxJ0sddREqBwTSRVKQR6_A.png" /><figcaption>🤖 Response to : “What are the best movies of Russell Crowe?n”</figcaption></figure><p>Now lets follow a structured functional test .I categorized them for clarity(For evaluation and metrics refer to “<a href="https://www.confident-ai.com/blog/llm-chatbot-evaluation-explained-top-chatbot-evaluation-metrics-and-testing-techniques">LLM Chatbot Evaluation Explained: Top Metrics and Testing Techniques</a>”):</p><p><strong>I. Basic Recommendation Functionality</strong></p><p>We will verify that the chatbot can provide movie recommendations based on simple criteria.</p><p><strong>Test Questions:</strong></p><ul><li>“Recommend a good action movie.”</li><li>“Suggest some comedies.”</li><li>“What are some science fiction films?”</li><li>“Recommend a horror movie.”</li><li>“I want to watch a romantic movie.”</li></ul><p><strong>Expected Results:</strong></p><ul><li>The chatbot provides a list of 3–5 movies matching the genre.</li><li>Each movie entry includes the title, year, and lead actors.</li><li>A 1–3 sentence description of the movie is included.</li><li>A brief explanation of why the movie fits the genre is provided.</li></ul><p>👤 Suggest some comedies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laQR_8g8PvteTJxrIJX7bw.png" /><figcaption>🤖 “Suggest some comedies” response, Gradio default theme</figcaption></figure><p>The Lost City(2022), Game Night(2018) and 21Jump Street(2012) are all match with the question.</p><p><strong>II. Actor/Director-Based Recommendations</strong></p><p>Test if the chatbot can suggest movies featuring specific actors or directed by specific directors.</p><p><strong>Test Questions:</strong></p><ul><li>“Movies with Tom Hanks.”</li><li>“Recommend movies starring Leonardo DiCaprio.”</li><li>“What movies did Christopher Nolan direct?”</li><li>“Suggest films directed by Quentin Tarantino.”</li><li>“What movies star Meryl Streep?”</li></ul><p><strong>Expected Results:</strong></p><ul><li>The chatbot provides movies featuring the specified actor/director.</li><li>The format is consistent: title, year, lead actors (if applicable, if not a director search), description, justification.</li><li>The justification highlights the actor/director’s role in the movie.</li></ul><p>👤 What movies did Christopher Nolan direct?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*LsoS3dHcQQknIrftjCoEsA.png" /><figcaption>🤖 Response to : “What movies did Christopher Nolan direct?”</figcaption></figure><p>Inception(2010) , The Dark Knight (2008) and Interseller(2014) suggested by the assistant are my favorite movies from Nolan!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCz4lTAG5N6f6IGvOiM_1A.png" /></figure><p><strong>III. Combined Criteria (Genre + Actor/Director)</strong></p><p>Test the chatbot’s ability to handle combined queries.</p><p><strong>Test Questions:</strong></p><ul><li>“Action movies with Tom Cruise.”</li><li>“Comedies directed by Woody Allen.”</li><li>“Science fiction films starring Sigourney Weaver.”</li><li>“Romantic movies with Julia Roberts.”</li><li>“Horror movies directed by John Carpenter.”</li></ul><p><strong>Expected Results:</strong></p><ul><li>The recommendations must satisfy <em>both</em> criteria (genre <em>and</em> actor/director).</li><li>The justification should explain why the movie fits <em>both</em> criteria.</li></ul><p>👤 Romantic movies with Julia Roberts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*zYaP7ay90vTGj4G6KLEsSQ.png" /><figcaption>🤖 Response to : “Romantic movies with Julia Roberts”</figcaption></figure><p><strong>IV. “Similar To” Recommendations</strong></p><p>Assess the chatbot’s ability to understand and provide recommendations based on similarity to a known movie.</p><p><strong>Test Questions:</strong></p><ul><li>“Recommend something similar to Inception.”</li><li>“What are some movies like The Matrix?”</li><li>“Suggest movies similar to Pulp Fiction.”</li><li>“I want to watch something like Gladiator.”</li><li>“What’s a movie similar to Forrest Gump?”</li></ul><p><strong>Expected Results:</strong></p><ul><li>The chatbot recommends movies that share similar themes, genres, or tones with the reference movie.</li><li>The justification should clearly explain <em>why</em> the recommended movie is similar to the reference movie.</li></ul><p>👤 What’s a movie similar to Forrest Gump?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*aDja6wXOww1O7aNJg-l16w.png" /><figcaption>🤖 Response to: “What’s a movie similar to Forrest Gump?”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjWuuut2AmxyWuDjYUVu0Q.png" /></figure><p>This question “What’s a movie similar to Forrest Gump?” is complicated but i think what recommended by the chatbot is relevant philosophically!</p><p><strong>V. Time-Based Recommendations</strong></p><p>Ensure that the chatbot can filter movies by release year or decade.</p><p><strong>Test Questions:</strong></p><ul><li>“What are the best romantic movies from the 1990s?”</li><li>“Recommend sci-fi films from the 1990s.”</li><li>“Suggest a good comedy from 2010.”</li><li>“What were some great action movies from 2005?”</li><li>“Suggest horror movies from 1970s.”</li></ul><p><strong>Expected Results:</strong></p><ul><li>All recommended movies should fall within the specified time period.</li></ul><p>👤 Recommend some top movies about Artificial intelligence form 2020s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkfxAQD5GjrD40A3gmq9LA.png" /><figcaption>🤖 Response to “Recommend some top movies about Artificial intelligence form 2020s”</figcaption></figure><p>👤 Recommend sci-fi films from the 2000s:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*7gtnIj_rga3mmJBZ26yl7w.png" /><figcaption>🤖 Response to “Recommend sci-fi films from the 2000s:”</figcaption></figure><p><strong>Test Questions:</strong></p><ul><li>“Recommend a good movie.”</li><li>“What should I watch tonight?”</li><li>“Suggest something interesting.”</li></ul><p><strong>Expected Results:</strong></p><ul><li>The chatbot should provide a general recommendation, possibly based on popular movies or a mix of genres.</li><li>The response should still adhere to the standard format (title, year, description, justification).</li></ul><p>👤 Suggest something intresting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*GUFiy8SEZC2SPzuVYRU-1A.png" /><figcaption>🤖 Response to: Suggest something intresting</figcaption></figure><p><em>Why recommended?</em></p><p><em>“ These films combine your preferred genres, offering exciting stories with unique twists on sci-fi tropes.”</em></p><p>Although we just use FAISS but look like the chatbot is considering my interest based on my previous questions in chat session . We will discuss about the langchain memory and conversational chat latare. During the improvement we willl apply, we don’t need to change our embedding for popular recommendation because our improvement will transform our QA to a conversational personalized chatbot.</p><p><strong>VI. Negative Testing (Edge Cases and Error Handling)</strong></p><p>Test how the chatbot handles invalid or unexpected input.</p><p><strong>Test Questions:</strong></p><ul><li>“Movies with Xyzzy Blorf” (made-up actor).</li><li>“Recommend a movie set on Mars in the 17th century.”</li><li>“Movie wth Tom Hankz” (typo).</li><li>“Give me all the movies ever made.” (overly broad query).</li><li>“What is the meaning of life?” (irrelevant query).</li></ul><p><strong>Expected Results:</strong></p><ul><li>The chatbot should handle the error gracefully. Avoid crashing or giving nonsensical results.</li><li>For unknown actors/directors: A polite message indicating that no movies were found.</li><li>For impossible scenarios: A message indicating that no movies matching the criteria could be found.</li><li>For irrelevant queries: A message gently redirecting the user to a movie-related topic.</li></ul><p>👤 What is the meaning of life:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*hMk8wXAmq4oM5mREcsBfuw.png" /><figcaption>🤖 Response to : “Suggest something intresting”</figcaption></figure><p>Intresting ! While our base solution is simple but the chatbot is surprising us! The chatbot redirected us to a movie-related topic.</p><p>Other test cases:</p><ul><li>The chatbot didn’t provide any response to questions like: <strong><em>“Movies with Xyzzy Blorf”</em></strong> .Improvment of the prompt will be solve this issue.</li><li>The chatbot crashed on this question. <strong><em>“Give me all the movies ever made.”</em></strong></li></ul><p><strong>Reasons for the Crash:</strong></p><p><strong>Resource Exhaustion:</strong> The most probable cause is that the query overloads the system’s resources. Here’s why:</p><ul><li><strong>Vectorstore Retrieval:</strong> The query likely triggers the retrieval of <em>a very large number</em> of documents from your vectorstore. The retriever component in your RetrievalQA chain is likely trying to find all documents relevant to the query.</li><li><strong>Context Window Overflow:</strong> The LlamaCpp model has a context window size (n_ctx=2048). If the combined length of the retrieved documents and the prompt exceeds this limit, the model will either crash or produce unpredictable results. This can cause the chain to hang indefinitely while trying to process a giant context.</li><li><strong>Memory Issues:</strong> Processing a massive amount of text can easily exhaust available memory, especially on resource-constrained environments like Kaggle notebooks.</li></ul><p><strong>Inefficient Retrieval:</strong> Even if it doesn’t fully crash, the retrieval process might become extremely slow and inefficient, effectively causing the chatbot to become unresponsive.</p><p>a) A simple solution is improving the Prompt (Add Specificity). Modify the prompt to discourage the chatbot from trying to list <em>all</em> movies. Add a constraint.</p><pre>... (existing prompt) ...<br><br>IMPORTANT:  If the user asks for &quot;all movies,&quot; &quot;every movie,&quot; or <br>something similar, DO NOT try to list every movie.  <br>Instead, suggest a few popular movies from different genres.  <br>Explain that listing all movies is not possible.</pre><p>Also we can try following changes:</p><p>b) <strong>Add a Pre-Retrieval Filter in handle_conversation</strong></p><p>Check the user’s query <em>before</em> sending it to the qa_chain. If the query is too broad, return a canned response.</p><pre>def handle_conversation(message, history):<br>    message = message.lower() # Normalize input<br>    if &quot;all movies&quot; in message or &quot;every movie&quot; in message:<br>        return &quot;I cannot list all movies ever made. The database is too large. Instead, I can suggest some popular movies from different genres. What genres are you interested in?&quot;<br><br>    # Cold-start handling<br>    if not history:<br>        return &quot;Welcome to MovieMaster! What kind of movies would you like to discover today?&quot;<br><br>    # Get recommendation<br>    result = qa_chain({&quot;query&quot;: message})<br>    response = result[&quot;result&quot;]<br><br>    return response</pre><h3>Potential Improvements</h3><h4><strong>1. Enhance FAISS Search for Better Recommendations</strong></h4><p>FAISS has many indexing methods. The simplest ones (like IndexFlatL2 or IndexFlatIP) perform an <strong>exhaustive search</strong> — that is, they compare the query vector against every stored vector. While this guarantees an exact match, it doesn’t scale well with large datasets and may not generalize as well for recommendation tasks. With current code we <strong>only retrieve exact matches</strong>, which can lead to <strong>poor generalization</strong>. Using <a href="https://www.youtube.com/watch?v=QvKMwLjdK-s"><strong>FAISS with HNSW</strong></a> (Hierarchical Navigable Small World), which is <strong>faster and more accurate</strong>.</p><p>In fact instead of returning only the “exact” closest matches, HNSW may return items that are <em>approximately</em> similar, which can lead to more diverse and sometimes more interesting recommendations.</p><h4><strong>2. Smarter Chatbot Responses with Contextual Awareness</strong></h4><p>FAISS is great at finding similar movies, but it does <strong>not track what the user said before</strong>. Without memory, the chatbot can <strong>forgets user preferences</strong> and may ask redundant questions.</p><p>👤 <strong>User:</strong> <em>“Recommend a sci-fi movie.”</em><br>🤖 <strong>Bot:</strong> <em>“You might like Inception or Interstellar.”</em></p><p>👤 <strong>User:</strong> <em>“I want something with time travel.”</em><br>🤖 <strong>Bot:</strong> <em>“What kind of movies do you like?”</em> ❌ (<em>Forgets past preference!</em>)</p><p>LangChain provides several powerful capabilities to add memory to chatbots, enabling them to maintain context and have more natural, conversational interactions. Here’s a breakdown of the key memory components in LangChain:</p><p><strong>Memory Abstractions:</strong></p><p><strong>ConversationBufferMemory:</strong></p><p>This is the simplest form of memory. It stores the entire conversation history in a buffer. It’s useful for short conversations where you want to keep track of everything.But It can become inefficient for long conversations as the context grows.</p><p><strong>ConversationBufferWindowMemory:</strong></p><p>This memory keeps a sliding window of the most recent interactions. You can define the k parameter to specify the number of interactions to keep.</p><p>It helps manage context length and avoids overwhelming the model with too much information.</p><p><strong>ConversationSummaryMemory:</strong></p><p>This memory summarizes the conversation over time. This is effective for long conversations, as it maintains a high-level understanding of the context.</p><p><strong>ConversationSummaryBufferMemory:</strong></p><p>A combination of ConversationBufferWindowMemory and ConversationSummaryMemory. It keeps a buffer of recent interactions, and when that buffer exceeds a certain length, it summarizes the older interactions.</p><p><strong>ConversationTokenBufferMemory:</strong></p><p>This memory keeps a buffer of recent interactions and keeps the memory under a set token limit. This protects from exceeding the LLM context window.</p><p><strong>ConversationKGMemory:</strong></p><p>This memory stores the conversation as a knowledge graph. It extracts entities and relationships from the conversation, allowing the chatbot to reason about the information and is useful for chatbots that need to understand complex relationships between entities.</p><p><strong>VectorStoreRetrieverMemory:</strong></p><p>This memory stores conversation history in a vector database. This is particularly useful for chatbots that need to access specific information from long conversations.</p><p><strong>Integration with Chains:</strong></p><ul><li>LangChain memory components are designed to be easily integrated with chains.</li><li>You can pass a memory object to a chain, and the chain will automatically use the memory to store and retrieve conversation history.</li><li>This allows you to create complex conversational flows with persistent context.</li></ul><p>In a <strong>traditional recommendation system</strong>, user history (e.g., past ratings, watch history) helps <strong>personalize recommendations</strong>. With <strong>LangChain memory</strong>, we achieve something similar:</p><ul><li><strong>Remembers past questions</strong> (<em>e.g., “I like sci-fi movies”</em>)</li><li><strong>Adapts recommendations over time</strong> (<em>e.g., suggests more sci-fi movies based on conversation history</em>)</li><li><strong>Avoids asking redundant questions</strong> (<em>e.g., won’t repeatedly ask for preferences if already given</em>)</li></ul><p>Conversation sample:</p><p><strong>User:</strong> <em>“Recommend a sci-fi movie.”</em><br><strong>Bot:</strong> <em>“You might like Inception or Interstellar.”</em></p><p><strong>User:</strong> <em>“I want something with time travel.”</em><br><strong>Bot:</strong> <em>“Got it! You’re looking for a sci-fi movie with time travel. Here are some: Tenet, Predestination, and Primer.”</em> ✅</p><p><strong>User:</strong> <em>“Maybe something with a more complex storyline?”</em><br><strong>Bot:</strong> <em>“I see! You prefer deep, complex sci-fi time travel movies. You might enjoy Arrival, Donnie Darko, or 12 Monkeys.”</em> ✅ (<em>Adapts recommendations!</em>)</p><p><strong>User:</strong> <em>“That sounds great! What about something lighter but still sci-fi?”</em><br><strong>Bot:</strong> <em>“Sure! For a lighter sci-fi experience with time travel, try Back to the Future, The Adam Project, or Palm Springs.”</em> ✅ (<em>Understands user intent!</em>)</p><p>If you add memory to our generative QA chatbot using <strong>ConversationBufferMemory</strong>you can start a short conversation as following example.</p><p>👤 Sample Query: Recommend me some action movies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*UT7d5_f0noB3okz5qmCz_Q.png" /><figcaption>🤖 Response to :”Recommend me some action movies”</figcaption></figure><p>👤 Second conversational question: Which one has the best car chases?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*u0T_Rvveys64w2gU7ClTWg.png" /><figcaption>🤖 Response to “Which one has the best car chases?” : While all three genres can feature car chases, the <strong>Crime, Thriller genre</strong> with a rating of 5.7 is most likely to have them.Think about classic crime thrillers like “The French Connection” or “Drive.” They often use high-octane car chases as part of their suspenseful narratives.</figcaption></figure><blockquote><strong>Note:</strong></blockquote><blockquote>It is impoerant to understand the differences between <strong>generative QA</strong>, and <strong>conversational </strong>tasks. These are distinct types of tasks in natural language processing (NLP), each with its own characteristics, challenges, and use cases.</blockquote><blockquote>In <strong>generative QA</strong>, the model generates a free-form answer to a question, which may or may not be a direct excerpt from the context. The answer can include new text or rephrased information.</blockquote><blockquote><strong>Input</strong>: A question and (optionally) a context. <strong>Output</strong>: A free-form text answer.</blockquote><blockquote><strong>Example</strong>:</blockquote><blockquote><strong>Context</strong>: “The Eiffel Tower is located in Paris, France. It was completed in 1889.”</blockquote><blockquote><strong>Question</strong>: “Tell me about the Eiffel Tower.” <strong>Answer</strong>: “The Eiffel Tower is a famous landmark in Paris, France, completed in 1889.”</blockquote><blockquote><strong>Conversational</strong> tasks involve interactive, multi-turn dialogues between a user and a model. The model must maintain context across turns and generate coherent, contextually relevant responses.</blockquote><blockquote><strong>Input</strong>: A conversation history (multiple turns of user and system messages).</blockquote><blockquote><strong>Output</strong>: A response that continues the conversation.</blockquote><blockquote><strong>Example</strong>:</blockquote><blockquote><strong>User</strong>: “What is the capital of France?” <strong>Model</strong>: “The capital of France is Paris.”</blockquote><blockquote><strong>User</strong>: “What is it known for?” <strong>Model</strong>: “Paris is known for its art, culture, and landmarks like the Eiffel Tower.”</blockquote><p>So by adding langchain memory we can say we change the problem/task from generative to conversational.</p><h4><strong>3. Deploy as a System Service (Linux) locally</strong></h4><p>Download the GGUF Model Locally from kaggle :</p><p><a href="https://www.kaggle.com/models/paultimothymooney/gemma-2-9b-it?select=gemma-2-9b-it-q4_k_m.gguf">Paul Mooney | gemma-2-9b-it | Kaggle</a></p><pre>wget https://www.kaggle.com/models/paultimothymooney/gemma-2-9b-it?select=gemma-2-9b-it-q4_k_m.gguf</pre><p>Or you can test othe appropriate models from huggingface like:</p><ul><li>google/gemma-2–2b-it-GGUF</li><li>TheBloke/zephyr-7B-beta-GGUF</li><li>TheBloke/Mistral-7B-Instruct-v0.2-GGUF</li></ul><pre>wget https://huggingface.co/google/gemma-2-2b-it-GGUF/resolve/main/gemma-2-2b-it-Q4_K_M.gguf -O gemma-2b-it.gguf<br></pre><p>Move the model to a specific folder (e.g., models folder in your project):</p><pre>mkdir -p models<br>mv gemma-2b-it.gguf models/</pre><p>Now, create a python script <strong>chatbot.py</strong> with the provided code and run the chatbot using <strong>nohup</strong> to keep it alive even if you close your terminal:</p><pre>nohup python chatbot.py &amp;</pre><p>or :</p><pre>nohup python chatbot.py &gt; chatbot.log 2&gt;&amp;1 &amp;</pre><p><strong>This </strong>Keeps Gradio running even after you log out and <strong>Generates a Gradio live link that persists</strong> (as long as your machine is on).</p><p>You can check logs anytime:</p><pre>tail -f nohup.out</pre><p><strong>Access the Chatbot</strong></p><ul><li>Open <strong>http://localhost:7860</strong> on your web browser (<strong>for local access</strong>).</li><li>Use the <strong>Gradio live link</strong> provided in the terminal (<strong>for global access</strong>).</li></ul><p>If you need g<strong>radio.live to work persistently</strong>, consider running the script as a <strong>systemd service</strong> on <strong>Linux</strong> or <strong>as a background process on Windows</strong>.</p><p>On Linux (systemd) , create a systemd service file:</p><pre>sudo nano /etc/systemd/system/moviemaster.service</pre><p>Add the following:</p><pre>[Unit]<br>Description=MovieMaster Chatbot<br>After=network.target<br><br>[Service]<br>ExecStart=/usr/bin/python3 /path/to/chatbot.py<br>WorkingDirectory=/path/to/<br>Restart=always<br>User=your-username<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Enable and start the service:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable moviemaster<br>sudo systemctl start moviemaster</pre><h3>4. Training and Inference</h3><p>Although we deployed our chatbot locally but we can to split our code into two parts , training and inference , even if we’re not “training” the language model in the traditional sense. In retrieval-augmented systems like a movie recommender using LangChain and a GGUF LLM, we can structure our workflow as follows:</p><h4>A. Offline “Training” (Index Building / Preprocessing)</h4><p>This step is analogous to “training” in that we perform a heavy, one-time (or periodic) computation. Once complete, our index is ready and doesn’t need to be rebuilt for every user query.</p><ul><li><strong>Data Processing: </strong>Load and clean the movie metadata and Process fields (e.g., genres, titles, overviews) and compute a combined text representation for each movie.</li><li><strong>Embedding Generation: </strong>Compute embeddings for each movie using a pre-trained SentenceTransformer model.</li><li><strong>Index Building: </strong>Build a FAISS index (using HNSW or another index type) from these embeddings.</li><li><strong>Persistence: </strong>Save the FAISS index (and optionally the processed data) to disk for later use.</li></ul><h4>B. Online Inference (Serving)</h4><p>This step is our online inference or “serving” stage, where incoming queries are answered quickly by leveraging the precomputed index and loaded LLM.</p><ul><li><strong>Load Precomputed Resources: </strong>Load the pre-built FAISS index and the processed movie data and Load the pre-trained GGUF model via llama.cpp.</li><li><strong>Conversational Chain: </strong>Use LangChain’s retrieval and conversational mechanisms (with memory if you added ) to generate recommendations in response to user queries.</li><li><strong>User Interaction: </strong>Serve queries in real time through a Gradio interface or another deployment method.</li></ul><h3><strong>Conclusion</strong></h3><p>The integration of <strong>Large Language Models (LLMs)</strong> into recommender systems represents a paradigm shift in how we approach personalized content discovery. By combining the power of <strong>Gemma 2</strong>, the efficiency of <strong>Llama.cpp</strong>, and the flexibility of <strong>LangChain</strong>, we’ve demonstrated how to build a <strong>privacy-preserving, locally deployable movie recommendation chatbot</strong> that addresses key challenges like the cold-start problem and data sparsity.</p><h3>Future Directions</h3><p>While this implementation provides a strong foundation, several avenues for improvement remain:</p><ul><li><strong>Personalization</strong>: Incorporate user feedback loops (e.g., thumbs-up/down ratings) to refine recommendations dynamically.</li><li><strong>Multimodal Recommendations</strong>: Expand beyond movies to include books, music, or products by integrating multimodal embeddings.</li><li><strong>Efficiency Optimization</strong>: Experiment with smaller LLMs (e.g., Phi-3) or quantization techniques to reduce hardware requirements.</li><li><strong>Domain Adaptation</strong>: Pre-train or fine-tune the LLM on domain-specific datasets (e.g., IMDb reviews) to enhance recommendation quality.</li></ul><h3>Final Thoughts</h3><p>The era of LLM-powered recommender systems is just beginning. As models grow more efficient and frameworks like LangChain mature, the barrier to building sophisticated, user-centric recommendation engines will continue to lower. By prioritizing <strong>local deployment</strong>, <strong>privacy</strong>, and <strong>interpretability</strong>, developers can create systems that not only recommend content but also empower users with transparency and control.</p><p>If you need to learn more about LLMs Fundamentals read my article: <em>“The Rise of Language Giants: How LLMs are Transforming Healthcare: </em><a href="https://medium.com/@anicomanesh/the-rise-of-language-giants-how-llms-are-transforming-healthcare-a9d4b54164ec"><em>Part I : A Comprehensive Guide to LLMs Fundamentals”</em></a></p><p><em>And please feel free to connect with me on ,</em><a href="https://www.linkedin.com/in/arashnicoomanesh/"><em> LinkedIn</em></a><em> , </em><a href="https://www.kaggle.com/arashnic"><em>Kaggle</em></a><em> or </em><a href="https://x.com/ANicoomanesh"><em>X</em></a><em> .</em></p><h4>References</h4><ol><li><em>Matthijs Douze FAIR, Meta et al. (2025) ,” THE FAISS LIBRARY”</em></li><li><a href="https://www.datacamp.com/portfolio/moezsajwani"><em>Moez Ali</em></a><em> , 2025, “The Top 7 Vector Databases in 2025”, datacamp.com</em></li><li><a href="https://www.datacamp.com/tutorial/llama-cpp-tutorial?utm_source=google&amp;utm_medium=paid_search&amp;utm_campaignid=19589720821&amp;utm_adgroupid=157098104375&amp;utm_device=c&amp;utm_keyword=&amp;utm_matchtype=&amp;utm_network=g&amp;utm_adpostion=&amp;utm_creative=733936221110&amp;utm_targetid=dsa-2264919291989&amp;utm_loc_interest_ms=&amp;utm_loc_physical_ms=2250&amp;utm_content=&amp;utm_campaign=230119_1-sea~dsa~tofu_2-b2c_3-emea_4-prc_5-na_6-na_7-le_8-pdsh-go_9-nb-e_10-na_11-na-feb25&amp;gad_source=1&amp;gclid=Cj0KCQiA_Yq-BhC9ARIsAA6fbAgAJm1iDk4FFdJA2yQjGodmmqEdLL71xW695VpBjeEIsE75DZL3uuYaAiyMEALw_wcB"><em>Llama.cpp Tutorial: A Complete Guide to Efficient LLM Inference and Implementation</em></a></li></ol><p>4. <em>Zihuai Zhao et al. (2024), “Recommender Systems in the Era of Large Language Models (LLMs)”</em></p><p><em>5. Weizhi Zhang et al.( 2025) , “Cold-Start Recommendation towards the Era of Large Language Models (LLMs): A Comprehensive Survey and Roadmap”</em></p><p>6. <em>Ruixuan Sun et al.(2024) , “Large Language Models as Conversational Movie Recommenders: A User Study”</em></p><p>7. <em>Anonymous authors Paper under double-blind review, 2025 , “IAGENT: LLM AGENT AS A SHIELD BETWEEN USER AND RECOMMENDER SYSTEMS”, </em><a href="https://openreview.net/forum?id=swdMzQUhBx"><em>link</em></a></p><p><a href="https://wandb.ai/tensorgirl/ecommercerecommendation/reports/E-commerce-recommender-chatbot-with-RAG-using-LlamaIndex-and-Mistral-7B--Vmlldzo2NTU3MDYw"><em>8. Usha Rengaraju</em></a><em> , E-commerce recommender chatbot with RAG using LlamaIndex and Mistral-7B</em></p><p>9. Hugging Face , <a href="https://huggingface.co/docs/hub/en/gguf">GGUF</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*Dhg7T4t5xQ8O8073.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69046f8b7a11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Dive Into LLM Output Configuration, Prompt Engineering Techniques and Guardrails]]></title>
            <link>https://medium.com/@anicomanesh/a-dive-into-advanced-prompt-engineering-techniques-for-llms-part-i-23c7b8459d51?source=rss-3b60b0dc5fe7------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c7b8459d51</guid>
            <category><![CDATA[zero-shot-prompting]]></category>
            <category><![CDATA[promptings]]></category>
            <category><![CDATA[chain-of-thought]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[tree-of-thought-prompting]]></category>
            <dc:creator><![CDATA[Arash Nicoomanesh]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 20:55:35 GMT</pubDate>
            <atom:updated>2025-04-11T19:46:01.554Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>Part I: Reasoning and Logic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7V0m2iaTJZtPCqtq" /></figure><p>In the ever-evolving landscape of artificial intelligence, prompting has emerged as a transformative technique that bridges human intentions and machine understanding. <strong>At its core, prompting is the art of crafting inputs for large language models (LLMs) to elicit the desired outputs</strong>, whether it be answering questions, generating text, or solving complex tasks. This seemingly simple interaction encapsulates the essence of human-AI collaboration, enabling users to unlock the vast potential of LLMs without extensive programming or fine-tuning.</p><p>While the <em>“</em><strong><em>Language Models are Few-Shot Learners</em></strong><em>”</em> <em>(2020) </em>paper brought the concept of <strong><em>few-shot</em>, <em>one-shot</em></strong>, and <strong><em>zero-shot </em></strong><em>learning</em> to the forefront of public and academic attention, the concept of using carefully crafted input (prompting) to guide machine behavior predates GPT-3 and this paper, early AI systems like ELIZA in the 1960s already demonstrated the need for tailored input phrasing to achieve specific outputs.</p><p>However, what the 2020 OpenAI paper truly established was the realization of zero-shot learning in practice, enabled by the unprecedented scale and generalization capabilities of models like GPT-3. It demonstrated that <strong>prompt engineering</strong> — or crafting prompts to guide these models effectively — <strong>could unlock powerful task-solving abilities without additional fine-tuning</strong>. This paper highlighted the centrality of prompting to modern LLMs and spurred a surge of interest in prompt design as a field of study.</p><p>Prompting is not merely about asking questions or issuing commands. It is a nuanced practice that leverages the inherent knowledge and reasoning capabilities of LLMs. From zero-shot learning, where no prior examples are provided, to few-shot learning, which uses examples for context, prompting has shown its versatility across a wide array of applications. <strong>As AI continues to permeate industries and daily life, understanding and mastering prompting techniques is becoming an indispensable skill for researchers, developers, and users alike.</strong></p><p>In this article series we will disscuss about different prompting techniques but in this part we will Focuss on <strong>“Reasoning and Logic”</strong> prompting, as well as a higher-Level perspective of techniques like “system” and “role” prompting:</p><ol><li>Zero-shot Prompting</li><li>Few-shot Prompting</li><li>System, Contextual, and Role Prompting</li><li>Chain of Thought (CoT) Prompting</li><li>Least-to-Most Prompting</li><li>Automatic Chain-of-Thought (Auto-CoT)</li><li>Self-Consistency Prompting</li><li>Tree of Thoughts (ToT) Prompting</li></ol><p>Also we will discuss about <strong>llm output formating</strong> and llms <strong>guardrails </strong>to understand the boundries of promp engineering and these two concepts and how they work together to achieve optimized output from llms.</p><h3>LLM output configuration</h3><p>Once you choose your model you will need to figure out the model configuration. Most LLMs come with various configuration options that control the LLM’s output. <strong>Effective prompt engineering requires setting these configurations optimally</strong> for our task.</p><p>When configuring a Large Language Model (LLM) for your specific tasks, several key parameters can significantly influence the model’s output. Understanding and adjusting these settings are crucial for effective prompt engineering:​</p><ul><li><strong>Temperature:</strong> Controls the randomness of the model’s responses. Lower values (e.g., 0.2) make outputs more deterministic and focused, suitable for tasks requiring precision. Higher values (e.g., 1.0) introduce variability, fostering creativity in tasks like story generation. ​</li><li><strong>Top P (Nucleus Sampling):</strong> Determines the diversity of the output by considering only the most probable tokens whose cumulative probability meets the top_p threshold. Lower values yield more focused responses, while higher values allow for greater diversity. ​</li><li><strong>Max Tokens:</strong> Sets the maximum length of the generated response. Adjusting this helps control verbosity, ensuring outputs are concise and relevant.</li><li><strong>Frequency Penalty:</strong> Applies a penalty to tokens based on their frequency in the generated text, reducing repetition. ​</li><li><strong>Presence Penalty:</strong> Penalizes tokens that have already appeared, encouraging the model to introduce new topics and ideas.</li><li><strong>Stop Sequences:</strong> Defines specific strings that signal the model to cease generating further tokens, helping to control the structure and length of responses. ​</li></ul><p>Optimally setting these configurations is essential for tailoring the LLM’s performance to your specific requirements, thereby enhancing the effectiveness of your prompt engineering efforts.</p><p>Limiting the output length of a Large Language Model (LLM) does not inherently make its responses more concise or stylistically succinct; instead, it merely truncates the output once the specified token limit is reached. Therefore, if you require shorter responses, it’s essential to craft your prompts accordingly to guide the LLM toward brevity. This is particularly crucial for certain prompting techniques, such as ReAct, where the model may continue generating unnecessary tokens beyond the desired response. Additionally, generating more tokens demands increased computational resources, leading to higher energy consumption, potentially slower response times, and increased operational costs.</p><h4>Sampling controls</h4><p>LLMs do not formally predict a single token. Rather, LLMs predict probabilities for what the next token could be, with each token in the LLM’s vocabulary getting a probability. Those token probabilities are then sampled to determine what the next produced token will be.<br>Temperature, top-K, and top-P are the most common configuration settings that determine how predicted token probabilities are processed to choose a single output token.</p><h4>Temperature</h4><p>Temperature in LLMs controls the randomness of token selection. Lower values result in more deterministic responses, while higher values introduce diversity and unpredictability. A temperature of 0 always selects the highest probability token, making outputs consistent. As temperature increases, token selection becomes more random, with extreme values making all tokens equally probable.</p><p>Different LLMs may have varying default temperature ranges and behaviors. For instance, OpenAI’s GPT models allow temperature settings from 0.0 to 2.0, with a default of 1.0, while Anthropic’s models restrict the temperature range to 0.0 to 1.0. Therefore, it’s essential to refer to the specific documentation of the LLM you’re using to understand its temperature parameterization.</p><ul><li>The <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini-use-supervised-tuning"><strong>Gemini</strong></a><strong> temperature</strong> setting works similarly to softmax in machine learning, where lower values emphasize certainty, and higher values allow for greater variability, making it useful for creative tasks.</li><li><strong>Mistral’s LLMs</strong> utilize the temperature parameter to balance output determinism and creativity. Lower values result in focused and predictable responses, suitable for tasks requiring accuracy. Higher values introduce diversity, beneficial for creative tasks. For example, setting the temperature to 0.1 may consistently yield the same answer, while a temperature of 1.0 produces varied responses.</li><li><strong>DeepSeek-R1</strong> The default value of temperature is 1.0 . Set the <a href="https://docs.together.ai/docs/prompting-deepseek-r1#:~:text=Sampling%20parameters%3A%20Set%20the%20temperature,contained%20within%20the%20user%20prompt.">temperature</a> within the range of 0.5-0.7 (0.6 is recommended) to prevent endless repetitions or incoherent outputs.</li></ul><h4>Top-K and top-P</h4><p>Top-K and top-P (also known as nucleus sampling)4 are two sampling settings used in LLMs to restrict the predicted next token to come from tokens with the top predicted probabilities.<br>Like temperature, these sampling settings control the randomness and diversity of generated text.</p><ul><li><strong>Top-K</strong> sampling selects the top K most likely tokens from the model’s predicted distribution. The higher top-K, the more creative and varied the model’s output; the lower top-K, the more restive and factual the model’s output. A top-K of 1 is equivalent to<br>greedy decoding.</li><li><strong>Top-P</strong> sampling selects the top tokens whose cumulative probability does not exceed a certain value (P). Values for P range from 0 (greedy decoding) to 1 (all tokens in the LLM’s vocabulary).</li></ul><p>Selecting top-K, top-P, temperature, and token count depends on the task and desired output and the LLM we use , as these parameters influence each other. Understanding how a model integrates them is crucial.</p><h3>What is Prompt Engineering?</h3><p>Prompt engineering is the process of crafting and refining prompts to improve the performance of generative AI models. It involves providing specific inputs to tools like ChatGPT, Midjourney, or Gemini, guiding the AI to deliver more accurate and contextually relevant outputs.</p><blockquote>When an AI model doesn’t produce the desired response, prompt engineering allows us to iterate and adjust the prompt to optimize the output. This method is particularly useful for overcoming limitations of generative models, such as logical errors or insufficient context in responses.</blockquote><p>Generative AI relies heavily on the input it receives. The more clearly and contextually a task is described, the better the AI can respond. While anyone can try basic prompts, prompt engineering as a skill allows users to structure queries that better unlock an AI’s capabilities. Prompt engineering enables tasks from writing creative text to generating images or even code.</p><p>In today’s AI landscape, where large language models (LLMs) power a wide range of applications, prompt engineering is essential. It helps bridge the gap between vague, general queries and specific, targeted outputs that align with your goals. This iterative process ensures that the AI not only understands your intent but delivers results that require minimal post-processing.</p><p>Moreover, prompt engineering can mitigate risks like prompt injection attacks (where users try to manipulate the AI’s logic) and ensure that the model’s outputs align with desired ethical and operational standards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RLdgPma42cJoUaXh.png" /><figcaption>Figure 1. Prompting an LLM with instructions</figcaption></figure><h3><strong>What is a Prompt?</strong></h3><p>A prompt used to guide a Large Language Model (LLM) typically includes components like: <strong>instructions, context, examples, specific questions, role definition (if applicable), and sometimes even formatting cues</strong>, all designed to clearly convey the desired task and provide enough information for the LLM to generate the most relevant response.</p><p><strong>Key components of a prompt:</strong></p><ul><li><strong>Instruction: </strong>The clear, concise task or action you want the LLM to perform, like “Write a summary of this article” or “Explain the concept of gravity in simple terms.”</li><li><strong>Context: </strong>Background information or relevant details that help the LLM understand the situation and provide a better response.</li><li><strong>Examples: </strong>Providing sample inputs and outputs can be helpful, especially for tasks requiring a specific format or style.</li><li><strong>Specific Question: </strong>The core question or prompt that the LLM needs to answer, ensuring clarity and focus.</li><li><strong>Role Definition (optional): </strong>Assigning a persona to the LLM, like “a science teacher” or “a customer service representative,” to guide the tone and style of the response.</li></ul><p>Important considerations when crafting a prompt:</p><ul><li><strong>Clarity and Specificity:</strong> Use clear language and avoid ambiguity to ensure the LLM understands the desired outcome.</li><li><strong>Relevance:</strong> Provide context and information that is directly related to the task at hand.</li><li><strong>Conciseness:</strong> Keep the prompt brief while still providing essential details.</li><li><strong>Tailoring to the Model:</strong> Understand the capabilities of your LLM and design prompts accordingly.</li></ul><h3>Guardrails</h3><p>Guardrails are mechanisms implemented to ensure LLMs operate within predefined safety and ethical boundaries. They can generally be categorized into:</p><ul><li><strong>Input Guardrails:</strong> Filter or modify user inputs to prevent the model from processing harmful or inappropriate content.​</li><li><strong>Output Guardrails:</strong> Review and adjust the model’s responses to block or refine content that may be harmful, biased, or irrelevant.​</li><li><strong>Behavioral Guardrails:</strong> Set overarching rules governing the model’s operation, ensuring it adheres to specific guidelines or remains within its domain expertise.​</li></ul><p>There are another categorization of guardrails in differnt perspective that will help to understand the application of guardrails as bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DXolmmtGn-pqqpRY.png" /><figcaption>Figure 2. Guardrails Categories from “Bhavishya Pandit”</figcaption></figure><p>Below is a simple code example that demonstrates the differences between three key aspects when working with LLMs: <strong>LLM Output Configuration</strong>, <strong>Prompt Engineering</strong>, and <strong>Guardrails</strong>.</p><pre>import openai<br><br><br># 1. LLM Output Configuration<br># These settings (e.g., temperature, max_tokens, top_p) control the behavior of the LLM.<br>llm_config = {<br>    &quot;model&quot;: &quot;gpt-4&quot;,          # The chosen LLM<br>    &quot;temperature&quot;: 0.7,        # Controls randomness (0 = deterministic; higher values yield more diverse output)<br>    &quot;max_tokens&quot;: 100,         # Maximum number of tokens to generate<br>    &quot;top_p&quot;: 0.95,             # Nucleus sampling: probability threshold for token selection<br>    &quot;frequency_penalty&quot;: 0,    # Penalty for repeating tokens<br>    &quot;presence_penalty&quot;: 0,     # Penalty for new topic introduction<br>}<br><br><br># 2. Prompt Engineering<br># Here, we carefully craft the prompt to guide the LLM toward the desired task.<br>prompt = (<br>    &quot;You are an assistant specialized in summarizing technical documents. &quot;<br>    &quot;Please provide a concise summary of the following text:\n\n&quot;<br>    &quot;\&quot;The quick brown fox jumps over the lazy dog. &quot;<br>    &quot;This sentence is often used to showcase all the letters of the English alphabet.\&quot;&quot;<br>)<br><br><br># 3. Guardrails<br># Guardrails are implemented to ensure that the generated output is safe and appropriate.<br>def apply_guardrails(text):<br>    # List of words or phrases that are considered unsafe or unwanted<br>    disallowed_words = [&quot;hate&quot;, &quot;violence&quot;, &quot;explicit&quot;]<br>    # Check if any disallowed word is present in the output<br>    for word in disallowed_words:<br>        if word in text.lower():<br>            return &quot;Output removed due to safety concerns.&quot;<br>    return text<br><br><br># LLM Call: Combining all the aspects<br>response = openai.Completion.create(<br>    engine=llm_config[&quot;model&quot;],<br>    prompt=prompt,<br>    temperature=llm_config[&quot;temperature&quot;],<br>    max_tokens=llm_config[&quot;max_tokens&quot;],<br>    top_p=llm_config[&quot;top_p&quot;],<br>    frequency_penalty=llm_config[&quot;frequency_penalty&quot;],<br>    presence_penalty=llm_config[&quot;presence_penalty&quot;]<br>)<br><br># Extract the generated text from the response<br>raw_output = response.choices[0].text.strip()<br><br># Apply guardrails to check and clean the output<br>final_output = apply_guardrails(raw_output)<br><br># Print the final output<br>print(&quot;LLM Output:&quot;)<br>print(final_output)</pre><h3>Prompt Engineering Techniques</h3><p><a href="https://arxiv.org/pdf/2402.07927">Pranab Sahoo et al. </a>in their paper have organized prompt engineering techniques according to their application areas and provided a <strong>concise overview</strong> of the evolution of prompting techniques, spanning from zero-shot prompting to the latest advancements. In this article series we cover a subset of advanced prompting engineering techniques which they have disscussed in their article <strong>practically</strong> that allow us to achieve more complex tasks and improve reliability and performance of LLMs.</p><p>By refering to their taxonomy of prompt engineering techniques in LLMs, which organized around application domains, we will cover following taxonomy during Part I and Part II of this article series :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iv_0LY6RQErAVxYL3lKArw.png" /><figcaption>Figure 3. Taxonomy of prompt engineering techniques in LLMs, organized around application domains , inspired by <a href="https://arxiv.org/pdf/2402.07927">Source</a></figcaption></figure><h4>Zero-shot Prompting</h4><p>Large language models (LLMs) today, such as GPT-3.5 Turbo, GPT-4, and Mistral-7B-Instruct , are tuned to <strong>follow instructions</strong> and are trained on large amounts of data. Large-scale training makes these models capable of performing some tasks in a “zero-shot” manner. Zero-shot prompting means that the prompt used to interact with the model <strong>won’t contain examples or demonstrations</strong>. The zero-shot prompt directly instructs the model to perform a task without any additional examples to steer it.</p><p>Text Classification</p><pre><br># Load a pre-trained open-source model<br>model_name = &quot;mistralai/Mistral-7B-Instruct-v0.3&quot;  # Replace with your preferred model<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForCausalLM.from_pretrained(model_name)<br><br># Define the prompt<br>prompt = &quot;Classify the sentiment of this text (positive, negative, neutral): &#39;The weather is gloomy, but I feel great today.&#39; Provide a brief and complete explanation.&quot;<br><br># Tokenize and generate<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;)<br>outputs = model.generate(**inputs, max_length=100,<br>    temperature=0.1,<br>    top_p=1,<br>    do_sample=True,<br>   )<br><br># Decode and print the result<br>result = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(result)</pre><p>Output:</p><pre>The sentiment of the text is positive. <br>Although the weather is described as gloomy, the speaker&#39;s personal <br>feelings are positive, as they feel great. <br>This shows that the speaker&#39;s mood is not affected by the weather, <br>which is a positive sentiment.</pre><p>Please note the model temperature should be set to a low number, since no creativity is needed, and we use the Mistral-7B default top-K and top-P values(Hugging Face implementation), which effectively disable both settings .</p><p>When zero-shot doesn’t work, you can provide demonstrations or examples in the prompt, which leads to “one-shot” and “few-shot” prompting</p><h4>Few-shot Prompting</h4><p>Few shot prompting is a prompt engineering technique where you insert examples in your prompt, training the model on what you want the output to look and sound like.</p><p>This method builds on LLM’s ability to learn and generalize information from a small amount of data. This makes it particularly helpful when you don’t have enough data to fine-tune a model.</p><p>Bellow is the sample code that the chatbot is asked to generate a headline (or title) for a given news-like paragraph based on two provided examples. We load &quot;google/gemma-2-2b&quot;, which is a <strong>non–instruction-tuned </strong>version. This model hasn&#39;t been fine-tuned to follow explicit instructions, so it benefits from additional context via few-shot examples.</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM<br><br><br>model_name = &quot;google/gemma-2-2b&quot;  <br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForCausalLM.from_pretrained(model_name)<br><br><br>prompt = (<br>    &quot;Example 1:\n&quot;<br>    &quot;Paragraph: &#39;The company reported a 25% increase in profits after launching their new eco-friendly product line, which resonated well with consumers.&#39;\n&quot;<br>    &quot;Title: &#39;Eco-Friendly Product Line Boosts Profits&#39;\n\n&quot;<br>    &quot;Example 2:\n&quot;<br>    &quot;Paragraph: &#39;After months of research, the team unveiled a groundbreaking solar panel technology that promises to revolutionize energy consumption.&#39;\n&quot;<br>    &quot;Title: &#39;Revolutionary Solar Panel Technology Unveiled&#39;\n\n&quot;<br>    &quot;Now, provide an appropriate title for the following paragraph:\n&quot;<br>    &quot;Paragraph: &#39;City officials introduced a new public park initiative, aimed at providing residents with green spaces and promoting community well-being.&#39;\n&quot;<br>    &quot;Title:&quot;<br>)<br><br># Tokenize the prompt<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;)<br><br># Generate the output with sufficient max_length and diversity parameters<br>outputs = model.generate(<br>    **inputs,<br>    max_length=200,      # Ensures enough room for a complete title<br>    temperature=0.7,     # Moderate randomness for creativity<br>    top_p=0.9,<br>    num_beams=5,         # Increase beam count to explore diverse completions<br>    do_sample=True<br>)<br><br># Decode and display the result<br>result = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(&quot;Few-Shot Title Generation Output:\n&quot;)<br>print(result)</pre><p>Output:</p><pre>Now, provide an appropriate title for the following paragraph:<br>Paragraph: &#39;City officials introduced a new public park initiative, aimed at providing residents with green spaces and promoting community well-being.&#39;<br>Title: &#39;Green Spaces for Community Well-being&#39;</pre><p>We used a Non–Instruction-Tuned Model with Few-Shot Prompting. Because Non–Instruction-Tuned Models are not explicitly fine-tuned to follow instructions. As a result, they may not produce the desired output when given a simple query. By providing examples (few-shot prompt), we guide the model by showing it the pattern to follow. In our example, the two provided examples illustrate how paragraphs are transformed into concise titles.</p><p>Selecting the appropriate prompting technique — zero-shot, one-shot, or few-shot — depends on the complexity of the task and the level of guidance the model requires.</p><p>Here’s a quick summary of when to use each method:</p><ul><li><strong>Zero-shot prompting</strong>: Use this when the task is simple, well-understood, or frequently encountered in the model’s training data. It’s efficient for tasks like basic arithmetic, general queries, or sentiment classification for common phrases.</li><li><strong>One-shot prompting</strong>: This is helpful for tasks that need more specific guidance or when the model struggles with ambiguity. Providing a single example can clarify the task, improving accuracy in tasks like basic classification or structured information extraction.</li><li><strong>Few-shot prompting</strong>: Best used for complex tasks requiring multiple examples to establish patterns. This technique is ideal for tasks that involve varied inputs, require precise formatting, or demand a higher degree of accuracy, such as generating structured outputs or handling nuanced classifications.</li></ul><h4><strong>System, Contextual, and Role Prompting: A Higher-Level Perspective</strong></h4><p>While techniques like zero-shot and few-shot prompting ( and more advanced technique e.g. COT ) focus on shaping the immediate output of language models, higher-level strategies such as <strong>system</strong>, <strong>contextual</strong>, and <strong>role prompting</strong> establish the overall framework in which these models operate. System prompting sets the broad mission — telling the model, for example, that it is an expert translator. Contextual prompting provides the detailed background necessary for nuanced responses, such as including relevant data in a technical explanation. Role prompting, meanwhile, assigns a persona to the model, ensuring its tone and style are consistent with the intended application. These methods work synergistically with zero-shot, few-shot, CoT, and ToT approaches to produce more accurate, coherent, and contextually appropriate outputs.</p><p>System, contextual and role prompting are all techniques used to guide how LLMs generate text, but they focus on different aspects:</p><ul><li><strong>System prompting </strong>sets the overall context and purpose for the language model. It defines the ‘big picture’ of what the model should be doing, like translating a language, classifying a review etc. Following is an example of system prompt, where I specify additional information on how to return the output:</li></ul><pre>Classify movie reviews as positive, neutral or negative. Only<br>return the label in uppercase.<br>Review: &quot;Her&quot; is a disturbing study revealing the direction<br>humanity is headed if AI is allowed to keep evolving,<br>unchecked. It&#39;s so disturbing I couldn&#39;t watch it.<br>Sentiment:</pre><ul><li><strong>Contextual prompting</strong> provides specific details or background information relevant to the current conversation or task. It helps the model to understand the nuances of what’s being asked and tailor the response accordingly.Example:</li></ul><pre>Context: You are writing for a blog about retro 80&#39;s arcade<br>video games.<br>Suggest 3 topics to write an article about with a few lines of<br>description of what this article should contain.</pre><ul><li><strong>Role prompting</strong> assigns a specific character or identity for the language model to adopt. This helps the model generate responses that are consistent with the assigned role and its associated knowledge and behavior.</li></ul><pre>I want you to act as a travel guide. I will write to you<br>about my location and you will suggest 3 places to visit near<br>me. In some cases, I will also give you the type of places I<br>will visit.<br>My suggestion: &quot;I am in Amsterdam and I want to visit<br>only museums.&quot;<br>Travel Suggestions:</pre><p>There can be considerable overlap between system, contextual, and role prompting. E.g. a prompt that assigns a role to the system, can also have a context.<br>However, each type of prompt serves a slightly different primary purpose:</p><ul><li>System prompt: Defines the model’s fundamental capabilities and overarching purpose.</li><li>Contextual prompt: Provides immediate, task-specific information to guide the response. It’s highly specific to the current task or input, which is dynamic.</li><li>Role prompt: Frames the model’s output style and voice. It adds a layer of specificity and personality.</li></ul><p><strong>When to Use System, Contextual, and Role Prompting?</strong></p><ul><li>Establishing Consistency:<br> Use system prompting when you need a persistent, overarching instruction (e.g., “You are a financial advisor”) that should influence all responses throughout the session.</li><li>Providing Background:<br> Use contextual prompting to supply necessary details or background information that enables the model to understand complex queries and produce accurate, tailored responses.</li><li>Defining Tone and Persona:<br> Use role prompting to set the model’s voice and behavior (e.g., as a technical expert, empathetic counselor, or creative writer), ensuring that the output fits the intended audience or application.</li></ul><p>System, contextual, and role prompting establish a high-level framework that can enhances the effectiveness of other prompting techniques such as zero-shot, few-shot, chain-of-thought (CoT), and tree-of-thought (ToT) too. By setting the overall mission through system prompting, providing necessary background with contextual prompts, and assigning a consistent persona via role prompting, these methods guide the model’s behavior throughout the interaction. When <strong>combined with zero-shot or few-shot examples, the model not only understands the specific task but also maintains a consistent tone and perspective.</strong> Similarly, integrating them with CoT or ToT and other techniques encourages the model to articulate its reasoning in a step-by-step manner, ensuring that every part of the response adheres to the overarching context and style defined by the higher-level prompts.</p><p>For example, imagine a chatbot designed to help users plan travel itineraries, using system prompting, the chatbot is set to operate as an expert travel advisor (“You are an expert travel planner”); with contextual prompting, the conversation includes specific details such as “the user is traveling to Italy in September with a focus on cultural experiences”; and role prompting ensures a friendly and engaging tone (“Speak as a warm, knowledgeable travel agent”). Now, when the user asks, “What’s the best way to spend three days in Rome?” the chatbot combines these high-level instructions with few-shot examples or chain-of-thought reasoning — breaking down the itinerary into daily activities — to provide a coherent, contextually rich, and personalized recommendation.</p><p>In above example <strong>“You are an expert travel planner” </strong>and<strong> “Speak as a warm, knowledgeable travel agent”</strong> do share similarities, as they guide the model’s persona, but they emphasize slightly different aspects:</p><ul><li><strong>“You are an expert travel planner”</strong> is aimed at establishing the domain expertise or overall context of the task. It signals to the model that it should draw on its knowledge about travel planning, itineraries, and logistics. This is often considered a form of <strong>system prompting</strong> because it sets the overarching task or mission.</li><li><strong>“Speak as a warm, knowledgeable travel agent”</strong> focuses on the tone and style of the response. It instructs the model to adopt a friendly, engaging manner while still being informed. This is more of a <strong>role prompting</strong> technique, where the model is guided to adopt a specific personality or communication style.</li></ul><p>While they overlap in that both shape the model’s behavior, one primarily sets the expertise and task (system prompting), and the other refines the manner in which the response is delivered (role prompting). In practice, we can use both together to ensure that the output is not only accurate but also engaging and appropriate for the target audience.</p><h4>CoT Prompting</h4><p>Chain of Thought (CoT) prompting is a technique that guides large language models (LLMs) to generate step-by-step reasoning before providing a final answer. This method enhances the model’s ability to handle complex reasoning tasks, such as multi-step math problems, logical reasoning, or causal analysis.</p><p>By explicitly prompting the model to break down a problem into smaller steps, CoT reduces errors and improves the quality of the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onbzQn9w4LhW88dPAk1yLA.png" /><figcaption>Figure 4. Example inputs and outputs of GPT-3 with (a) standard Few-shot ([Brown et al., 2020]), (b) Few-shot-CoT ([Wei et al., 2022]), © standard Zero-shot, and (d) Zero-shot-CoT. Similar to Few-shot-CoT, Zero-shot-CoT facilitates multi-step reasoning (blue text) and reach correct answer where standard prompting fails. Unlike Few-shot-CoT using step-by-step reasoning examples per task, zero-shot-COT does not need any examples and just uses the same prompt “Let’s think step by step” across all tasks (arithmetic, symbolic, commonsense, and other logical reasoning tasks). <a href="https://arxiv.org/pdf/2205.11916">Source</a></figcaption></figure><p>Chain of thought can be useful for various use-cases. Think of code generation, for breaking down the request into a few steps, and mapping those to specific lines of code. Or for creating synthetic data when you have some kind of seed like “The product is called XYZ, write a description guiding the model through the assumptions you would make based on<br>the product given title.” Generally, any task that can be solved by ‘talking through is a good candidate for a chain of thought. If you can explain the steps to solve the problem, try chain of thought.</p><h4>Least-to-Most Prompting</h4><p>Chain-of-thought prompting was first written[6] about in 2022 and is still one of the top prompt engineering methods for increasing performance through enhanced reasoning.</p><p>Like all prompt engineering methods, <strong>chain-of-thought</strong> has limitations. Most notably, it performs poorly on tasks that require solving problems that are harder than the examples shown. <strong>Least-to-most prompting was designed to overcome this specific limitation in chain-of-thought prompting [</strong>5].</p><p>This method is a prompt engineering method that increases the problem-solving capabilities of LLMs by breaking down complex problems into a series of simpler subproblems that get executed sequentially.</p><p>Least-to-most prompting has two stages:</p><ol><li><strong>Decomposition stage:</strong> Break down a complex problem into a list of subproblems. The prompt used in this step has few-shot examples that show the model how to decompose problems.</li><li><strong>Subproblem solving stage:</strong> After breaking the problem into simpler subproblems, the model solves each subproblem sequentially, or all at once if you’d like. This prompt has three parts: (1) few-shot prompting examples demonstrating how subproblems are solved, (2) previously solved subproblems and solutions, and (3) the next question to be answered.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f0jIo2jM6JV39cNi.png" /><figcaption>Figure 5. Least-to-most prompting solving a math word problem in two stages: (1) query the language model to decompose the problem into subproblems; (2) query the language model to sequentially solve the subproblems. The answer to the second subproblem is built on the answer to the first subproblem. The demonstration examples for each stage’s prompt are omitted in this illustration.<a href="https://arxiv.org/pdf/2205.10625">Source</a></figcaption></figure><p>Just to illustrate how does Least-to-Most Prompting work i used following problem with an static approach for solution code:</p><blockquote>Let’s solve the problem:</blockquote><blockquote>“If a factory produces 100 items per day, how many items will it produce in 3 weeks (assuming 6 working days per week)?”</blockquote><pre>from transformers import AutoTokenizer, AutoModelForCausalLM<br><br># Step 1: Load the model and tokenizer<br>model_name = &quot;mistralai/Mistral-7B-Instruct-v0.3&quot;  # Replace with your open-source model<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForCausalLM.from_pretrained(model_name)<br><br>def least_to_most_prompting(problem, steps):<br>    &quot;&quot;&quot;<br>    Implements least-to-most prompting by guiding the model step by step.<br>    &quot;&quot;&quot;<br>    context = &quot;&quot;<br>    final_output = &quot;&quot;<br>    <br>    for i, step in enumerate(steps):<br>        # Build the incremental prompt<br>        prompt = f&quot;{context}\nStep {i+1}: {step}&quot;<br>        inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;)<br>        outputs = model.generate(**inputs, max_length=100)<br>        step_output = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>        <br>        # Update the context for the next step<br>        context += f&quot;\nStep {i+1}: {step_output}&quot;<br>        <br>        # Print the intermediate step for clarity<br>        print(f&quot;Step {i+1} Output:\n{step_output}\n&quot;)<br>        <br>        # Save the final output if it&#39;s the last step<br>        if i == len(steps) - 1:<br>            final_output = step_output.strip()<br>    <br>    return final_output<br><br># Define the problem and steps<br>problem = &quot;If a factory produces 100 items per day, how many items will it produce in 3 weeks (assuming 6 working days per week)?&quot;<br>steps = [<br>    &quot;How many working days are there in 3 weeks if the factory works 6 days per week?&quot;,<br>    &quot;How many items are produced in one working day?&quot;,<br>    &quot;Multiply the number of working days by the number of items produced per day to get the total number of items.&quot;<br>]<br><br># Execute least-to-most prompting<br>final_answer = least_to_most_prompting(problem, steps)<br><br>print(&quot;\nFinal Answer:&quot;)<br>print(final_answer)</pre><p>Output:</p><pre>Step 1 Output:<br><br>Step 1: How many working days are there in 3 weeks if the factory works 6 days per week?<br><br>To find the number of working days in 3 weeks, we multiply the number of weeks by the number of days per week.<br><br>Number of working days = Weeks * Days per week<br>                                   = 3 * 6<br>                                   = 18 days<br><br>So, there are 18 working days in 3 weeks if the factory works 6 days per week.<br><br>--------------------<br>Step 2 Output:<br><br>Step 2: How many items are produced in one working day?<br><br>To find the number of items produced in one working day, we need to know the production rate per hour and the number of hours worked per day.<br><br>Let&#39;s assume the factory works 8 hours per day and the production rate is 10 items per hour.<br><br>Number of items produced per day = Production rate * Hours per day<br>                                                 = 10 items/hour * 8 hours<br>                                                 = 80 items<br><br>So, if the production rate is 10 items per hour and the factory works 8 <br>hours per day, then 80 items are produced in one working day.<br><br>--------------------<br>Step 3 Output:<br><br>Step 3: How many items are produced in 3 weeks<br><br>Multiply the number of working days by the number of items produced per day to get the total number of items.<br><br>Total number of items = Working days * Items per day<br>                                   = 18 days * 80 items<br>                                   = 1440 items<br><br>So, if the factory works 6 days per week for 3 weeks with a production <br>rate of 10 items per hour and 8 hours per day, then 1440 items are produced<br>in 3 weeks.</pre><p>We can see the problem-solving is broken into smaller steps that build logically from one another. Also Each step explicitly provides intermediate results before proceeding to the next, which aligns well with the goal of least-to-most prompting. The assumptions made (e.g., production rate = 10 items/hour, working hours = 8 hours/day) are explicitly stated. And finaly each calculation (e.g., working days = 3×6=183 \times 6 = 183×6=18, items per day = 10×8=8010 \times 8 = 8010×8=80, total items = 18×80=144018 \times 80 = 144018×80=1440) is accurate.</p><p><strong>Key Differences Between Least-to-Most Prompting and CoT Prompting</strong></p><p>Least-to-Most prompting focuses on breaking down complex tasks into a sequence of simpler subproblems, solving them step-by-step to build towards the final solution, whereas Chain-of-Thought (CoT) prompting emphasizes generating a continuous, logical reasoning chain for solving a problem directly. While both methods encourage structured reasoning, Least-to-Most prompting explicitly decomposes the problem into discrete steps, making it ideal for tasks that benefit from modular problem-solving, whereas CoT is better suited for tasks requiring holistic reasoning with a single, unbroken flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDV3tRxrfZy1u4LSIrqzDA.png" /><figcaption>Table 1. Least-to-Most Prompting and CoT Prompting, Table by Author</figcaption></figure><p><strong>Why Use One Over the Other?</strong></p><ol><li><strong>Choose Least-to-Most Prompting when</strong>:</li></ol><ul><li>You have a highly complex problem that can naturally be decomposed into sequential subproblems.</li><li>Intermediate results from one step might influence the next.</li><li>The task requires modular reasoning and clarity at each step.</li></ul><p><strong>2. Choose Chain-of-Thought Prompting when</strong>:</p><ul><li>The task involves reasoning or logic that can be handled in a single “thought chain.”</li><li>There’s no need for external guidance or intermediate results.</li><li>Simplicity and brevity are essential.</li></ul><h4><strong>Automatic Chain-of-Thought (Auto-CoT)</strong></h4><p>When using chain-of-thought (CoT) prompting with demonstrations, the process often involves manually crafting effective and diverse examples. However, this approach can lead to suboptimal results due to human limitations. To address this, Zhang et al. (2022) introduced an automated method called Auto-CoT, which eliminates manual effort by leveraging large language models (LLMs). Using a prompt like “Let’s think step by step,” the LLM generates reasoning chains for demonstrations. However, mistakes in these generated chains can still occur. To mitigate these errors, ensuring diversity among the demonstrations is crucial.</p><p><strong>Auto-CoT</strong> operates in two main stages:</p><ol><li><strong>Question Clustering</strong>: Partition the questions in a dataset into clusters based on their similarity.</li><li><strong>Demonstration Sampling</strong>: Select a representative question from each cluster and generate its reasoning chain using Zero-Shot CoT with simple heuristics.</li></ol><p>The heuristics may include criteria like the length of the question (e.g., 60 tokens) or the number of reasoning steps (e.g., 5 steps). This encourages the model to generate simple yet accurate demonstrations.</p><p>The following diagram illustrates the Auto-CoT process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aX8yUcLkeowl2JuVn6kx6w.png" /><figcaption>Figure 6. Overview of the Auto-CoT method. Different from Manual-CoT , demonstrations (on the right) are automatically constructed one by one (total: k) using an LLM with the “Let’s think step by step” prompt. <a href="https://arxiv.org/pdf/2210.03493">Source</a></figcaption></figure><p>You can find related code in this <a href="https://colab.research.google.com/github/amazon-science/auto-cot/blob/main/try_cot_colab.ipynb">colab notebook</a> using <a href="https://github.com/amazon-science/auto-cot">amazon-science/auto-cot</a>.</p><h4><strong>Self-Consistency</strong></h4><p>While large language models have shown impressive success in various NLP tasks, their ability to reason is often seen as a limitation that cannot be overcome solely by increasing model size. As we learned in the previous Chain of Thought prompting section, the model can be prompted to generate reasoning steps like a human solving a problem. However CoT uses a simple ‘greedy decoding’ strategy, limiting its effectiveness. Self-consistency combines sampling and majority voting to generate diverse reasoning paths and select the most consistent answer. It improves the accuracy and coherence of responses generated by LLMs.<br>Self-consistency gives a pseudo-probability likelihood of an answer being correct, but obviously has high costs.</p><p>It follows the following steps:</p><ol><li>Generating diverse reasoning paths: The LLM is provided with the same prompt multiple times. A high temperature setting encourages the model to generate different reasoning paths and perspectives on the problem.</li><li>Extract the answer from each generated response.</li><li>Choose the most common answer.</li></ol><p>Self-consistency prompting can be used in a variety of applications, including <strong>personalized medicine</strong>, autonomous systems, and human-AI collaboration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GmvInrZiIT8BqbXG.png" /><figcaption>Figure 7. Comparing Chain-of-thought prompting and Self-consistency prompting</figcaption></figure><h4>Tree of Thoughts (ToT)</h4><p><strong>Tree of Thoughts (ToT)</strong> prompting expands on the idea of Chain-of-Thought (CoT) reasoning by exploring multiple reasoning paths in parallel. Instead of following a single linear reasoning path, ToT generates and evaluates multiple possible solutions at each step, forming a “tree” structure. This allows the model to backtrack and compare paths, improving the accuracy and robustness of its reasoning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*FqvehmigKV8sGnYF.png" /><figcaption>Figure 8. Schematic illustrating various approaches to problem solving with LLMs. Each rectangle box represents a <em>thought</em>, which is a coherent language sequence that serves as an intermediate step toward problem solving. <a href="https://arxiv.org/pdf/2305.10601">Source</a></figcaption></figure><p>When using ToT prompting, we explore several <em>paths</em> — each comprised of individual <em>thoughts</em> — that represent potential solutions to a problem. Together, each of these paths and their individual thoughts form a tree that explores a problem’s solution space; see above. In this tree, each node is simply a partial solution (or thought) to our problem, while each connection is a operator that modifies this partial solution to yield the next thought within a problem-solving path.</p><p>I used following problem and simulation code to illustrate how does ToT work :</p><blockquote><strong>Problem:</strong></blockquote><blockquote>“How can we build a scalable recommendation system for a growing e-commerce platform?”</blockquote><p>Lets use Gemma2–2b to reflect a simple implementation of <strong>Tree-of-Thoughts (ToT)</strong> reasoning.</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer<br>import torch<br><br># Load the Gemma 2B model and tokenizer<br>model_name = &quot;google/gemma-2b-it&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>model.to(device)<br><br># Define the question and the ToT prompt<br>question = &quot;How can we build a scalable recommendation system for a growing e-commerce platform?&quot;<br><br># Properly structure the ToT prompt to include the question<br>prompt = f&quot;&quot;&quot;<br>Imagine three different experts are answering this question collaboratively: &quot;{question}&quot;. <br>Each expert will:<br>1. Write down one step of their thinking and share it with the group.<br>2. Consider the prior explanations of the others and openly acknowledge any mistakes.<br>3. Refine and build upon the contributions of others until a definitive answer is reached.<br><br>Simulate three brilliant, logical experts (Expert 1, Expert 2, and Expert 3) engaging in this collaborative process. <br>At each step:<br>- Experts will score their peers’ responses from 1 (highly unlikely) to 5 (highly likely).<br>- If any expert is judged to be wrong at any point, they will leave.<br><br>Provide the analysis and final consensus in the form of a **Markdown table**, and then summarize the definitive solution.<br>&quot;&quot;&quot;<br><br># Tokenize the input<br>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(device)<br><br># Generate the model response<br>outputs = model.generate(<br>    inputs.input_ids,<br>    max_length=1024,<br>    temperature=0.7,<br>    top_p=0.9,<br>    num_return_sequences=1,<br>    do_sample=True<br>)<br><br># Decode the output<br>response = tokenizer.decode(outputs[0], skip_special_tokens=True)<br><br># Display the output<br>print(&quot;Collaborative Reasoning ToT Result:&quot;)<br>print(response)</pre><p>Output:</p><pre><br><br>Collaborative Reasoning ToT Result:<br><br>Imagine three different experts are answering this question collaboratively: &quot;How can we build a scalable recommendation system for a growing e-commerce platform?&quot;. <br>Each expert will:<br>1. Write down one step of their thinking and share it with the group.<br>2. Consider the prior explanations of the others and openly acknowledge any mistakes.<br>3. Refine and build upon the contributions of others until a definitive answer is reached.<br><br>Simulate three brilliant, logical experts (Expert 1, Expert 2, and Expert 3) engaging in this collaborative process. <br>At each step:<br>- Experts will score their peers’ responses from 1 (highly unlikely) to 5 (highly likely).<br>- If any expert is judged to be wrong at any point, they will leave.<br><br>Provide the analysis and final consensus in the form of a **Markdown table**, and then summarize the definitive solution.<br>## Collaborative Recommendation System for E-commerce Platform<br><br>**Expert 1:**<br><br>1. **Identify user behavior patterns:** Analyze user purchase history, browsing behavior, social media engagement, and search queries to understand user interests and preferences.<br>2. **Develop a recommendation engine:** Choose from existing recommendation algorithms like collaborative filtering, content-based filtering, or deep learning models based on the data and platform characteristics.<br><br>**Expert 2:**<br><br>1. **Prioritize data quality and cleansing:** Ensure data consistency, accuracy, and completeness to improve the quality of recommendations.<br>2. **Implement user feedback mechanisms:** Encourage users to provide feedback on their satisfaction with recommendations.<br>3. **Integrate with marketing automation tools:** Automatically deliver personalized recommendations to users based on their behavior and preferences.<br><br>**Expert 3:**<br><br>1. **Establish clear data privacy and ethical guidelines:** Implement robust data security measures and comply with relevant privacy regulations.<br>2. **Focus on personalization and context:** Recommend products and services based on individual user characteristics, browsing history, and purchase history.<br>3. **Continuously monitor and optimize recommendations:** Regularly evaluate the performance of the recommendation system and make adjustments based on user behavior and feedback.<br><br>**Analysis:**<br><br>| **Step** | **Expert 1** | **Expert 2** | **Expert 3** |<br>|---|---|---|---|<br>| 1 | 5 | 4 | 3 |<br>| 2 | 4 | 5 | 1 |<br>| 3 | 3 | 3 | 5 |<br>| 4 | 5 | 4 | 2 |<br>| 5 | 5 | 5 | 1 |<br><br>**Consensus:**<br><br>The collaborative process led to a comprehensive and balanced solution. Expert 1 focused on data analysis and recommendation engine selection, Expert 2 prioritized data quality and user feedback, and Expert 3 emphasized ethical considerations and personalization.<br><br>**Final Solution:**<br><br>1. **Build a robust recommendation engine** that leverages collaborative filtering and deep learning techniques.<br>2. **Implement comprehensive data cleansing and privacy safeguards.**<br>3. **Integrate the recommendation system with marketing automation tools** to personalize recommendations and improve user engagement.<br>4. **Continuously monitor and optimize the system** based on user behavior and feedback.</pre><p>This result adheres to ToT principles but can benefit from further refinement in clarity and structure, e.g. A more targeted LLM or prompt optimization might produce deeper and more nuanced reasoning per step. At all Tree-of-Thought reasoning involves breaking problems into multiple reasoning paths and validating the solution through logical consistency. While this example is simple, the same approach scales to complex tasks in navigation, decision-making, and AI reasoning.</p><h4>Chain of Thought (CoT) Vs Self-Consistency Vs Tree of Thought (ToT)</h4><p>While all three — Chain of Thought (CoT), Self-Consistency, and Tree of Thought (ToT) — are prompting techniques used to enhance reasoning abilities in large language models, the key difference lies in how they structure the thought process: CoT follows a linear chain of reasoning, Self-Consistency generates multiple reasoning paths to find the most consistent answer, and ToT uses a tree-like structure to explore multiple potential solutions and backtrack when necessary, offering a more complex and flexible approach to problem-solving.</p><p><strong>1. Chain of Thought (CoT):</strong></p><ul><li>CoT is a reasoning framework where the model generates step-by-step intermediate reasoning before reaching the final answer.</li><li>It works by explicitly modeling the intermediate steps required for logical reasoning.</li></ul><p>Example: <strong>“What is 23 + 45?”</strong></p><p><strong>CoT:</strong> “23 + 45 = 23 + 40 + 5 = 63 + 5 = 68.”</p><p><strong>2. Self-Consistency (SC):</strong></p><ul><li>SC enhances CoT by sampling multiple reasoning paths and then selecting the most consistent answer (majority voting).</li><li>It assumes that the most plausible reasoning path leads to the correct answer and mitigates errors due to individual path failures.</li></ul><p>Example: <strong>“What is 23 + 45?”</strong></p><p><strong>SC:</strong> Multiple reasoning paths generated (e.g., CoT1 = 68, CoT2 = 68, CoT3 = 70). Majority answer is 68.</p><p><strong>3. Tree of Thought (ToT):</strong></p><ul><li>ToT generalizes CoT by introducing branching reasoning paths where different “thoughts” are explored simultaneously.</li><li>At each step, the process evaluates which branch to continue, combining systematic exploration with reasoning evaluation.</li></ul><p>Example: <strong>“What is 23 + 45?”</strong></p><p><strong>ToT:</strong> Branch 1 explores “23 + 40 = 63, 63 + 5 = 68,” while Branch 2 explores alternatives like “20 + 45 = 65, 65 + 3 = 68.” The tree converges to the correct result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sdb87t4GsuSA-zUgEN_Pw.png" /><figcaption>Table 3. CoT Vs Self-Consistency Vs ToT, Table by Author</figcaption></figure><h3>Final Thoughts</h3><p>The realm of artificial intelligence is vast, intricate, and ever-evolving. As we’ve journeyed through the intricacies of prompt engineering, it’s evident that this field is more than just a technical endeavor — it’s a bridge between human intent and machine understanding. It’s the subtle art of asking the right questions to elicit the desired answers.</p><p>Prompt engineering, though a relatively new discipline, holds the key to unlocking the full potential of AI models, especially Large Language Models. As these models become increasingly integrated into our daily lives, the importance of effective communication cannot be overstated. Whether it’s a voice assistant helping with daily tasks, a chatbot providing customer support, or an AI tool aiding researchers, the quality of interaction hinges on the prompts that guide them.</p><p>For data enthusiasts, professionals, and even the general public, understanding prompt engineering is not just about better AI communication. It’s about envisioning a future where AI seamlessly blends into our lives, augmenting our capabilities and enriching our experiences.</p><p><em>Please feel free to connect with me on ,</em><a href="https://www.linkedin.com/in/arashnicoomanesh/"><em> LinkedIn</em></a><em> , </em><a href="https://www.kaggle.com/arashnic"><em>Kaggle</em></a><em> or </em><a href="https://x.com/ANicoomanesh"><em>X</em></a><em> .</em></p><h4>References:</h4><ol><li><em>Sewon Min et al. 2022, “Rethinking the Role of Demonstrations: What Makes In-Context Learning Work? “</em></li><li><em>Takeshi Kojima , 2023, “Large Language Models are Zero-Shot Reasoners “</em></li><li><em>Zhuosheng Zhang et al. 2023, “AUTOMATIC CHAIN OF THOUGHT PROMPTING IN LARGE LANGUAGE MODELS”</em></li><li><em>Xuezhi Wang et al. 2022, “Self-Consistency Improves Chain of Thought Reasoning in Language Models”</em></li><li><em>Shichao Sun et al. 2024, “Prompt Chaining or Stepwise Prompt? Refinement in Text Summarization”</em></li><li><em>Jason Wei et al. 2023, “Chain-of-Thought Prompting Elicits Reasoning in Large Language Models”</em></li><li><em>Denny Zhou , et al. 2023, “LEAST-TO-MOST PROMPTING ENABLES COMPLEX REASONING IN LARGE LANGUAGE MODELS”</em></li><li><em>Jules White , et al. 2023, “A Prompt Pattern Catalog to Enhance Prompt Engineering with ChatGPT”</em></li><li><em>Xinyun Chen, et al. 2023, “UNIVERSAL SELF-CONSISTENCY FOR LARGE LANGUAGE MODEL GENERATION”</em></li><li><a href="https://www.vellum.ai/author/anita-kirkovska"><em>Anita Kirkovska</em></a><em> ,2023, “Tree of Thought Prompting: What It Is and How to Use It”</em></li><li><em>Shunyu Yao, et al. 2023, “Tree of Thoughts: Deliberate Problem Solving with Large Language Models”</em></li><li><em>Pranab Sahoo, et al. 2024, “A Systematic Survey of Prompt Engineering in Large Language Models: Techniques and Applications”</em></li><li><em>Banghao Chen, et al. 2024, “Unleashing the potential of prompt engineering in Large Language Models: a comprehensive review”</em></li><li><a href="https://substack.com/@cwolferesearch"><em>Cameron R. Wolfe, Ph.D.</em></a><em> , 2023, “Chain of Thought Prompting for LLMs”</em></li><li><em>Gemma Cookbook, </em><a href="https://github.com/google-gemini/gemma-cookbook"><em>github</em></a><em> : “A collection of guides and examples for </em><a href="https://ai.google.dev/gemma/"><em>Google Gemma</em></a><em>.”</em></li><li><em>Mistral Cookbook, </em><a href="https://github.com/mistralai/cookbook?tab=readme-ov-file"><em>github</em></a><em> : “Features examples contributed by Mistralers and the community”</em></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c7b8459d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>