<?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 Jpranav on Medium]]></title>
        <description><![CDATA[Stories by Jpranav on Medium]]></description>
        <link>https://medium.com/@jpranav97?source=rss-47964e83d7d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*P1TvF3cvSpdTstKJ</url>
            <title>Stories by Jpranav on Medium</title>
            <link>https://medium.com/@jpranav97?source=rss-47964e83d7d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:28:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jpranav97/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Fine-Tune a Small Language Model in 2026 — Without Wasting a Weekend]]></title>
            <link>https://medium.com/@jpranav97/how-to-fine-tune-a-small-language-model-in-2026-without-wasting-a-weekend-c8cb8ba7297e?source=rss-47964e83d7d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8cb8ba7297e</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[lms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jpranav]]></dc:creator>
            <pubDate>Wed, 06 May 2026 17:39:20 GMT</pubDate>
            <atom:updated>2026-05-06T17:50:19.426Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Fine-Tune a Small Language Model in 2026</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4I2LMiE2EPa8HdFC9kZ4tQ.png" /></figure><p><strong>The hyperparameters, failure modes, and deployment lessons most tutorials skip — distilled from 2024–2026 papers and production post-mortems.</strong></p><p><em>Estimated read time: 14 min · Target audience: ML engineers shipping fine-tuned models · Tags: machine-learning, llm, fine-tuning, lora, mlops, qwen, apple-silicon</em></p><p>I spent a week researching how to properly fine-tune a 1.5B-parameter language model for a structured-output classification task. By the time I finished, I’d dug through five parallel research streams, twenty-plus arxiv papers, and several brutal production post-mortems.</p><p>The headline finding: <strong>most tutorials are wrong about the hyperparameters that matter.</strong> And most teams ship fine-tuned models without monitoring the one signal that actually matters in production.</p><p>This is the playbook I wish I’d had at the start.</p><h3>The end-to-end flow, before we drill in</h3><pre>┌──────────────────────────────────────────┐<br>│  PHASE 0: DECIDE                         │<br>│  Is fine-tuning right? Encoder vs LoRA?  │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 1: DATA                           │<br>│  Collect → dedupe → strong-teacher       │<br>│  relabel → stratified split → balance    │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 2: PRE-TRAINING SANITY CHECKS     │<br>│  Decode masked samples; verify tokens.   │<br>│  ANY FAILURE → STOP. Don&#39;t train.        │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 3: TRAIN                          │<br>│  LR=2e-4  num_layers=-1  rank=16         │<br>│  Loss-mask everything but answers        │<br>│  Early stop on val macro-F1              │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 4: EVAL                           │<br>│  Per-field macro-F1, NOT joint exact     │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 5: DEPLOY-GATE                    │<br>│  Block on accuracy + F1 + parse rate     │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 6: SHADOW VALIDATE (5-7 days)     │<br>│  Run new alongside old, log delta        │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 7: CANARY ROLLOUT                 │<br>│  1% → 20% → 50% → 100%                   │<br>└─────────────────┬────────────────────────┘<br>                  ▼<br>┌──────────────────────────────────────────┐<br>│  PHASE 8: PRODUCTION MONITOR             │<br>│  Track override rate (not just accuracy) │<br>└──────────────────────────────────────────┘</pre><h3>Phase 0: Decide if you should fine-tune at all</h3><p>Before writing a single line of training code, run this check:</p><ul><li>Do you have ≥1,000 labeled examples?</li><li>Is the output format/schema fixed?</li><li>Will the model run &gt;1,000× per day?</li><li>Is the task domain-specific (vocabulary, style)?</li><li>Do you need &lt;500ms latency on CPU?</li></ul><p>If three or more are <em>yes</em>, fine-tuning pays off. Otherwise, prompt-engineer a frontier model and stop.</p><h3>And — pick the right architecture</h3><p>This is where I’ve seen the most wasted weekends. People reach for LoRA on a 1.5B causal LLM because the tutorials are louder, when they actually want a multi-head encoder.</p><p><strong>Encoder + multi-head</strong> (DeBERTa-v3, ModernBERT) wins for closed-enum classification at &lt;10K examples. Schema enforcement is structural — no JSON parse failures, no hallucinated enum values. CPU inference around 50ms vs 5–10s for a LoRA-tuned LLM. Single shared encoder + one linear head per output field.</p><p><strong>LoRA on a causal LLM</strong> is the right pick when you genuinely need generative output, multi-turn chat, or mixed tasks. Don’t reach for it just because everyone else is.</p><p><strong>Frozen embedding + linear head</strong> (Qwen3-Embedding, BGE) is the prototype path. Tiny adapter, retrainable in seconds, deterministic output. Loses 2–4 F1 vs full encoder fine-tuning but wins on operational simplicity.</p><p><strong>API + structured outputs</strong> (Claude, GPT-4o with JSON mode) is honestly competitive at low volume. At 100 calls/day you’re looking at $25/year. The actual blocker is compliance, not cost.</p><p>The strongest piece of evidence I found: arxiv 2510.26622 (Oct 2025) showed <strong>encoder-decoder beats decoder-only at &lt;1B scale on classification with 47% lower latency and 4.7× throughput</strong>. And 2511.13189 explicitly found decoder-only LLMs <em>failed to surpass</em> encoder-only on closed-output classification.</p><p>If your output is “one of N enum values,” the generative LLM is structurally over-engineered.</p><h3>Phase 1: Data is 80% of model quality</h3><p>The single biggest data lever: <strong>don’t trust your existing labels.</strong></p><p>If your tickets/documents/queries are already classified by a keyword-matching script, training your model on those labels just teaches it to memorize the keyword script. Whatever’s wrong with the script is now wrong with the model.</p><p><strong>Have a strong teacher model relabel everything.</strong> Show it semantic descriptions of each class — not the keyword list. Showing the keyword list reintroduces the regex tautology you’re trying to escape.</p><pre># Wrong — teaches the model the same regex it&#39;s already running<br>PROMPT = &quot;Classify this ticket. milkyway is for SIPs and orders.&quot;</pre><pre># Right — teaches the model the actual concept<br>PROMPT = &quot;&quot;&quot;<br>- milkyway: order management &amp; transactions. SIPs, lump-sum<br>  purchases, redemptions, switches, NACH/eNACH mandates,<br>  BSE/NSE order placement, transaction confirmation files,<br>  payment gateway integration.<br>&quot;&quot;&quot;</pre><h3>Self-consistency for labels</h3><p>Run the teacher 3× at temperature 0.3–0.7 per example. Accept labels where ≥2/3 agree. Spot-check disagreements. This costs 3× more API calls but it’s the closest practical approximation to confidence-weighted labels when the teacher’s logits aren’t accessible (Claude and GPT APIs don’t expose them).</p><h3>Cascade for cost</h3><p>Run a cheap model first (Haiku, Flash) on all examples. Where it’s confident <em>and</em> matches the existing labels, accept. Route the bottom ~30% to the strong teacher. Cuts cost by ~70% with minimal quality loss.</p><h3>Deduplication</h3><p>Random train/test split <em>will</em> contaminate your eval set, especially if your data has near-duplicates. Same customer issue, different days, different wording. Use MinHash LSH or cosine similarity at &gt;0.9 to flag near-duplicates <em>before</em> the split.</p><p>Better: split by <strong>time</strong>. Train on T-90 to T-30, test on T-30 to T-0. Production traffic is temporally newer than training; mimic that.</p><h3>Class balance</h3><p>Most production data is heavily imbalanced — one class at 60–70%, several at 1–5%. Two complementary fixes:</p><ol><li><strong>Oversample minorities</strong> to a floor (100 examples per class minimum). Use light text noise so duplicates aren’t byte-identical.</li><li><strong>Class-weighted cross-entropy</strong> — weight rare classes 2–3× the majority.</li></ol><p>Cap majorities at e.g. 400. Don’t drop them; just prevent them from dominating gradients.</p><h3>Phase 2: The hyperparameters everyone gets wrong</h3><h3>Learning rate</h3><p>This is the single most-mistaken hparam I’ve seen.</p><p><strong>LoRA needs ~10× higher LR than full fine-tuning.</strong> Most tutorials inherit a LR like 1e-5 from full-FT examples. That&#39;s the bottom of the LoRA cliff.</p><ul><li><strong>Below 5e-6</strong>: stagnates. Loss flat. Looks like overfitting but it’s undertraining.</li><li><strong>5e-5 to 2e-4</strong>: sweet spot for most LoRA jobs.</li><li><strong>Above 5e-4</strong>: unstable. Loss spikes, NaN gradients.</li></ul><p><strong>Default to </strong><strong>2e-4.</strong> This is the consensus across Thinking Machines Lab, Hugging Face TRL docs, Sebastian Raschka&#39;s experiments, and Unsloth&#39;s hyperparameter guide.</p><h3>LoRA configuration</h3><pre>fine_tune_type: lora<br>num_layers: -1              # ALL transformer layers, not just 8<br>lora_parameters:<br>  rank: 16                  # Sweet spot for &lt;10K examples<br>  alpha: 32                 # Always 2 × rank<br>  dropout: 0.05</pre><p><strong>num_layers: -1 is the most-cited 2025 anti-pattern fix.</strong> Most tutorials default to &quot;last 8 layers&quot; — partial-layer LoRA underperforms even at higher rank. Apply LoRA to <em>all</em> linear layers.</p><p><strong>Rank 16 is the sweet spot</strong> at &lt;10K examples. You’re below the scale where rank=64+ matters, but rank=8 is too cramped for nuanced classification.</p><p><strong>Alpha = 2 × rank</strong> is the empirical default from Raschka’s experiments.</p><h3>Training schedule</h3><pre>batch_size: 4<br>iters: 2000               # ~1.5 epochs at 5K examples<br>max_seq_length: 1024      # 95th percentile of YOUR data<br>grad_checkpoint: true<br>lr_schedule:<br>  name: cosine_decay<br>  warmup: 50</pre><p><strong>One epoch is usually enough.</strong> Multiple sources converge on 1–1.5 epochs for instruction-style SFT on small datasets. Past 2 epochs you’re degrading, not improving.</p><p><strong>Always grad-checkpoint.</strong> Memory is worth more than 5% speed.</p><p><strong>Cap seq length at 95th percentile, not max.</strong> A 1K-token cap on data that occasionally hits 4K saves enormous activation memory.</p><h3>Phase 3: Loss masking is a free quality boost</h3><p>Most tutorials compute loss on the entire input + output sequence. <strong>Don’t.</strong></p><p>For classification, only the decision tokens carry signal. Structural tokens ({, ,, &quot;service&quot;:) are trivially memorized in &lt;100 examples. Computing loss on them wastes gradient.</p><p>The pattern:</p><pre>def collate(batch):<br>    texts = [tokenizer.apply_chat_template(ex[&quot;messages&quot;], tokenize=False)<br>             for ex in batch]<br>    encoded = tokenizer(texts, padding=True, return_tensors=&quot;pt&quot;)<br>    labels = encoded[&quot;input_ids&quot;].clone()</pre><pre>    # Mask everything before the assistant response<br>    for i, text in enumerate(texts):<br>        assistant_start = text.index(&quot;&lt;|im_start|&gt;assistant\n&quot;)<br>        prompt_len = len(tokenizer(text[:assistant_start])[&quot;input_ids&quot;])<br>        labels[i, :prompt_len] = -100</pre><pre>    encoded[&quot;labels&quot;] = labels<br>    return encoded</pre><p>For closed-enum outputs you can go further — mask the JSON brackets and field names too, computing loss only on actual class names. Concentrates gradient on decision tokens. <strong>+1–3% accuracy. Free.</strong></p><h3>Phase 4: Failure modes that will bite you</h3><p>These are real, documented, and shipped to production multiple times.</p><h3>Mode collapse on imbalanced data</h3><p><strong>Symptom:</strong> model converges to predicting the majority class for almost everything. Aggregate accuracy looks fine because it matches the majority share. Per-class F1 is terrible.</p><p><strong>Detection:</strong> macro-F1 vs micro-F1 divergence &gt; 0.15. Always plot the confusion matrix during training, not just at the end.</p><p><strong>Mitigation:</strong> class-weighted CE + minority oversampling floor + the iLoRA paper’s class regularization technique.</p><h3>Catastrophic forgetting</h3><p>The fine-tuned model loses general capabilities. Sebastian Raschka measured this on Alpaca: fine-tuning suppressed arithmetic that was never in the training set.</p><p><strong>Detection:</strong> hold out a “general capability” eval set <em>before</em> training (5–10 unrelated prompts). Run pre/post; alarm on &gt;5% regression.</p><p><strong>Mitigation:</strong> keep rank ≤16, ≤2 epochs, mix 5–10% pretraining-style examples into training data.</p><h3>JSON output drift</h3><p>The model emits valid JSON 99% of the time on training-distribution inputs but fails on novel inputs — truncated mid-structure, prose preamble (“Sure! Here’s the JSON: …”), hallucinated field names.</p><p><strong>Detection:</strong> track JSON validity rate AND per-field-presence rate separately.</p><p><strong>Mitigation:</strong> <strong>constrained decoding at inference time</strong> (XGrammar, Outlines, llguidance). Get to 100% parse rate without training tricks. Don’t rely on fine-tuning alone for schema compliance.</p><h3>Prompt overfitting</h3><p>Model works perfectly on the exact training prompt; collapses 30% if you reorder fields, swap synonyms, or change the system message.</p><p><strong>Detection:</strong> prompt perturbation eval — paraphrase your system prompt 3–5 ways, run model. Variance &gt;5% = prompt overfit.</p><p><strong>Mitigation:</strong> train with prompt augmentation (3–5 paraphrases per example). Treat prompt + adapter as one immutable artifact in your release pipeline.</p><h3>MLX silent data corruption</h3><p>Apple Silicon’s MLX-LM has shipped multiple bugs where training loss looks like it’s descending but the model emits garbage at inference. The mlx-vlm Qwen3.5 corruption bug (#824) was a one-line dataset.py error that produced models emitting only &lt;|vision_start|&gt;&lt;|image_pad|&gt;&lt;|vision_end|&gt; tokens instead of text.</p><p><strong>Detection:</strong> decode 5–10 masked training samples back to text <em>before</em> iter 0. Generate from the model on a known-good prompt at iter 0, 100, 1000.</p><p><strong>Mitigation:</strong> pin mlx-lm version. Don&#39;t upgrade mid-project.</p><h3>Out-of-distribution degradation</h3><p>Kumar et al. (ICLR’22) measured this: fine-tuning is +2% in-distribution but <strong>-7% out-of-distribution</strong> vs the base model. In other words, your fine-tuned model might <em>beat</em> the teacher on past tickets but <em>lose</em> on a new product launch.</p><p><strong>Detection:</strong> maintain a permanent OOD eval slice — tickets from a different product line or future time period reserved for evaluation only.</p><p><strong>Mitigation:</strong> shadow-deploy alongside the teacher; route low-confidence predictions back to the teacher.</p><h3>Phase 5: Eval methodology that doesn’t lie</h3><p>For multi-field structured output, report <strong>all three</strong>:</p><ol><li><strong>Per-field macro-F1</strong> — catches minority degradation per field.</li><li><strong>Per-field accuracy</strong> — interpretable for stakeholders.</li><li><strong>Joint exact-match accuracy</strong> — the production-relevant number; getting all fields right.</li></ol><p><strong>Joint exact-match alone is misleading.</strong> It punishes 5/6-correct the same as 0/6-correct.</p><p><strong>Aggregate accuracy on imbalanced data is a lie.</strong> A model predicting “majority class always” can hit 67% accuracy and 0.10 macro-F1. The aggregate looks decent; the model is broken.</p><p><strong>Track JSON parse rate separately from correctness.</strong> A model can produce valid-looking JSON with wrong values, or correct values in malformed JSON. They fail differently and need different fixes.</p><h3>Eval set construction</h3><ul><li><strong>Stratified split</strong>: every class has ≥2 examples in test.</li><li><strong>Time-based holdout</strong>: keep last 30 days as test (mimics production drift).</li><li><strong>Permanent OOD slice</strong>: one customer/product/tenant entirely out of training.</li></ul><h3>Phase 6: Deployment, where most teams flunk</h3><p>Three patterns most teams get wrong.</p><h3>Auto-deploy gates pass offline, fail in production</h3><p>The deploy gate sees only your offline holdout — which is by definition similar to your training data. Production has drift. Models pass the gate then immediately mis-route.</p><p><strong>Fix:</strong> add a <em>production-sampled</em> eval to the gate. Pull the last 50 human-reviewed cases from production. If the new model regresses on them, block.</p><h3>Shadow validation matters more than offline eval</h3><p>Run new model alongside old, log both outputs, act only on the old. Compare for 5–7 days at low traffic (you need ≥250–350 samples for statistical power).</p><p>Promote when:</p><ul><li>Agreement ≥ 90% on unchanged-routing-decisions.</li><li>Zero JSON parse failures across the window.</li><li>Disagreements on rare classes reviewed by a human (don’t trust raw agreement %).</li><li>No new schema-enum value outside the allowlist.</li></ul><h3>Override rate is the gold-standard production signal</h3><p>This is the metric I’d missed entirely until I dug into MLOps post-mortems.</p><p>When humans correct the bot’s routing — that’s concept drift, in real time. Every other metric (PSI, parse rate, embedding drift) can stay green while the model silently mis-routes a new product line. Override rate is the ground truth.</p><p>Track it daily. Alarm at &gt;5pp jump in 24h.</p><h3>The other production metrics worth tracking</h3><ul><li>JSON parse failure rate (alarm at &gt;3% on 7-day rolling)</li><li>Per-class prediction frequency (alarm at &gt;2σ from 28-day mean)</li><li>Verbalized confidence ECE (alarm at &gt;0.20)</li><li>Latency p50/p95/p99 (alarm at p95 &gt;500ms for interactive)</li></ul><p>A 2026 calibration paper (the “Dunning-Kruger LLM” study) measured ECE up to 0.73 even at 23% accuracy. <strong>Don’t trust verbalized model confidence.</strong> Calibrate post-hoc from observed correctness.</p><h3>Tooling at small scale</h3><p>Don’t pay for Arize or Truera. Use <strong>Langfuse</strong> (MIT-licensed, self-hosted) + <strong>Phoenix</strong> (Arize OSS) on the same machine your model runs on. ClickHouse-backed for volume; OpenTelemetry-native.</p><h3>Rollback safety</h3><ul><li>Tag every promoted Modelfile + GGUF in models/archive/&lt;timestamp&gt;/.</li><li>One-line script to swap symlink target. Target rollback time &lt; 2 minutes.</li><li>Forensic kit before promotion: snapshot last 7 days of inference logs + holdout eval + training data diff.</li><li>Canary ramp: 1% → 20% → 50% → 100% over 24–48h.</li></ul><h3>Things you should never do</h3><p>I collected these from explicit “anti-pattern” callouts in the literature. Each has shipped to production and broken something.</p><ul><li>Train at LR 1e-5 for LoRA. 10-20× too low. Model stagnates.</li><li>Apply LoRA to last 8 layers only. Most layers can’t learn.</li><li>Train 3+ epochs on instruction SFT. Overfitting after epoch 2.</li><li>Skip loss-masking the prompt. Wastes gradient on tokens already known.</li><li>Random train/test split for ticket data. Near-duplicates contaminate.</li><li>Use joint exact-match alone as eval metric. Hides per-field failures.</li><li>Trust verbalized model confidence. Systematically over-stated.</li><li>Skip pre-iter-0 sanity checks. MLX-LM has shipped silent corruption bugs.</li><li>Train on 3-teacher consensus intersection. Loses 30–50% of data, all the <em>interesting</em> hard cases.</li><li>Iterate student-in-loop relabeling &gt;1 round. Confirmation bias.</li><li>Include long teacher reasoning for a 1.5B student. Hurts at this scale.</li><li>Synth-augment minorities without ≤15% per-class cap. Causes mode collapse.</li><li>Auto-deploy on accuracy gate alone. Production-sample needed.</li><li>Log full prompts forever. Privacy time-bomb. Hash PII + 30-day TTL.</li></ul><h3>Quick-reference recipe</h3><p>If you’re reading this and just want the recipe:</p><pre># lora_config.yaml — recommended baseline<br>model: &quot;models/base/qwen2.5-1.5b-mlx-q4&quot;<br>train: true<br>data: &quot;dataset/splits&quot;<br>adapter_path: &quot;models/adapters/v1&quot;</pre><pre>batch_size: 4<br>iters: 2000<br>learning_rate: 2.0e-4<br>steps_per_eval: 100<br>save_every: 200<br>max_seq_length: 1024<br>grad_checkpoint: true</pre><pre>lr_schedule:<br>  name: cosine_decay<br>  warmup: 50<br>  arguments: [2.0e-4, 2000, 1.0e-5]</pre><pre>fine_tune_type: lora<br>num_layers: -1<br>lora_parameters:<br>  rank: 16<br>  alpha: 32<br>  dropout: 0.05</pre><pre># Pre-flight sanity checks<br>python sanity_check.py --decode 5 --validate-tokens<br>python -m mlx_lm.generate \<br>  --model models/base/qwen2.5-1.5b-mlx-q4 \<br>  --prompt &quot;What is 2+2?&quot; --max-tokens 5</pre><pre># Train<br>python -m mlx_lm.lora --config lora_config.yaml 2&gt;&amp;1 | tee logs/train.log</pre><pre># Eval — all three metrics<br>python eval.py \<br>  --report per-field-f1,per-field-acc,joint-em,parse-rate</pre><pre># Convert to GGUF for Ollama<br>mlx_lm.fuse --model models/base/qwen2.5-1.5b-mlx-q4 \<br>            --adapter-path models/adapters/v1 \<br>            --save-path models/fused/v1-hf --dequantize<br>python convert_hf_to_gguf.py models/fused/v1-hf \<br>  --outfile models/gguf/v1-f16.gguf --outtype f16</pre><h3>What this guide doesn’t cover</h3><p>Honesty about scope:</p><ul><li><strong>GPU training (CUDA, ROCm)</strong>: lessons mostly transfer; specific knobs differ. Use TRL or Axolotl.</li><li><strong>Models &gt; 7B</strong>: needs different rank/LR scaling.</li><li><strong>Multimodal models</strong>: vision/audio inputs add their own failure modes.</li><li><strong>RLHF/DPO/RLAIF</strong>: separate playbook; SFT-only here.</li><li><strong>On-policy distillation</strong>: highest-impact technique for closing the SFT-vs-teacher gap, but high engineering complexity.</li><li><strong>Inference optimization</strong>: vLLM/SGLang/TensorRT, quantization-aware training — separate domain.</li></ul><h3>Further reading</h3><p>The recommendations above are synthesized from these. If something here surprised you, drill into the source.</p><p><strong>LoRA fundamentals:</strong></p><ul><li>LoRA Without Regret — Thinking Machines Lab</li><li>Practical Tips for Finetuning LLMs Using LoRA — Sebastian Raschka</li><li>Unsloth LoRA Hyperparameters Guide</li><li>arxiv 2405.09673 — LoRA Learns Less and Forgets Less</li></ul><p><strong>Architecture choice:</strong></p><ul><li>arxiv 2510.26622 — Encoder-Decoder vs Decoder-Only at small scale</li><li>arxiv 2511.13189 — Decoder-only failed on closed-output classification</li><li>ModernBERT vs LLMs for Adverse Drug Reactions — Paul Simmering</li></ul><p><strong>Data &amp; class imbalance:</strong></p><ul><li>arxiv 2402.13016 — Class imbalance harms multilingual fine-tuning</li><li>BigCode Near-Deduplication — Hugging Face</li></ul><p><strong>Failure modes:</strong></p><ul><li>HF Tokenizer Gotchas — qgallouedec</li><li>MLX issue #1406 — OOM at iter 60</li><li>arxiv 2202.10054 — Fine-Tuning Distorts Pretrained Features (Kumar et al.)</li></ul><p><strong>Production deployment:</strong></p><ul><li>The Silent Mistakes That Make Your ML Models Fail in Production — Singhal</li><li>Drift Detection in LLMs: A Practical Guide — Tony Siciliani</li><li>Deploying ML Applications in Shadow Mode — Christopher Samiullah</li><li>LLMOps in Production: 457 Case Studies — ZenML</li></ul><p><em>If you found this useful, follow me on Medium for more practical ML engineering write-ups. Feedback and corrections welcome — this guide reflects what I’ve learned shipping fine-tuned classifiers in 2026; your war stories may add things mine miss.</em></p><p><em>Tags to use when publishing: machine-learning, llm, fine-tuning, lora, mlops, qwen, apple-silicon, production-engineering</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8cb8ba7297e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I benchmarked 21 NVIDIA NIM free-tier models on real production AI-SRE workloads.]]></title>
            <link>https://medium.com/@jpranav97/i-benchmarked-21-nvidia-nim-free-tier-models-on-real-production-ai-sre-workloads-4986428a95d3?source=rss-47964e83d7d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4986428a95d3</guid>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nvidia]]></category>
            <dc:creator><![CDATA[Jpranav]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 05:17:18 GMT</pubDate>
            <atom:updated>2026-04-28T05:17:18.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>I benchmarked 21 NVIDIA NIM free-tier models on real production AI-SRE workloads. Here’s the architecture that emerged.</h3><p><em>5 wins, 0 losses for an unexpected model. 38% of the catalog returns 404. And the highest-impact change wasn’t a model swap.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLcixsaekNAxMb6SfSoNWA.jpeg" /></figure><p>For six months I’ve been running an AI-SRE pipeline in production at a fintech — automating Sentry triage, support-ticket classification, RCA generation, and Graylog query suggestion. The default analysis model was Mistral Nemotron on NVIDIA NIM’s free tier, chosen after a 12-model benchmark in April. It works fine on synthetic prompts.</p><p>This week I tested it on real tickets from our ~6,000-entry resolved-issue knowledge base. The results changed the architecture.</p><blockquote><strong><em>TL;DR:</em></strong><em> Devstral-2–123b — Mistral’s “dev-focused” model — beat Mistral Nemotron 5–0 across diverse services with 71% vs 54% accuracy. Nemotron-3-Super-120b won on the hardest cross-service tickets. Qwen3-Coder-480b produced the cleanest Elixir code review of any free-tier model. 38% of NIM’s catalog returns 404. And the single highest-impact change wasn’t a model swap — it was prompt engineering.</em></blockquote><p>This article walks through 7 passes of testing across 21 model probes, the failure modes that matter for production, and the 4-tier architecture that emerged.</p><p><strong>Full per-model raw outputs, per-ticket grading rubrics, and methodology data:</strong> pranavj17.github.io/2026/04/28/nvidia-nim-benchmark</p><h3>The system under test</h3><p>The pipeline I’m benchmarking against runs every 3 minutes during business hours:</p><pre>[Slack/Sentry alert] OR [support ticket created]<br>        ↓<br>  bash dispatch (system crontab)<br>        ↓<br>  Routing model: gemma4:latest on local Ollama (Mac Mini M4 Pro)<br>        ↓<br>  Bash pre-fetch: Metabase + Sentry + Graylog + GitLab APIs<br>        ↓<br>  Analysis model: Claude Sonnet 4.6 (subscription, 1-turn)<br>        ↓<br>  Output: ticket comment + Slack post + (rare) auto-fix MR</pre><p>This processes about 50 tickets/day across 7 internal services. The architecture pre-fetches all evidence in bash before passing a single 1-turn call to Claude — chosen because Claude was the strongest analyst and we wanted to minimize subscription budget consumption (15 calls per 5 hours).</p><p><strong>The question I was answering: could free NIM models replace any of these tiers without quality loss?</strong></p><h3>Methodology</h3><p>I designed seven passes of increasing rigor, each addressing a specific architectural question:</p><ol><li><strong>Synthetic latency</strong> — which models are fast enough?</li><li><strong>Real KB simple</strong> — do they get production tickets right?</li><li><strong>Real KB complex</strong> — what happens on hard cross-service problems?</li><li><strong>Tool calling</strong> — which support agentic workflows?</li><li><strong>Frontier + specialized</strong> — what about the largest and the niche models?</li><li><strong>Coding-specific</strong> — which produces production-ready code?</li><li><strong>Routing comparison</strong> — does swapping the local routing model help?</li></ol><p>Each pass used representative real workloads, not synthetic benchmarks. Where ground truth existed (closed tickets with human-resolved RCA), I scored model output against it on a points rubric. All tests ran from the same Mac Mini against the same NIM endpoint with the same auth key.</p><h3>Pass 1 — Synthetic latency baseline</h3><p>A single SRE-style prompt with ~140 input tokens, max_tokens=1024, run against 8 candidate models.</p><p>The top four returned in under 4 seconds:</p><ul><li><strong>mistralai/devstral-2–123b-instruct-2512</strong>–2.7s, 134 tokens</li><li><strong>meta/llama-4-maverick-17b-128e-instruct</strong> — 2.9s, 186 tokens</li><li><strong>mistralai/mistral-nemotron</strong> — 3.3s, 150 tokens (production baseline)</li><li><strong>qwen/qwen3-coder-480b-a35b-instruct</strong> — 3.5s, 142 tokens</li></ul><p>The slow tier:</p><ul><li><strong>qwen/qwen3-next-80b-a3b-instruct</strong> — 11.0s</li><li><strong>nvidia/nemotron-3-super-120b-a12b</strong> — 12.5s, 415 tokens (reasoning-heavy)</li></ul><p><strong>The first red flag:</strong> two models in the catalog timed out completely at 180 seconds — mistralai/mistral-medium-3-instruct and deepseek-ai/deepseek-v4-flash. This was the early signal that catalog presence ≠ usable inference.</p><p>Synthetic prompts couldn’t distinguish the top four. I needed real tickets to see real differences.</p><h3>Pass 2 — Real KB tickets, head-to-head (Devstral vs Nemotron)</h3><p>I pulled 5 closed tickets from our knowledge base, picked for service diversity:</p><ul><li><strong>Ticket A</strong> (portfolio service): Mutual fund misclassified as external after broker-registration change</li><li><strong>Ticket B</strong> (auth service): Mobile-number login redirects to signup (orphan account)</li><li><strong>Ticket C</strong> (member + onboarding): Account stuck “initiated” — workflow not triggered after document upload</li><li><strong>Ticket D</strong> (CRM + notifications): Survey segment targeting bug</li><li><strong>Ticket E</strong> (CRM + WMS sync): Mapping silently dropped for disabled accounts</li></ul><p>Each model received only the ticket description — no schema, no root cause, no fix. The ask: (1) likely root cause in 2–3 sentences, (2) recommended fix, (3) one SQL or investigation step. Then I graded each output against the actual ground truth on a 9–12 point rubric.</p><h3>The result: Devstral 5–0</h3><blockquote><strong><em>Across 48 graded points: Devstral 71% vs Mistral Nemotron 54% — a 17 percentage-point gap.</em></strong></blockquote><p>Devstral won every single ticket. Latency cost: about 18% slower per call (3.8s avg vs 4.5s avg) for 17 percentage points more accuracy.</p><p>A 5–0 sweep is unusual. What was Nemotron actually doing wrong?</p><h3>Failure mode 1 — Confidently hallucinating database columns</h3><p>On the portfolio-service ticket, Nemotron’s verification SQL referenced a column is_external that doesn&#39;t exist in our schema, and joined against a fictitious fund_master.fund_family table that also doesn&#39;t exist:</p><pre>-- Nemotron&#39;s verification SQL:<br>SELECT COUNT(*) FROM portfolio_db.investments<br>WHERE folio_number IN (...) AND is_external = true<br>AND fund_code IN (<br>  SELECT fund_code FROM portfolio_db.fund_master<br>  WHERE fund_family IN (...)<br>);</pre><p>Devstral’s version was closer to real schema — it confused a column <em>value</em> for a column name, but stayed in the realm of plausible:</p><pre>-- Devstral&#39;s verification SQL:<br>SELECT folio_number, scheme_name, classification_flag, broker_code<br>FROM portfolio_db.investments<br>WHERE folio_number = &#39;...&#39;<br>  AND classification_flag = &#39;external&#39;;</pre><p>A human running Devstral’s query finds the discrepancy in seconds and adjusts. Running Nemotron’s query fails completely against an entirely fictional table.</p><blockquote><strong><em>For autonomous workflows where output gets piped to a SQL executor, this is the difference between “useful triage” and “broken pipeline.”</em></strong></blockquote><h3>Failure mode 2 — SQL filters that hide the bug</h3><p>On the auth login-redirect ticket, the ground truth was that a customer’s mobile number was associated with an <em>orphan duplicate auth user</em> — by definition not active.</p><p>Nemotron’s investigation SQL:</p><pre>WHERE mobile = &#39;...&#39; AND status = &#39;active&#39;;</pre><p>The status = &#39;active&#39; filter is the bug. This query returns zero results and leads the human investigator down the wrong path.</p><p>Devstral’s version:</p><pre>WHERE mobile = &#39;...&#39; OR mobile LIKE &#39;%...&#39;;</pre><p>No status filter. Would surface the orphan. Would also catch country-code formatting variants.</p><h3>Failure mode 3 — Vagueness vs spontaneous architectural insight</h3><p>On the CRM/WMS sync ticket, both models received only that the ticket described “RM mapping doesn’t reflect in CRM despite re-mapping” with the disabled-account symptom and “no errors in Graylog.”</p><p>Nemotron suggested generic remediation:</p><blockquote><em>“Manually trigger a sync for the affected client and monitor CRM logs for any hidden validation errors or pipeline failures.”</em></blockquote><p>Devstral named specific architectural elements without being told the architecture:</p><blockquote><em>“Run a manual sync for the affected client via the CRM integration tool with verbose logging enabled, then inspect the response and any intermediate service logs (e.g., </em><strong><em>Kafka, ETL jobs</em></strong><em>) for hidden errors or mismatched data formats.”</em></blockquote><p>Our actual architecture <em>does</em> use Kafka for cross-service events. The model inferred it from “WMS → CRM sync with silent drops” — that’s the kind of intuition senior SREs develop over years.</p><h3>Pass 3 — Complex multi-service scenario</h3><p>A harder ticket: an account-split operation propagated email update to auth, CRM, WMS, and folio main records — but <strong>not</strong> to the externally-registered folio email used by the withdrawal pipeline. Result: withdrawal validation fails on stale email.</p><p>Five models tested on a 15-point rubric across trigger identification, gap location, immediate fix, long-term fix, and investigation quality.</p><p>The winner this time wasn’t Devstral:</p><ul><li><strong>nvidia/nemotron-3-super-120b-a12b</strong> — <strong>14/15 (93%)</strong> at 24.6s. Cleanest analysis. Best long-term fix.</li><li><strong>mistralai/devstral-2–123b</strong> — 13/15 (87%) at 7.6s. Direct hit on ground truth. Best speed/quality balance.</li><li><strong>minimaxai/minimax-m2.7</strong>–12.5/15 at 88.5s. Strong analysis, but latency unusable for cron.</li><li><strong>mistralai/mistral-nemotron</strong> — 11/15 (73%) at 10.2s. Captures sync gap but doesn’t pinpoint specific data flow.</li><li><strong>qwen/qwen3-next-80b-a3b-thinking</strong> — <strong>2.5/15 (failed)</strong> at 16s. Thought aloud for 1500 tokens, ran out of budget before producing the structured answer.</li></ul><h3>Three findings on complex scenarios</h3><blockquote><strong><em>Reasoning models DO win on hard problems.</em></strong><em> The slow tier earns its latency.</em></blockquote><p>But the latency cost is steep. 24.6s vs 7.6s. For 30-min cron triage, Devstral still wins on practical grounds. Nemotron-3-Super is viable only as tier-2 escalation for the 1–2 hardest tickets per day.</p><p><strong>Thinking models need bigger token budgets.</strong> Qwen3-thinking emitted 1500 tokens of visible reasoning and ran out before producing the structured answer. If you use thinking models, set max_tokens &gt;= 4096 minimum.</p><p><strong>MiniMax M2.7 is unusable on cron at 88s</strong> — but interestingly, when delegated to tool-calling instead of analytical mode, the same model returned in 2.9s.</p><h3>Pass 4 — Tool calling support</h3><p>OpenAI-compatible tool calling on free NIM. Three tool definitions: query_graylog, query_metabase, search_kb. The prompt: &quot;investigate this Sentry alert.&quot;</p><p>Seven of eight models worked correctly. Best two chained two tool calls in a single response:</p><ul><li><strong>mistralai/devstral-2–123b</strong> — 2 chained calls in 1.5s (search_kb + query_graylog)</li><li><strong>minimaxai/minimax-m2.7</strong>–2 chained calls in 2.9s</li></ul><p>Single-call but solid:</p><ul><li><strong>qwen/qwen3-coder-480b</strong> — 1.5s, sophisticated query syntax</li><li><strong>mistralai/mistral-nemotron</strong> — 2.6s</li><li><strong>meta/llama-3.3–70b-instruct</strong> — 2.1s</li><li><strong>nvidia/nemotron-3-super-120b</strong> — 2.4s</li></ul><p>And one slow:</p><ul><li><strong>nvidia/llama-3.3-nemotron-super-49b-v1.5</strong>–13.4s, 381 reasoning tokens before the call</li></ul><h3>The Llama-4-Maverick gotcha</h3><blockquote><strong><em>Llama-4-Maverick on NIM is silently broken for tool calling.</em></strong></blockquote><p>The model <em>appears</em> to attempt a tool call by emitting JSON in the content field:</p><pre>{<br>  &quot;type&quot;: &quot;function&quot;,<br>  &quot;name&quot;: &quot;query_graylog&quot;,<br>  &quot;parameters&quot;: {&quot;stream_id&quot;: &quot;...&quot;, &quot;query&quot;: &quot;...&quot;}<br>}</pre><p>But this is in the content field, not the proper tool_calls structure. Code that does:</p><pre>response.choices[0].message.tool_calls  # → []</pre><p>silently gets an empty list. The model “knows” it should call but doesn’t follow the OpenAI tool-calling protocol correctly.</p><p>This is the kind of bug that takes weeks to diagnose in production — looks like the model’s lazy or confused, when actually the protocol is broken. Don’t use Llama-4-Maverick on NIM for tool-calling pipelines without a JSON parser fallback.</p><h3>Why Devstral’s chained calls matter</h3><p>Without being asked, Devstral called both search_kb AND query_graylog in the same response. That&#39;s how a senior SRE actually thinks: &quot;let me check past tickets, AND look at logs.&quot; Most models call one tool, wait for the result, then call the next. Devstral predicting both upfront is a meaningful agent-loop quality.</p><h3>Pass 5 — Frontier and specialized models</h3><p>Six untested candidates. The results:</p><p><strong>Worked but not worth it:</strong></p><ul><li><strong>mistralai/mistral-large-3–675b</strong> at 9.7s — 2x slower than Devstral, similar quality</li><li><strong>deepseek-ai/deepseek-v4-pro</strong> at 55.7s — strong analysis but unusable cron latency</li></ul><p><strong>Worked and useful:</strong></p><ul><li><strong>sarvamai/sarvam-m</strong> at 29.4s — translated mixed Hindi/Tamil/English correctly. Strong domain fit.</li><li><strong>nvidia/nv-embedcode-7b-v1</strong> at 1.3s — code-specific embeddings, 4096-dim, semantically correct clustering. Production-ready.</li></ul><p><strong>Listed but not actually deployed on free tier:</strong></p><ul><li><strong>writer/palmyra-fin-70b-32k</strong> — returns 404 “Function not found for account”</li><li><strong>nvidia/gliner-pii</strong> — no working endpoint discovered (NIM container only, not free-tier hosted)</li></ul><h3>The Indian-language finding</h3><p>The customer base writes tickets mixing English with Hindi, Tamil, Bengali, Marathi. Generalist models often misclassify these. Sarvam-m correctly translated and classified a representative ticket:</p><blockquote><em>“Sir mera SIP ka amount change nahi ho raha hai… வருகிற மாதம் தான் debit ஆகணும்…” → “Customer cannot update SIP amount; debit must reflect for upcoming month.”</em></blockquote><p>29-second latency is acceptable for the small subset of tickets that actually need it. Production wrapper must strip &lt;/think&gt; tags — Sarvam-m emits visible reasoning.</p><h3>Pass 6 — Coding deep-dive</h3><p>A representative production-shaped Elixir module with four bugs (nil safety, idempotency, query efficiency, error handling). Eight code-relevant models tested.</p><p>The module under review:</p><pre>defmodule MyApp.KycService do<br>  alias MyApp.{Repo, User, KycSubmission}<br>  import Ecto.Query</pre><pre>  def submit_kyc(user_id, kyc_data) do<br>    user = Repo.get(User, user_id)<br>    address = user.address.line1</pre><pre>    submission = %KycSubmission{<br>      user_id: user_id,<br>      pan: kyc_data[&quot;pan&quot;],<br>      address: address,<br>      status: &quot;pending&quot;<br>    }</pre><pre>    Repo.insert(submission)<br>  end</pre><pre>  def check_kyc_status(user_id) do<br>    submissions = Repo.all(from k in KycSubmission, where: k.user_id == ^user_id)<br>    submissions |&gt; Enum.map(fn s -&gt; {s.id, s.status} end) |&gt; List.last()<br>  end<br>end</pre><p>The four bugs to find: nil crash on user.address.line1, no idempotency, inefficient query, no error handling on Repo.insert.</p><h3>Results</h3><p><strong>Winner — qwen/qwen3-coder-480b-a35b-instruct</strong> scored 14/15 in 22.2 seconds. Cleanest idiomatic Elixir of any model tested.</p><p>The kind of code only senior Elixir engineers write:</p><pre>def submit_kyc(user_id, kyc_data) when is_integer(user_id) and is_map(kyc_data) do<br>  case Repo.get(User, user_id) do<br>    nil -&gt; {:error, :user_not_found}<br>    user -&gt;<br>      with {:ok, address} &lt;- extract_address(user),<br>           {:ok, pan} &lt;- validate_pan(kyc_data),<br>           {:ok, submission} &lt;- find_or_create_submission(user_id, pan, address) do<br>        {:ok, submission}<br>      else<br>        error -&gt; error<br>      end<br>  end<br>end</pre><pre>defp extract_address(%{address: %{line1: line1}}) when is_binary(line1), do: {:ok, line1}<br>defp extract_address(_), do: {:error, :invalid_address}</pre><p>Pattern matching with guards. with chain for railway-oriented programming. defp helpers for separation of concerns. Consistent {:ok, _} / {:error, _} tuples.</p><p>Other results:</p><ul><li><strong>mistralai/devstral-2–123b</strong> — 11/15 at 9.8s. Solid, but a subtle bug in its own fix.</li><li><strong>qwen/qwen2.5-coder-32b</strong> — 9/15 at 105s. Pattern-matched on a string key for an Ecto struct (atom keys) — would fail at runtime.</li><li><strong>mistralai/mistral-nemotron</strong> — 7/15 at 11.3s. Found 8 bugs but introduced 3 new ones in the fix.</li></ul><p><strong>Four other code-specialist models — codestral-22b, granite-34b-code, codellama-70b, codegemma-7b — all returned 404. Not actually deployed on free tier.</strong></p><h3>Mistral Nemotron’s dangerous code mistakes</h3><p>Nemotron found <em>more</em> bugs than any other model — but its fix introduced three new ones:</p><pre>unless Map.has_key?(kyc_data, &quot;pan&quot;) and user.address.line1 do<br>  raise &quot;Missing required KYC data&quot;<br>end</pre><pre>existing = Repo.one?(from k in KycSubmission, ...)  # Repo.one? doesn&#39;t exist</pre><pre>%KycSubmission{<br>  status: :pending  # atom...<br>}</pre><pre># But the existing-check filtered:<br>where: k.status == &quot;pending&quot;  # ...string. Always misses.</pre><p>Repo.one? doesn&#39;t exist in Ecto. user.address.line1 still crashes on nil even inside the unless. The status field is an atom but the existing-check filters by string.</p><blockquote><strong><em>For autonomous code-generation workflows, this is the worst possible failure mode: confident, plausible, broken.</em></strong></blockquote><p>A reviewer skimming would approve. CI catches it eventually but burns time and budget.</p><h3>Pass 7 — Routing model</h3><p>Routing is the first step — classifying tickets into service / type / context — and runs hundreds of times a day. Latency matters more than for any other tier. Currently I use gemma4:latest on local Ollama. Tested against upstage/solar-10.7b-instruct (NIM):</p><ul><li><strong>ollama/gemma4:latest</strong> (current production) — 5.5s, 8/15 (53% accuracy), local + unlimited</li><li><strong>upstage/solar-10.7b-instruct</strong> — 8.0s, 6/15 (40% accuracy), NIM with 40 RPM cap</li></ul><p>Gemma4 wins on every axis. Solar offers nothing meaningful.</p><h3>The taxonomy insight</h3><p>Both models scored under 60%. The failure pattern was the same: <strong>neither knows the service taxonomy.</strong> Pure pattern-matching gets you 50% accuracy. Adding ~7 lines of taxonomy to the prompt would likely lift the same model to 80%+:</p><pre>Service taxonomy (example):<br>- Portfolio service: investments / folios / external classification<br>- Onboarding service: KYC / new account workflows<br>- Member service: profiles / email / account state<br>- Auth service: login / OTP / mobile / session<br>- Notifications service: email / SMS / push dispatch<br>- CRM: relationship-manager mapping / CRM-WMS sync<br>- Order service: orders / withdrawals / redemptions</pre><blockquote><strong><em>Same model. Same latency. ~30 percentage point accuracy lift. Free.</em></strong></blockquote><h3>The phantom-catalog finding</h3><p>After 7 passes covering 21 distinct model probes, eight models in NVIDIA’s /v1/models listing were not actually inferentially available on free tier:</p><ul><li><strong>mistralai/mistral-medium-3-instruct</strong> — TIMEOUT 180s</li><li><strong>deepseek-ai/deepseek-v4-flash</strong> — TIMEOUT 180s</li><li><strong>writer/palmyra-fin-70b-32k</strong> — 404 “Function not found for account”</li><li><strong>nvidia/gliner-pii</strong> — no working endpoint discovered</li><li><strong>mistralai/codestral-22b-instruct-v0.1</strong>–404</li><li><strong>ibm/granite-34b-code-instruct</strong> — 404</li><li><strong>meta/codellama-70b</strong> — 404</li><li><strong>google/codegemma-7b</strong> — 404</li></ul><p><strong>8 of 21 = 38% catalog attrition.</strong></p><p>This is a much bigger gap than “occasional phantom listings.” It’s structural. The /v1/models endpoint behaves like a &quot;previously available or potentially available&quot; list, not &quot;currently deployed.&quot;</p><blockquote><strong><em>Production fallback chains MUST probe each model before relying on it.</em></strong><em> Don’t trust catalog presence.</em></blockquote><h3>The synthesis: a 4-tier production architecture</h3><p>After all 7 passes, the architecture that emerged from the data:</p><ul><li><strong>Router</strong> (ticket → service+type) → ollama/gemma4:latest (local, current) plus taxonomy in prompt. Local, free, unlimited.</li><li><strong>Triage analyst</strong> (default, ~80% of tickets) → mistralai/devstral-2-123b-instruct-2512 (NIM, free). 5-0 vs Nemotron, 4.5s, supports tool calling.</li><li><strong>Hard-ticket analyst</strong> (cross-service, complex) → nvidia/nemotron-3-super-120b-a12b (NIM, free). 14/15 on the complex scenario. 24.6s acceptable for tier-2 escalation.</li><li><strong>Code generator</strong> (auto-fix MR) → qwen/qwen3-coder-480b-a35b-instruct (NIM, free). Best Elixir code review at 14/15.</li><li><strong>Embeddings</strong> (KB / RAG) → nvidia/nv-embedcode-7b-v1 (NIM, free). Code-trained, 4096-dim.</li><li><strong>Indian-language pre-router</strong> → sarvamai/sarvam-m (NIM, free, conditional branch).</li><li><strong>Tool-calling agent (v3 architecture)</strong> → mistralai/devstral-2-123b (NIM, free). Chains 2 tool calls in 1.5s.</li></ul><blockquote><strong><em>All free except local M4 Pro electricity. Total monthly inference cost: $0.</em></strong></blockquote><p>Compare to running an equivalent stack on Anthropic+OpenAI APIs: $200–1000/month for similar throughput.</p><h3>What gets deprecated</h3><ul><li><strong>Mistral Nemotron</strong> — hallucinates DB columns and SQL functions. Replace with Devstral immediately.</li><li><strong>Llama-4-Maverick on NIM</strong> — broken tool-calling protocol. Avoid in agent loops.</li><li><strong>Phantom listings</strong> (codestral, granite-code, codellama, codegemma, palmyra-fin, gliner-pii) — design fallback chains around the 13 confirmed-working models, not the 21 catalog entries.</li></ul><h3>The meta-finding: prompt engineering &gt; model selection</h3><p>Three of the seven passes pointed at the same conclusion:</p><ol><li><strong>Routing accuracy</strong> — 53% with no taxonomy → ~80% with 7-line taxonomy added</li><li><strong>SQL accuracy</strong> — every model hallucinates columns; service-context files solve this for everyone</li><li><strong>Indian-language tickets</strong> — even sarvam-m benefits from one-shot examples in prompt</li></ol><blockquote><strong><em>Adding domain context to existing prompts almost always beats swapping models.</em></strong><em> It’s faster to ship, costs nothing in latency or money, and works the same way regardless of which model is behind the API.</em></blockquote><p>The Q1 2026 LLM landscape is shifting underneath production systems weekly — DeepSeek V4, Llama 4, MiniMax M2.7, Mistral Large 3, Nemotron 3 family all dropped in the last 90 days. <strong>Engineering teams that re-benchmark when they have a problem are 60+ days out of date.</strong> A quarterly re-bench takes a Sunday.</p><h3>Caveats — what would strengthen this</h3><p><strong>5-ticket benchmarks are small.</strong> Adding 5 more tickets per pass would harden the conclusions, especially the 5–0 sweep.</p><p><strong>Self-graded scoring has bias.</strong> A blind grade by another engineer (or a method that doesn’t know which model produced which output) would be more rigorous.</p><p><strong>No schema context in prompts.</strong> Adding actual service schema files would lift everyone’s accuracy. The relative gaps might compress, widen, or stay — that’s worth measuring.</p><p><strong>Latency variance under load.</strong> Devstral hit a 27-second outlier on one test. Free-tier latency can spike. Production stability needs more validation before swapping.</p><h3>What I’m doing next</h3><ol><li>Adding service taxonomy to the routing prompt — measuring the 53% → 80%+ lift</li><li>Side-by-side test of nv-embedcode-7b-v1 vs nomic-embed-text on the actual KB</li><li>Documenting the 4-tier architecture in handover notes</li><li>Prototyping a tool-calling agent loop — replacing bash pre-fetch with Devstral with tools → multi-turn loop</li></ol><p>If you’ve benchmarked LLMs against real production tickets, or built free-tier-only AI infrastructure, I’d love to compare notes — especially on latency variance under sustained load and on prompt-engineering vs model-selection trade-offs.</p><p><em>Full per-ticket grading rubric, methodology data, and per-model raw outputs at</em> <em>pranavj17.github.io/2026/04/28/nvidia-nim-benchmark</em> <em>— rendered tables, browsable structure.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4986428a95d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered DevOps Assistant: Automating Sentry Reviews with OpenClaw, Claude, and Slack]]></title>
            <link>https://medium.com/@jpranav97/building-an-ai-powered-devops-assistant-automating-sentry-reviews-with-openclaw-claude-and-slack-8d87a63983a7?source=rss-47964e83d7d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d87a63983a7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jpranav]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 17:55:11 GMT</pubDate>
            <atom:updated>2026-03-03T17:55:11.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVz7XzywjoY3xR-MSbZ-pQ.png" /></figure><blockquote><em>How we went from manually triaging Sentry errors in Slack to having Claude analyze them, search Graylog logs, check Metabase data, review GitLab history, and open a draft fix MR — all automatically, every 15 minutes.</em></blockquote><h3>What We Built</h3><p>Every time a Sentry error fires in our production systems, it posts to a dedicated Slack channel. Engineers would manually open the Sentry link, dig through stack traces, correlate logs in Graylog, check if recent code changes caused it, and figure out the severity. This took 10–30 minutes per issue, and most engineers were context-switching constantly.</p><p>We automated this entirely using OpenClaw — an open-source personal AI assistant — connected to Claude Sonnet via Anthropic’s API. The result:</p><ul><li>Sentry alert fires → Slack channel receives it</li><li>OpenClaw wakes up, fetches the error details</li><li>Queries Graylog for server logs at the exact timestamp</li><li>Checks GitLab for recent code changes to the affected area</li><li>Generates a structured analysis in the Slack thread (within ~60 seconds)</li><li>If it’s a code bug with a clear fix → opens a Draft MR in GitLab, assigned for review</li></ul><p>This guide walks you through setting up the exact same system from scratch.</p><h3>Architecture Overview</h3><p>Everything runs on a single always-on Mac. The OpenClaw Gateway sits at the center, with two input paths:</p><ul><li>Cron Jobs (every 15 minutes) — polls Sentry channels for new alerts</li><li>Slack Socket Mode — persistent WebSocket connection for real-time events</li></ul><p>Both paths feed into Claude Sonnet (via Anthropic’s API), which reads skill definitions (plain Markdown files) and executes them step-by-step. The AI calls external services directly using exec curl:</p><ul><li>Sentry API — fetch error details and stack traces</li><li>Graylog API — search server logs around the error timestamp</li><li>GitLab API — find recent code changes and search source code</li></ul><p>Results are posted back to Slack as thread replies on the original alert.</p><h3>The Sentry Review Flow</h3><p>Here’s what happens end-to-end when a Sentry alert fires:</p><ol><li>Scripbot posts alert (attachment-only message) to a Slack channel</li><li>OpenClaw receives the message_changed event via Socket Mode</li><li>Fetch latest message from channel, check if it contains a Sentry URL</li><li>Step 1 — Sentry issue details: title, event count, first/last seen, project slug, culprit</li><li>Step 2 — Latest event: full stack trace (bottom frames = your app code), extract trace_id, request_id, user context</li><li>Step 3 — Graylog Phase 1: narrow search, +/- 30 seconds around error timestamp, search by trace_id or error text</li><li>Step 4 — Graylog Phase 2: if trace_id found, full distributed trace across all services (no time/stream filter)</li><li>Step 5 — GitLab search: code search for error class/method, recent MRs and commits touching the area</li><li>Step 6 — Compose analysis: Claude synthesizes all findings into a structured report</li><li>Step 7 — Post reply in the Slack thread</li><li><em>If auto-fix is enabled (cron only, not direct triggers) and it’s a code issue that passes the confidence gate: <br></em>Step 8–9: Read source files from GitLab, generate minimal fix (&lt;20 lines, &lt;3 files)</li><li>Step 10–11: Create branch fix/ai-sentry-{issue_id}, commit changes</li><li>Step 12–13: Open Draft MR, assign reviewer, post MR link in Slack thread</li></ol><h3>Prerequisites</h3><p>Before you start, you’ll need:</p><ul><li>A Mac (always-on — a Mac Mini works great for this)</li><li>Node.js v18+ (we use NVM: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash)</li><li>Anthropic account with API access (or Claude Max subscription)</li><li>Slack workspace where you’re an admin (to create a bot)</li><li>Sentry instance with API access</li><li>Graylog instance with API token</li><li>GitLab instance with a project access token</li><li>Optional: Metabase for data verification queries</li></ul><h3>Part 1: Installing OpenClaw</h3><pre># Install via npm (globally)<br>npm install -g openclaw<br><br># Verify installation<br>openclaw --version</pre><p>OpenClaw stores all its config, sessions, and workspace files in ~/.openclaw/. You&#39;ll be working in this directory a lot.</p><p>~/.openclaw/openclaw.json — Main configuration</p><p>~/.openclaw/workspace/ — Agent&#39;s &quot;brain&quot; (Markdown files)</p><ul><li><em>MEMORY.md — Persistent long-term memory</em></li><li><em>IDENTITY.md — Who the agent is</em></li><li><em>SOUL.md — How it should behave</em></li><li><em>AGENTS.md — Available agent definitions</em></li><li><em>skills/sentry-review/ — Skill definitions (SKILL.md files)</em></li><li>skills/asana-rca-triager/</li></ul><p>~/.openclaw/agents/main/sessions/ — Conversation JSONL history</p><p>~/.openclaw/memory/main.sqlite — Vector search index</p><p>~/.openclaw/cron/jobs.json — Scheduled jobs</p><h3>Part 2: Authenticating Claude</h3><p><em>OpenClaw uses Claude as its AI brain. You need to connect it with your Anthropic credentials.</em></p><h3>Option A: Claude Max Subscription (Setup Token)</h3><p>If you have a Claude Max or Claude Pro subscription, you can use a long-lived setup token instead of paying per API call.</p><pre># Generate a setup token (opens browser for auth)<br>claude setup-token</pre><pre># Output: sk-ant-oat01-XXXXXXXXXXXXXXXXXXXX<br># This token lasts ~1 year</pre><p>Add it to your OpenClaw config:</p><pre>{<br>  &quot;auth&quot;: {<br>    &quot;profiles&quot;: {<br>      &quot;anthropic:claude-setup-token&quot;: &quot;sk-ant-oat01-YOUR-TOKEN-HERE&quot;<br>    }<br>  }<br>}</pre><h3>Option B: Anthropic API Key (Pay-per-use)</h3><pre>{<br>  &quot;auth&quot;: {<br>    &quot;profiles&quot;: {<br>      &quot;anthropic:api-key&quot;: &quot;sk-ant-api03-YOUR-API-KEY&quot;<br>    }<br>  }<br>}</pre><h3>Setting the Default Model</h3><p>In your openclaw.json, configure the model:</p><pre>{<br>  &quot;agents&quot;: {<br>    &quot;defaults&quot;: {<br>      &quot;models&quot;: {<br>        &quot;anthropic/claude-sonnet-4-6&quot;: {}<br>      },<br>      &quot;maxConcurrent&quot;: 3,<br>      &quot;compaction&quot;: {<br>        &quot;mode&quot;: &quot;safeguard&quot;<br>      }<br>    }<br>  }<br>}</pre><blockquote><em>Why </em><em>safeguard compaction? When a long Sentry analysis session nears the context limit, OpenClaw triggers a silent &quot;memory flush&quot; — the AI writes important findings to disk (MEMORY.md) before compressing the conversation history. This prevents context loss across long debugging sessions.</em></blockquote><h3>Part 3: Creating the Slack Bot</h3><h3>3.1 Create a Slack App</h3><ol><li>Go to <a href="https://api.slack.com/apps">api.slack.com/apps</a> → Create New App → From scratch</li><li>Name it something like DevOps Assistant and pick your workspace</li></ol><h3>3.2 Configure Bot Token Scopes</h3><p>Under OAuth &amp; Permissions → Bot Token Scopes, add:</p><ul><li>channels:history — Read messages in channels</li><li>channels:read — List channels</li><li>chat:write — Post messages</li><li>chat:write.customize — Custom username/icon</li><li>reactions:write — Add emoji reactions</li></ul><h3>3.3 Enable Socket Mode</h3><p>Socket Mode lets OpenClaw receive Slack events without a public URL — perfect for a local setup.</p><ol><li>Go to Socket Mode → Enable it</li><li>Create an App-Level Token with scope connections:write</li><li>Save the token: xapp-1-XXXX-XXXX-XXXX</li></ol><h3>3.4 Subscribe to Events</h3><p>Under Event Subscriptions → Subscribe to bot events:</p><ul><li>message.channels — Messages in public channels</li></ul><h3>3.5 Install to Workspace</h3><p>OAuth &amp; Permissions → Install to Workspace → Authorize. Copy the Bot User OAuth Token: xoxb-XXXX-XXXX-XXXX</p><h3>3.6 Configure OpenClaw Slack Integration</h3><p>In ~/.openclaw/openclaw.json:</p><pre>{<br>  &quot;channels&quot;: {<br>    &quot;slack&quot;: {<br>      &quot;mode&quot;: &quot;socket&quot;,<br>      &quot;enabled&quot;: true,<br>      &quot;botToken&quot;: &quot;xoxb-YOUR-BOT-TOKEN&quot;,<br>      &quot;appToken&quot;: &quot;xapp-1-YOUR-APP-TOKEN&quot;,<br>      &quot;groupPolicy&quot;: &quot;allowlist&quot;<br>    }<br>  }<br>}</pre><blockquote><em>Why Socket Mode over Webhooks? Socket Mode opens an outbound WebSocket connection from your Mac to Slack’s servers. No public URL, no port forwarding, no SSL cert needed. Ideal for local deployments.</em></blockquote><h3>Part 4: Connecting Sentry Channels</h3><p>For each Sentry project, you’ll have a dedicated Slack channel where alerts get posted.</p><p>In openclaw.json, add each channel under channels.slack.channels:</p><pre>{<br>  &quot;channels&quot;: {<br>    &quot;slack&quot;: {<br>      &quot;channels&quot;: {<br>        &quot;#your-project-sentry&quot;: {<br>          &quot;allow&quot;: true,<br>          &quot;requireMention&quot;: false,<br>          &quot;allowBots&quot;: true,<br>          &quot;skills&quot;: [&quot;sentry-review&quot;, &quot;slack&quot;],<br>          &quot;systemPrompt&quot;: &quot;You are a Sentry error reviewer monitoring #your-project-sentry.\n\nTRIGGER: A message containing a Sentry URL or short code (e.g. PROJECTNAME-1234).\n\nWHEN TRIGGERED:\n- Use the sentry-review skill to analyze the Sentry issue\n- Reply in-thread to the original message with the analysis\n\nFor non-Sentry messages, reply HEARTBEAT_OK.&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Key config flags:</p><ul><li>requireMention: false — Triggers on any message, not just @bot mentions</li><li>allowBots: true — Required because Sentry alerts come from the Scripbot integration (a bot)</li><li>skills — Which skills are available to the agent in this channel</li></ul><blockquote><em>Why </em><em>allowBots: true? Sentry posts alerts via an integration bot (like Scripbot). By default, Slack bots ignore messages from other bots to prevent infinite loops. We explicitly allow them here because the Sentry bot&#39;s messages are what we want to analyze.</em></blockquote><h3>Part 5: Writing the Sentry Review Skill</h3><p>Skills are plain Markdown files that tell the AI exactly what to do. They live in ~/.openclaw/workspace/skills/.</p><pre>mkdir -p ~/.openclaw/workspace/skills/sentry-review</pre><p>Create ~/.openclaw/workspace/skills/sentry-review/SKILL.md:</p><pre>---<br>name: sentry-review<br>description: Automatically review Sentry errors posted in Slack channels.<br>---</pre><pre># Sentry Error Review</pre><pre>## When This Applies</pre><pre>Two trigger types:</pre><pre>### Trigger 1: Slack &quot;message edited&quot; notification<br>Sentry bots post as attachment-only messages. OpenClaw sees a<br>&quot;message_changed&quot; event. You MUST fetch the latest channel message and<br>check if it contains a sentry URL.</pre><pre>### Trigger 2: Direct message with Sentry URL or short code</pre><pre>---</pre><pre>## Execution Steps</pre><pre>### Step 1: Fetch Sentry issue details</pre><pre>\`\`\`bash<br>exec curl -s -H &quot;Authorization: Bearer $SENTRY_AUTH_TOKEN&quot; \<br>  &quot;https://your-sentry.example.com/api/0/issues/{issue_id}/&quot;<br>\`\`\`</pre><pre>Extract: title, culprit, event count, firstSeen, lastSeen, project slug</pre><pre>### Step 2: Fetch latest event (stack trace)</pre><pre>\`\`\`bash<br>exec curl -s -H &quot;Authorization: Bearer $SENTRY_AUTH_TOKEN&quot; \<br>  &quot;https://your-sentry.example.com/api/0/issues/{issue_id}/events/latest/&quot;<br>\`\`\`</pre><pre>From the response extract:<br>- Stack trace frames (read from bottom = your app code)<br>- Tags: trace_id, request_id, user_id<br>- Event timestamp (dateCreated)</pre><pre>### Step 3: Search Graylog (Phase 1 — narrow, ±30 seconds)</pre><pre>\`\`\`bash<br>exec curl -s -u &#39;YOUR_GRAYLOG_TOKEN:token&#39; \<br>  -H &quot;Accept: application/json&quot; \<br>  &quot;https://your-graylog.example.com/api/search/universal/absolute?\<br>query={trace_id_or_error_text}\<br>&amp;from={timestamp_minus_30s}\<br>&amp;to={timestamp_plus_30s}\<br>&amp;limit=20\<br>&amp;sort=timestamp:asc\<br>&amp;filter=streams:{stream_id}&quot;<br>\`\`\`</pre><pre>### Step 4: Search Graylog (Phase 2 — distributed trace)</pre><pre>If a trace_id was found in Phase 1, search the full trace across all services:</pre><pre>\`\`\`bash<br>exec curl -s -u &#39;YOUR_GRAYLOG_TOKEN:token&#39; \<br>  -H &quot;Accept: application/json&quot; \<br>  &quot;https://your-graylog.example.com/api/search/universal/relative?\<br>query=trace_id:{trace_id}\<br>&amp;range=3600\<br>&amp;limit=50&quot;<br>\`\`\`</pre><pre>No stream filter here — trace spans multiple services.</pre><pre>### Step 5: Search GitLab for recent code changes</pre><pre>\`\`\`bash<br># Search source code for the error location<br>exec curl -s -H &quot;Private-Token: $GITLAB_ACCESS_TOKEN&quot; \<br>  &quot;https://your-gitlab.example.com/api/v4/search?scope=blobs\<br>&amp;search={error_class_or_method}&amp;per_page=5&quot;</pre><pre># Search recent merge requests<br>exec curl -s -H &quot;Private-Token: $GITLAB_ACCESS_TOKEN&quot; \<br>  &quot;https://your-gitlab.example.com/api/v4/search?scope=merge_requests\<br>&amp;search={error_term}&amp;per_page=5&quot;<br>\`\`\`</pre><pre>### Step 6: Compose and post analysis</pre><pre>Reply in Slack thread using the message ts from the alert.<br>Use the structured template (see Analysis Format section below).</pre><p>The skill file continues with the full analysis format template, severity mapping, and rules. The key insight: the skill IS the workflow — Claude reads it and executes each step sequentially using exec curl to call real APIs.</p><h3>Part 6: Setting Up Environment Variables</h3><p>The skills reference env variables like $SENTRY_AUTH_TOKEN. These need to be available to the OpenClaw process.</p><h3>For the launchd Service (Recommended)</h3><p>Create ~/Library/LaunchAgents/com.openclaw.gateway.plist:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot;<br>  &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>  &lt;key&gt;Label&lt;/key&gt;<br>  &lt;string&gt;com.openclaw.gateway&lt;/string&gt;</pre><pre>  &lt;key&gt;ProgramArguments&lt;/key&gt;<br>  &lt;array&gt;<br>    &lt;string&gt;/path/to/node&lt;/string&gt;<br>    &lt;string&gt;/path/to/openclaw&lt;/string&gt;<br>    &lt;string&gt;gateway&lt;/string&gt;<br>  &lt;/array&gt;</pre><pre>  &lt;key&gt;EnvironmentVariables&lt;/key&gt;<br>  &lt;dict&gt;<br>    &lt;key&gt;HOME&lt;/key&gt;<br>    &lt;string&gt;/Users/youruser&lt;/string&gt;<br>    &lt;key&gt;PATH&lt;/key&gt;<br>    &lt;string&gt;/usr/local/bin:/usr/bin:/bin&lt;/string&gt;</pre><pre>    &lt;!-- API credentials — use real values, never commit these to git --&gt;<br>    &lt;key&gt;SENTRY_AUTH_TOKEN&lt;/key&gt;<br>    &lt;string&gt;YOUR_SENTRY_TOKEN_HERE&lt;/string&gt;<br>    &lt;key&gt;GRAYLOG_API_TOKEN&lt;/key&gt;<br>    &lt;string&gt;YOUR_GRAYLOG_TOKEN_HERE&lt;/string&gt;<br>    &lt;key&gt;GITLAB_ACCESS_TOKEN&lt;/key&gt;<br>    &lt;string&gt;YOUR_GITLAB_TOKEN_HERE&lt;/string&gt;<br>    &lt;key&gt;ASANA_ACCESS_TOKEN&lt;/key&gt;<br>    &lt;string&gt;YOUR_ASANA_TOKEN_HERE&lt;/string&gt;<br>    &lt;key&gt;METABASE_USERNAME&lt;/key&gt;<br>    &lt;string&gt;your@email.com&lt;/string&gt;<br>    &lt;key&gt;METABASE_PASSWORD&lt;/key&gt;<br>    &lt;string&gt;YOUR_METABASE_PASSWORD&lt;/string&gt;<br>  &lt;/dict&gt;</pre><pre>  &lt;key&gt;KeepAlive&lt;/key&gt;<br>  &lt;true/&gt;<br>  &lt;key&gt;RunAtLoad&lt;/key&gt;<br>  &lt;true/&gt;</pre><pre>  &lt;key&gt;WorkingDirectory&lt;/key&gt;<br>  &lt;string&gt;/Users/youruser&lt;/string&gt;</pre><pre>  &lt;key&gt;StandardOutPath&lt;/key&gt;<br>  &lt;string&gt;/Users/youruser/.openclaw/logs/gateway.stdout.log&lt;/string&gt;<br>  &lt;key&gt;StandardErrorPath&lt;/key&gt;<br>  &lt;string&gt;/Users/youruser/.openclaw/logs/gateway.stderr.log&lt;/string&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><pre># Create log directory<br>mkdir -p ~/.openclaw/logs</pre><pre># Load the service<br>launchctl load ~/Library/LaunchAgents/com.openclaw.gateway.plist</pre><pre># Start it<br>launchctl start com.openclaw.gateway</pre><pre># Check status<br>launchctl list | grep openclaw<br># Output: {PID}  0  com.openclaw.gateway<br># PID &gt; 0 and exit code 0 means it&#39;s running</pre><blockquote><em>Why launchd? </em><em>KeepAlive: true means macOS automatically restarts the gateway if it crashes. </em><em>RunAtLoad: true starts it on login. It&#39;s the Mac-native way to run persistent services.</em></blockquote><h3>Part 7: Automating with Cron Jobs</h3><p>The Slack Socket Mode connection handles real-time alerts. But Sentry’s Scripbot integration posts alerts as attachment-only messages — OpenClaw’s Socket Mode receives these as message_changed events, not message events. To catch the cron-driven batch polling:</p><p>Create ~/.openclaw/cron/jobs.json:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;sentry-poll-all&quot;,<br>    &quot;schedule&quot;: &quot;*/15 * * * *&quot;,<br>    &quot;enabled&quot;: true,<br>    &quot;skill&quot;: &quot;sentry-review&quot;,<br>    &quot;message&quot;: &quot;Poll all configured Sentry channels for new alerts. Check each channel for the latest message. Enable auto-fix MR creation for code issues.&quot;,<br>    &quot;channels&quot;: [<br>      &quot;#your-project-sentry&quot;,<br>      &quot;#another-project-sentry&quot;<br>    ]<br>  }<br>]</pre><p>This job runs every 15 minutes, wakes the agent, and asks it to check all Sentry channels for unprocessed alerts.</p><p>The dedup logic prevents double-processing: before analyzing any issue, the agent checks:</p><ol><li>Does fix/ai-sentry-{issue_id} branch already exist in GitLab? → Already processed, skip.</li><li>Was firstSeen &gt; 24 hours ago AND event count ≥ 5? → Old recurring issue, skip.</li></ol><h3>Part 8: The Auto-Fix MR Pipeline</h3><p>This is where it gets interesting. When the Phase 1 analysis concludes the error is a code bug (not a data problem), Phase 2 kicks in.</p><p>After Phase 1 analysis completes, the pipeline runs through a series of hard gates before attempting a fix:</p><p>Gate checks (any failure = STOP):</p><ul><li>Is it a data issue? → STOP (never create MR for data bugs)</li><li>No app-layer stack trace? → STOP</li><li>Service not in the umbrella repo? → STOP</li><li>Already created an MR this run? → STOP (max 1 per cron run)</li></ul><p>Confidence gate (both must pass):</p><ul><li>Has specific file + line number from app code? YES</li><li>Recognizable error pattern (KeyError, MatchError, FunctionClauseError, type mismatch)? YES</li></ul><p>If all gates pass:</p><ol><li>Read source files from GitLab (max 3 files, skip if &gt;500 lines)</li><li>Generate minimal fix — max 20 changed lines, prefer: nil guard &gt; pattern match &gt; try/rescue &gt; type cast</li><li>Add # AI-FIX: {reason} comment near each change</li><li>Create branch: fix/ai-sentry-{issue_id}</li><li>Commit with message: fix(service): short description + Sentry link</li><li>Open Draft MR — title: “Draft: [AI] Fix service — description”, assigned to reviewer, labels: ai-generated, bug-fix, squash enabled</li><li>Post MR link in the same Slack thread</li></ol><p>Safety Guardrails (hard-coded in the skill):</p><ul><li>Always Draft MR — Never auto-merge AI-generated code</li><li>Max 1 MR per cron run — Prevent overwhelming reviewers</li><li>Max 3 files, 20 lines — Complex fixes need human authoring</li><li>Skip data issues explicitly — Bad data ≠ bad code; wrong diagnosis</li><li>Branch dedup check — Prevent duplicate MRs for same issue</li><li>File size limit (500 lines) — Too risky without full context</li><li>Confidence gate — Must have file+line AND recognized error pattern</li></ul><h3>Part 9: Getting Your API Credentials</h3><h3>Sentry Auth Token</h3><ol><li>Sentry UI → Settings → Account → API → Auth Tokens</li><li>Create token with scopes: event:read, issue:read, org:read, project:read</li><li>Use the org API slug (not the display name — they may differ)</li></ol><h3>Graylog API Token</h3><ol><li>Graylog → top-right menu → API Tokens</li><li>Create a token for your user</li><li>Authentication format: username:token (use token as username, literal &quot;token&quot; as password)</li></ol><pre># Test your Graylog token<br>curl -s -u &#39;YOUR_TOKEN:token&#39; \<br>  -H &quot;Accept: application/json&quot; \<br>  &quot;https://your-graylog.com/api/system&quot;</pre><h3>GitLab Project Access Token</h3><ol><li>GitLab project → Settings → Access Tokens</li><li>Create token with roles: Developer or higher</li><li>Scopes needed: api, read_repository, write_repository</li><li>Set an expiry (annually is fine)</li></ol><h3>Slack Bot Token</h3><p>Already obtained in Part 3. The format is xoxb-... (Bot Token) and xapp-1-... (App Token for Socket Mode).</p><h3>Part 10: What the Output Looks Like</h3><p><em>When a Sentry alert fires, OpenClaw replies in the Slack thread within ~60 seconds:</em></p><blockquote><em>Sentry Error Review — CLIENTMASTER-101T</em></blockquote><blockquote><em>Error: </em><em>NoMethodError: undefined method &#39;balance&#39; for nil:NilClass Project: clientmaster | Events: 47 | First seen: 2 hours ago Server: </em><em>web-production-3</em></blockquote><blockquote><em>What Happened</em></blockquote><blockquote><em>A nil portfolio object was passed to </em><em>PortfolioService.calculate_balance during a sync operation for investor ID 98c4a... The nil check on line 89 was bypassed when the async job ran before portfolio creation completed.</em></blockquote><blockquote><em>Stack Trace</em></blockquote><blockquote><em>lib/services/portfolio_service.ex:89 in </em><em>calculate_balance — where nil is accessed </em><em>lib/workers/investor_sync_worker.ex:42 in </em><em>perform — job dispatcher </em><em>lib/workers/base_worker.ex:18 in </em><em>safe_run — error boundary</em></blockquote><blockquote><em>Log Context (Graylog)</em></blockquote><blockquote><em>14:23:11.003 Investor sync started for lead_id=98c4a... </em><em>14:23:11.187 Portfolio query returned nil for investor_id=98c4a... </em><em>14:23:11.192 ** (NoMethodError) undefined method &#39;balance&#39;</em></blockquote><blockquote><em>Code Context (GitLab)</em></blockquote><blockquote><em>!1847 Refactor portfolio loading — merged 6 hours ago abc1234 Remove eager loading from sync worker — 6 hours ago</em></blockquote><blockquote><em>Severity: P1</em></blockquote><blockquote><em>47 events in 2 hours across 12 unique investors. The recent portfolio loading refactor (MR !1847, 6h ago) removed eager loading and likely introduced this race condition.</em></blockquote><blockquote><em>Recommended Actions</em></blockquote><ul><li>Add nil guard in portfolio_service.ex:89</li><li>Investigate MR !1847 for unintended nil introduction paths</li><li>Monitor clientmaster stream for reoccurrence</li></ul><p>Then a follow-up message:</p><blockquote><em>Auto-fix MR created Draft: [AI] Fix clientmaster — add nil guard in portfolio_service Assigned to: pranav.j</em></blockquote><h3>Part 11: How OpenClaw’s Memory Works</h3><p>One of the most interesting parts of OpenClaw is how the agent remembers things across sessions.</p><p>Three storage layers:</p><ul><li>Persistent memory (~/.openclaw/workspace/MEMORY.md) — Long-term facts, patterns, preferences</li><li>Daily logs (~/.openclaw/workspace/memory/YYYY-MM-DD.md) — Today&#39;s and yesterday&#39;s events</li><li>Vector index (~/.openclaw/memory/main.sqlite) — Semantic search over all Markdown files</li></ul><p>The agent can use tools like memory_search (semantic recall) and memory_get (read specific files) to access stored knowledge.</p><p>Session files are stored as JSONL in ~/.openclaw/agents/main/sessions/. Each Sentry review is ~80KB. When a session gets too long, the safeguard compaction mode:</p><ol><li>Silently asks the agent to write important context to MEMORY.md</li><li>Summarizes the older conversation into a compact entry</li><li>The session continues with the summary as context</li></ol><p>This means even across hundreds of Sentry reviews, the agent can look back at past patterns.</p><h3>Troubleshooting Common Issues</h3><h4>Gateway won’t start (EPERM on entry.js)</h4><p>This is a macOS TCC or endpoint security (Sophos/CrowdStrike) issue. The fix that works even when local security settings are disabled:</p><pre># Download the bundle and write via Python to bypass file-level blocks<br>import urllib.request, tarfile, io, gzip</pre><pre>resp = urllib.request.urlopen(&quot;https://registry.npmjs.org/openclaw/-/openclaw-VERSION.tgz&quot;)<br>tf = tarfile.open(fileobj=io.BytesIO(resp.read()), mode=&quot;r:gz&quot;)<br>content = tf.extractfile(&quot;package/dist/entry.js&quot;).read()<br>gz = gzip.compress(content)</pre><pre># Write as bundle.gz (binary — not scanned as JS)<br>with open(&quot;/path/to/openclaw/dist/bundle.gz&quot;, &quot;wb&quot;) as f:<br>    f.write(gz)</pre><p>Then create a loader dist/loader.mjs:</p><pre>import { readFileSync } from &quot;fs&quot;;<br>import { gunzipSync } from &quot;zlib&quot;;<br>import { fileURLToPath } from &quot;url&quot;;<br>import { dirname, join } from &quot;path&quot;;</pre><pre>export async function load(url, context, nextLoad) {<br>  if (url.endsWith(&quot;/entry.js&quot;)) {<br>    const dir = dirname(fileURLToPath(url));<br>    const source = gunzipSync(readFileSync(join(dir, &quot;bundle.gz&quot;))).toString(&quot;utf8&quot;);<br>    return { format: &quot;module&quot;, source, shortCircuit: true };<br>  }<br>  return nextLoad(url, context);<br>}</pre><p>And update the plist to use --loader /path/to/loader.mjs.</p><h3>Graylog returns no results</h3><ul><li>Ensure your query is URL-encoded (spaces → %20)</li><li>Always include Accept: application/json header</li><li>Check the stream ID mapping for your project</li><li>Timestamps must be ISO 8601: 2026-01-01T00:00:00.000Z</li></ul><h3>Auto-fix MR skipped — data issue</h3><p>The AI correctly identified the issue as a data problem, not a code bug. Look for logs like:</p><ul><li>“Sentry firstSeen &gt; 24h&quot; → old issue, not new</li><li>“No app-layer stack trace” → framework/library error, not your code</li><li>Data keywords in error title: “wrong”, “missing”, “not found” for user data</li></ul><h3>Sessions growing too large</h3><p>Normal — each Sentry review adds ~80KB. Sessions are automatically compacted when they near the model’s context limit. If you want to manually compact: send /compact in the web UI.</p><h3>Complete Configuration Reference</h3><pre>{<br>  &quot;meta&quot;: {<br>    &quot;lastTouchedVersion&quot;: &quot;2026.x.x&quot;<br>  },<br>  &quot;auth&quot;: {<br>    &quot;profiles&quot;: {<br>      &quot;anthropic:claude-setup-token&quot;: &quot;sk-ant-oat01-YOUR-TOKEN&quot;<br>    }<br>  },<br>  &quot;agents&quot;: {<br>    &quot;defaults&quot;: {<br>      &quot;models&quot;: {<br>        &quot;anthropic/claude-sonnet-4-6&quot;: {}<br>      },<br>      &quot;workspace&quot;: &quot;/Users/youruser/.openclaw/workspace&quot;,<br>      &quot;compaction&quot;: { &quot;mode&quot;: &quot;safeguard&quot; },<br>      &quot;maxConcurrent&quot;: 3,<br>      &quot;subagents&quot;: { &quot;maxConcurrent&quot;: 3 }<br>    }<br>  },<br>  &quot;channels&quot;: {<br>    &quot;slack&quot;: {<br>      &quot;mode&quot;: &quot;socket&quot;,<br>      &quot;enabled&quot;: true,<br>      &quot;botToken&quot;: &quot;xoxb-YOUR-BOT-TOKEN&quot;,<br>      &quot;appToken&quot;: &quot;xapp-1-YOUR-APP-TOKEN&quot;,<br>      &quot;groupPolicy&quot;: &quot;allowlist&quot;,<br>      &quot;channels&quot;: {<br>        &quot;#your-project-prod-sentry&quot;: {<br>          &quot;allow&quot;: true,<br>          &quot;requireMention&quot;: false,<br>          &quot;allowBots&quot;: true,<br>          &quot;skills&quot;: [&quot;sentry-review&quot;, &quot;slack&quot;],<br>          &quot;systemPrompt&quot;: &quot;You monitor #your-project-prod-sentry. Use sentry-review skill for Sentry alerts. Reply HEARTBEAT_OK for non-Sentry messages.&quot;<br>        }<br>      }<br>    }<br>  },<br>  &quot;gateway&quot;: {<br>    &quot;port&quot;: 18789,<br>    &quot;mode&quot;: &quot;local&quot;,<br>    &quot;bind&quot;: &quot;loopback&quot;,<br>    &quot;auth&quot;: {<br>      &quot;mode&quot;: &quot;token&quot;,<br>      &quot;token&quot;: &quot;YOUR-GATEWAY-SECRET-TOKEN&quot;<br>    }<br>  }<br>}</pre><h3>Key Design Decisions</h3><p>Why OpenClaw over a custom webhook bot? Skills are plain Markdown. No redeployments needed to update the workflow — just edit the .md file. The AI interprets the skill at runtime. This also means non-engineers can read and modify the logic.</p><p>Why exec curl for API calls instead of MCP tools? exec curl replaces the current shell process (no subprocess overhead), and the response comes directly back to the model without an intermediary layer. It&#39;s faster, more transparent, and needs no additional tooling.</p><p>Why Socket Mode over a public webhook? No public URL required. Works from a home or office network behind NAT. Perfect for a Mac Mini running as a local AI assistant server.</p><p>Why Draft MR, not auto-merge? AI-generated code is a suggestion, not a guarantee. The engineer reviews, understands the fix, and merges manually. The value is in the legwork (reading logs, finding files, writing the patch), not in removing human judgment.</p><p>Why max 1 MR per cron run? During a bad deploy, Sentry can fire 10+ alerts at once. Without the limit, the reviewer would wake up to a wall of AI PRs. One is a suggestion; ten is noise.</p><h3>What’s Next</h3><p>Once this is running, extensions you can add:</p><ol><li>Asana triage — poll Asana bug tickets, classify as data vs code issue, run the same Sentry+Graylog+GitLab analysis, post findings as a comment</li><li>Amplitude integration — add user journey analysis to understand what the user was doing when the error occurred</li><li>PagerDuty routing — auto-escalate P0 issues</li><li>Weekly summaries — use HEARTBEAT.md to schedule a weekly “top 5 recurring errors” digest</li></ol><p>The skills-as-Markdown approach means each of these is just a new .md file in ~/.openclaw/workspace/skills/.</p><h3>Summary</h3><p>In about 2 hours of setup, you get:</p><ul><li>Automatic Sentry analysis posted as Slack thread replies within ~60 seconds of an alert</li><li>Correlated Graylog logs — the exact server logs at the time of the error, including distributed trace context</li><li>GitLab blame — recent commits and MRs that may have caused the regression</li><li>Severity classification — P0/P1/P2 with evidence-backed reasoning</li><li>Auto-fix MRs — for simple nil/type/pattern errors, a draft fix appears in GitLab with the reviewer already assigned</li></ul><p>The best part: when Sentry fires at 3am, the analysis is already in the Slack thread by the time an engineer opens their laptop in the morning.</p><p><em>Built with </em><a href="https://openclaw.ai/"><em>OpenClaw</em></a><em> and Claude Sonnet. Running on a Mac Mini M4 Pro.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d87a63983a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero-Cost Code Reviews: Self-Hosted Qwen2.5-Coder on GitLab CI]]></title>
            <link>https://medium.com/@jpranav97/zero-cost-code-reviews-self-hosted-qwen2-5-coder-on-gitlab-ci-8010439a14e0?source=rss-47964e83d7d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8010439a14e0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jpranav]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 11:20:11 GMT</pubDate>
            <atom:updated>2025-11-27T11:20:11.391Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How we eliminated API costs while keeping our code private and reviews comprehensive</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*t38z5wBmB3uyVi7dOPQL9Q.png" /></figure><p>Every merge request now gets an instant AI code review. The catch? It costs us exactly $0 in API fees.</p><p>If you’re using Claude, ChatGPT, or any cloud-based LLM for code reviews, you’re probably familiar with the pain points:</p><ul><li><strong>API costs add up fast</strong> — At $0.10–0.50 per review, 100 daily MRs means $300–1,500/month</li><li><strong>Privacy concerns</strong> — Your proprietary code leaves your network and hits third-party servers</li><li><strong>Rate limits</strong> — Nothing kills CI pipeline velocity like hitting API throttling</li><li><strong>Vendor lock-in</strong> — Pricing changes or service outages are outside your control</li></ul><p>We solved all of these by running <strong>Qwen2.5-Coder:7b</strong> locally on a Mac Mini, integrated directly into our GitLab CI pipeline. Here’s exactly how we did it — including the batching system, prompt engineering, and optimizations that make it production-ready.</p><h3>The Architecture</h3><pre>╔═══════════════════════════════════════════════════════════════════╗<br>║                      GitLab CI Pipeline                           ║<br>║                                                                   ║<br>║   ┌──────────┐      ┌──────────┐      ┌──────────┐                ║<br>║   │  Build   │ ───► │  ai_bot  │ ───► │  Tests   │                ║<br>║   │  Stage   │      │   Job    │      │  Stage   │                ║<br>║   └──────────┘      └────┬─────┘      └──────────┘                ║<br>║                          │                                        ║<br>╚══════════════════════════╪════════════════════════════════════════╝<br>                           │<br>                           │ HTTP Request<br>                           │ (port 11434)<br>                           ▼<br>╔═══════════════════════════════════════════════════════════════════╗<br>║                   Mac Mini (In-House Server)                      ║<br>║                                                                   ║<br>║   ┌───────────────────────────────────────────────────────────┐  ║<br>║   │                    Ollama Service                         │  ║<br>║   │                                                           │  ║<br>║   │   ┌───────────────────────────────────────────────────┐   │  ║<br>║   │   │          qwen2.5-coder:7b (~5GB RAM)              │   │  ║<br>║   │   │                                                   │   │  ║<br>║   │   │  • Code-specialized (5.5T tokens training)        │   │  ║<br>║   │   │  • Apache 2.0 license (commercial OK)             │   │  ║<br>║   │   │  • 128K context window                            │   │  ║<br>║   │   └───────────────────────────────────────────────────┘   │  ║<br>║   │                                                           │  ║<br>║   └───────────────────────────────────────────────────────────┘  ║<br>║                                                                   ║<br>║   IP: Internal Network | Auto-start: launchd                      ║<br>╚══════════════════════════╤════════════════════════════════════════╝<br>                           │<br>                           │ JSON Response<br>                           │ + GitLab API<br>                           ▼<br>╔═══════════════════════════════════════════════════════════════════╗<br>║                       Merge Request                               ║<br>║                                                                   ║<br>║   ┌───────────────────────────────────────────────────────────┐  ║<br>║   │  ## 🤖 AI Code Review Summary                             │  ║<br>║   │                                                           │  ║<br>║   │  ### ✅ APPROVE WITH COMMENTS                             │  ║<br>║   │                                                           │  ║<br>║   │  **Critical:** None                                       │  ║<br>║   │  **Important:** 2 issues found                            │  ║<br>║   │  **Suggestions:** 1 improvement                           │  ║<br>║   │                                                           │  ║<br>║   │  ─────────────────────────────────────────────────────    │  ║<br>║   │  *Powered by Ollama (qwen2.5-coder:7b) • 8.5s • $0*       │  ║<br>║   └───────────────────────────────────────────────────────────┘  ║<br>║                                                                   ║<br>╚═══════════════════════════════════════════════════════════════════╝</pre><h3>Simple Flow Diagram (for featured image)</h3><pre>┌────────────┐     ┌────────────┐     ┌────────────┐<br>│            │     │            │     │            │<br>│   GitLab   │────►│   Ollama   │────►│  MR Gets   │<br>│  CI Job    │     │  (Local)   │     │  Review    │<br>│            │     │            │     │            │<br>└────────────┘     └────────────┘     └────────────┘<br>     MR               Qwen2.5           AI Comment<br>   Created            Coder:7b          Posted</pre><pre>         ┌─────────────────────────────────┐<br>         │  💰 Cost: $0  🔒 Private  ⚡ Fast │<br>         └─────────────────────────────────┘</pre><h3>Why Mac Mini?</h3><p>Apple Silicon is remarkably efficient for LLM inference:</p><ul><li><strong>M1/M2 chips</strong> — Unified memory architecture eliminates GPU memory bottlenecks</li><li><strong>Power efficiency</strong> — ~$5/month in electricity vs $50+ for a GPU server</li><li><strong>Quiet operation</strong> — Can sit under a desk without dedicated cooling</li><li><strong>One-time cost</strong> — $599–999 vs ongoing cloud API fees</li></ul><h3>Why Ollama?</h3><p><a href="https://ollama.ai/">Ollama</a> makes running local LLMs trivially easy:</p><ul><li><strong>One-command setup</strong> — ollama pull qwen2.5-coder:7b</li><li><strong>OpenAI-compatible API</strong> — Drop-in replacement for existing integrations</li><li><strong>Model management</strong> — Easy switching between models for testing</li><li><strong>Automatic optimization</strong> — Handles memory management and batching</li></ul><h3>Why Qwen2.5-Coder?</h3><p>We tested Llama3.1, CodeLlama, DeepSeek Coder, and Qwen2.5-Coder. Here’s why Qwen won:</p><p>Qwen2.5-Coder at 7B parameters <strong>outperforms CodeLlama-34B</strong> (48.8%) while running 5x faster. The Apache 2.0 license means no commercial restrictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*FNqPQmbqKYQ05t1oiHCPQQ.png" /></figure><h3>Implementation Deep-Dive</h3><h3>Step 1: Infrastructure Setup</h3><p><strong>Install Ollama on Mac Mini:</strong></p><pre># Install Ollama<br>curl -fsSL https://ollama.ai/install.sh | sh</pre><pre># Pull the model (4.7GB download)<br>ollama pull qwen2.5-coder:7b</pre><pre># Verify it works<br>ollama run qwen2.5-coder:7b &quot;Write a hello world in Python&quot;</pre><p><strong>Configure auto-start (launchd):</strong></p><p>Create /Library/LaunchDaemons/com.ollama.ollama.plist:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot;<br>  &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>    &lt;key&gt;Label&lt;/key&gt;<br>    &lt;string&gt;com.ollama.ollama&lt;/string&gt;<br>    &lt;key&gt;ProgramArguments&lt;/key&gt;<br>    &lt;array&gt;<br>        &lt;string&gt;/usr/local/bin/ollama&lt;/string&gt;<br>        &lt;string&gt;serve&lt;/string&gt;<br>    &lt;/array&gt;<br>    &lt;key&gt;RunAtLoad&lt;/key&gt;<br>    &lt;true/&gt;<br>    &lt;key&gt;KeepAlive&lt;/key&gt;<br>    &lt;true/&gt;<br>    &lt;key&gt;EnvironmentVariables&lt;/key&gt;<br>    &lt;dict&gt;<br>        &lt;key&gt;OLLAMA_HOST&lt;/key&gt;<br>        &lt;string&gt;0.0.0.0:11434&lt;/string&gt;<br>    &lt;/dict&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><pre>sudo launchctl load /Library/LaunchDaemons/com.ollama.ollama.plist</pre><h3>Step 2: GitLab CI Job</h3><p>Add this to your .gitlab-ci.yml:</p><pre>ai_bot:<br>  stage: build  # Or any stage that runs on MRs<br>  needs: []     # No dependencies - runs in parallel<br>  image: alpine:3.21<br>  rules:<br>    # Skip for main branch pushes<br>    - if: &#39;$CI_COMMIT_BRANCH == &quot;main&quot;&#39;<br>      when: never<br>    # Run on all merge requests<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>      when: on_success<br>  before_script:<br>    - apk add --no-cache git curl bash jq<br>  script:<br>    - chmod +x scripts/ollama_review.sh<br>    - bash scripts/ollama_review.sh<br>  tags:<br>    - inhouse  # Runs on self-hosted runner with network access<br>  allow_failure: true  # Don&#39;t block MRs if AI review fails<br>  timeout: 10m</pre><p>Key decisions:</p><ul><li><strong>allow_failure: true</strong> — AI review is advisory, not blocking</li><li><strong>tags: [inhouse]</strong> — Ensures the job runs on runners that can reach the Mac Mini</li><li><strong>timeout: 10m</strong> — Large diffs may take longer; prevents hanging jobs</li></ul><h3>The Secret Sauce: Optimizations That Make It Work</h3><p>A naive implementation would hit context limits, produce inconsistent output, and miss important issues. Here are the optimizations that make our system production-ready.</p><h3>Optimization 1: Token Budget Management</h3><p>Local LLMs have limited context windows (~16K tokens for 7B models). We budget tokens carefully:</p><pre># Token budget allocation (24K chars ≈ 8K tokens)<br>MAX_PROMPT_CHARS=24000        # Total prompt limit<br>MAX_ADDED_LINES_SIZE=18000    # ~6K tokens for code changes<br>MAX_ASANA_CONTEXT_SIZE=3000   # ~1K tokens for task context<br># Remaining ~1K for instructions, patterns, format</pre><p><strong>Why this matters:</strong> Without budgeting, a 500-line diff would exceed context and produce garbage output.</p><h3>Optimization 2: Batched Reviews</h3><p>Large MRs can have 50+ files. Instead of one massive prompt, we batch:</p><pre># Batching configuration<br>BATCH_SIZE=5        # Files per LLM call<br>MAX_BATCHES=10      # Maximum batches (50 files coverage)<br>BATCH_DELAY=2       # Seconds between batches (avoid overload)</pre><p><strong>How it works:</strong></p><pre>50 files changed<br>    ↓<br>Split into 10 batches of 5 files each<br>    ↓<br>Batch 1: Files 1-5   → LLM call → JSON result<br>Batch 2: Files 6-10  → LLM call → JSON result<br>...<br>Batch 10: Files 46-50 → LLM call → JSON result<br>    ↓<br>Merge all results into single review</pre><p><strong>Merge logic:</strong> Accumulate issues from all batches, use worst verdict:</p><pre>merge_reviews() {<br>    # Collect all critical/important/suggestions<br>    # Verdict priority: REQUEST_CHANGES &gt; APPROVE_WITH_COMMENTS &gt; APPROVE<br>    # Combine all reasons<br>}</pre><h3>Optimization 3: Added Lines Only Format</h3><p>We don’t send the entire diff. We extract ONLY added lines with precise locations:</p><pre># Input: raw git diff<br># Output: structured format</pre><pre>[src/auth/login.ex:45] +    def authenticate(user, password) do<br>[src/auth/login.ex:46] +      case verify_password(user, password) do<br>[src/auth/login.ex:47] +        {:ok, _} -&gt; {:ok, user}<br>[src/auth/login.ex:48] +        {:error, _} -&gt; {:error, :invalid_credentials}<br>[src/auth/login.ex:49] +      end<br>[src/auth/login.ex:50] +    end</pre><p><strong>Why </strong><strong>[file:line] format:</strong></p><ol><li>LLM can reference exact locations in its response</li><li>We can validate LLM output against real line numbers</li><li>Enables line-specific comments on MRs (future feature)</li></ol><h3>Optimization 4: Triggered Pattern Injection</h3><p>Not all code needs the same review rules. We detect patterns in the diff and inject relevant checks:</p><pre>load_triggered_patterns() {<br>    local diff=&quot;$1&quot;<br>    local patterns=&quot;&quot;</pre><pre>    # Security patterns<br>    if echo &quot;$diff&quot; | grep -qE &quot;password|secret|token|api_key&quot;; then<br>        patterns+=&quot;⚠️ SECRETS: Check for hardcoded credentials\n&quot;<br>    fi</pre><pre>    # Financial patterns<br>    if echo &quot;$diff&quot; | grep -qE &quot;Float\.|amount.*\*|price.*\*&quot;; then<br>        patterns+=&quot;💰 MONEY: Use Decimal, NEVER Float for currency\n&quot;<br>    fi</pre><pre>    # Database patterns<br>    if echo &quot;$diff&quot; | grep -qE &quot;INSERT|UPDATE|DELETE|Repo\.(insert|update)&quot;; then<br>        patterns+=&quot;📝 DATABASE: Check for SQL injection, use parameterized queries\n&quot;<br>    fi</pre><pre>    # API patterns<br>    if echo &quot;$diff&quot; | grep -qE &quot;fetch|axios|http|curl&quot;; then<br>        patterns+=&quot;🔌 HTTP: Verify timeout handling and error responses\n&quot;<br>    fi</pre><pre>    # Async patterns<br>    if echo &quot;$diff&quot; | grep -qE &quot;async|await|Promise|Task\.async&quot;; then<br>        patterns+=&quot;⏳ ASYNC: Check for unhandled rejections/errors\n&quot;<br>    fi</pre><pre>    echo &quot;$patterns&quot;<br>}</pre><p><strong>Result:</strong> The LLM gets context-specific review criteria instead of generic advice.</p><h3>Optimization 5: LLM Parameters Tuning</h3><p>Default LLM parameters produce verbose, inconsistent output. We tuned for code review:</p><pre># LLM parameters<br>TEMPERATURE=0.1       # Low = deterministic, consistent format<br>REPEAT_PENALTY=1.5    # High = prevents verbose repetition<br>MAX_TOKENS=600        # Short = forces concise output<br>NUM_CTX=8192         # Context window for full understanding</pre><pre># System prompt (10%+ quality improvement per research)<br>SYSTEM_PROMPT=&quot;You are an expert code reviewer. You identify ONLY real bugs,<br>security issues, and critical problems. You never flag style preferences or<br>valid patterns as issues. You output ONLY the requested format.&quot;</pre><h3>Optimization 6: Semantic Annotations</h3><p>We pre-annotate important changes to guide LLM attention:</p><pre>annotate_diff_semantically() {<br>    case &quot;$line&quot; in<br>        +*def\ *|+*function\ *)<br>            echo &quot;[NEW FUNC] $line&quot; ;;<br>        +*Repo.insert*|+*INSERT*)<br>            echo &quot;[DB MUTATION] $line&quot; ;;<br>        +*password*|+*secret*)<br>            echo &quot;[SECURITY] $line&quot; ;;<br>        +*send_email*|+*notify*)<br>            echo &quot;[NOTIFICATION] $line&quot; ;;<br>        *)<br>            echo &quot;$line&quot; ;;<br>    esac<br>}</pre><p><strong>Before:</strong> LLM might miss a buried password variable <strong>After:</strong> [SECURITY] + password = params[&quot;password&quot;] gets flagged</p><h3>Optimization 7: Module Context Extraction</h3><p>For languages with rich type systems (Elixir, TypeScript), we extract context:</p><pre>extract_module_context() {<br>    local file=&quot;$1&quot;</pre><pre>    # Extract module name<br>    grep -m1 &quot;^defmodule&quot; &quot;$file&quot;</pre><pre>    # Extract type specs<br>    grep &quot;^\s*@spec&quot; &quot;$file&quot; | head -8</pre><pre>    # Extract function signatures<br>    grep &quot;^\s*def &quot; &quot;$file&quot; | head -15</pre><pre>    # Extract struct definition<br>    grep &quot;defstruct&quot; &quot;$file&quot;<br>}</pre><p>This helps the LLM understand the codebase structure without sending entire files.</p><h3>Prompt Engineering: The Complete Prompt</h3><p>Here’s the actual prompt structure we use:</p><pre>PROMPT=&quot;${ASANA_CONTEXT}</pre><pre>Review these code changes. Each line shows [file:line] and the code.</pre><pre>CHANGES TO REVIEW (Batch $batch_num of $total_batches):<br>$ADDED_LINES_WITH_NUMBERS</pre><pre>CHECKS TO APPLY:<br>$TRIGGERED_PATTERNS</pre><pre>RULES:<br>1. Only review the NEWLY ADDED lines shown above<br>2. Use the EXACT [file:line] from the line you&#39;re reviewing<br>3. If no issues with the NEW code, say \&quot;None found\&quot;<br>4. Consider task context (if provided) to understand business intent</pre><pre>FOCUS ON:<br>- Bugs or logic errors in the new code<br>- Security issues introduced by these specific changes<br>- Missing error handling for new code paths<br>- Potential crashes or exceptions</pre><pre>SEVERITY GUIDE:<br>- CRITICAL: Security vulnerabilities, data loss, crashes<br>- IMPORTANT: Logic errors, missing error handling<br>- SUGGESTIONS: Style improvements, minor optimizations</pre><pre>DO NOT flag as issues:<br>- Patterns that follow existing conventions<br>- Configuration constants (timeouts, limits are intentional)<br>- Valid language idioms</pre><pre>OUTPUT JSON:<br>{\&quot;critical\&quot;:\&quot;none\&quot;,\&quot;important\&quot;:\&quot;none\&quot;,\&quot;suggestions\&quot;:\&quot;none\&quot;,<br> \&quot;verdict\&quot;:\&quot;APPROVE\&quot;,\&quot;reason\&quot;:\&quot;clean code\&quot;}&quot;</pre><h3>Why JSON Output?</h3><p>We request JSON format for structured parsing:</p><pre>curl &quot;http://$OLLAMA_HOST/api/generate&quot; -d &#39;{<br>  &quot;model&quot;: &quot;qwen2.5-coder:7b&quot;,<br>  &quot;prompt&quot;: &quot;...&quot;,<br>  &quot;format&quot;: &quot;json&quot;,          # ← Request JSON output<br>  &quot;options&quot;: {<br>    &quot;temperature&quot;: 0.1,<br>    &quot;num_predict&quot;: 600,<br>    &quot;repeat_penalty&quot;: 1.5<br>  }<br>}&#39;</pre><p><strong>Benefits:</strong></p><ul><li>Predictable parsing (no regex gymnastics)</li><li>Easy verdict extraction for CI status</li><li>Simple merge of batch results</li><li>Clean separation of issue categories</li></ul><h3>Integrations: External Context</h3><h3>Task Management (Asana/Jira)</h3><p>We extract task context from MR descriptions:</p><pre># Extract task URL from MR description<br>TASK_URL=$(echo &quot;$MR_DESCRIPTION&quot; | grep -oE &#39;https://app.asana.com/[0-9/]+&#39;)</pre><pre># Fetch task details via API<br>TASK_CONTEXT=$(curl -H &quot;Authorization: Bearer $ASANA_PAT&quot; \<br>  &quot;https://app.asana.com/api/1.0/tasks/$TASK_GID?opt_fields=name,notes&quot;)</pre><pre># Include in prompt<br>ASANA_SECTION=&quot;<br>## Task Context<br>**Task:** $TASK_NAME<br>**Description:** $TASK_NOTES</pre><pre>Use this context to understand the business intent of the changes.<br>&quot;</pre><p><strong>Why this helps:</strong> LLM can distinguish between “bug fix” and “new feature” behavior.</p><h3>Cross-Module Impact Detection</h3><p>For monorepos, detect when changes affect multiple modules:</p><pre>detect_cross_impact() {<br>    local changed_files=&quot;$1&quot;</pre><pre>    if echo &quot;$changed_files&quot; | grep -q &quot;auth/&quot;; then<br>        echo &quot;⚡ AUTH changes may affect: user sessions, permissions&quot;<br>    fi</pre><pre>    if echo &quot;$changed_files&quot; | grep -q &quot;database/&quot;; then<br>        echo &quot;⚡ DB schema changes require migrations&quot;<br>    fi</pre><pre>    if echo &quot;$changed_files&quot; | grep -q &quot;api/&quot;; then<br>        echo &quot;⚡ API changes may break clients - check versioning&quot;<br>    fi<br>}</pre><h3>Cost Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*ugpBRfZ6JAEjciilGXdsyw.png" /></figure><p>Additional benefits:</p><ul><li><strong>Data privacy</strong> — Code never leaves our network</li><li><strong>No rate limits</strong> — Review 1,000 MRs/day if needed</li><li><strong>No vendor dependency</strong> — We control uptime and availability</li><li><strong>Customization</strong> — Fine-tune on our codebase patterns</li></ul><h3>Real Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*s_2-phSvrkEuqA5tPGC2DQ.png" /></figure><h3>Sample Review Output</h3><pre>## AI Code Review Summary</pre><pre>### CRITICAL<br>None found</pre><pre>### IMPORTANT<br>1. **Missing error handling** [src/api/users.ex:67]<br>   The `Repo.insert` call doesn&#39;t handle `{:error, changeset}`.<br>   Pattern match on the result to handle validation failures.</pre><pre>2. **Potential nil access** [src/api/users.ex:82]<br>   `user.profile.name` may crash if profile is nil.<br>   Use `user.profile &amp;&amp; user.profile.name` or safe navigation.</pre><pre>### SUGGESTIONS<br>- Consider extracting lines 45-60 into a separate function for testability.</pre><pre>### VERDICT<br>APPROVE WITH COMMENTS - Good implementation, address error handling before merge.</pre><pre>---<br>*Review: Batch 1/2 | Model: qwen2.5-coder:7b | Time: 6.2s | Tokens: 1,250+180*</pre><h3>Limitations &amp; Honest Assessment</h3><h3>Where It Excels</h3><ul><li><strong>Pattern matching</strong> — Catches common mistakes reliably</li><li><strong>Style consistency</strong> — Enforces coding standards</li><li><strong>Security basics</strong> — SQL injection, XSS, hardcoded secrets</li><li><strong>Speed</strong> — 5–15 seconds vs hours waiting for human review</li></ul><h3>Where It Falls Short</h3><ul><li><strong>Complex business logic</strong> — Can’t understand domain-specific rules</li><li><strong>Architecture decisions</strong> — Won’t catch design flaws</li><li><strong>Context awareness</strong> — Doesn’t know codebase history</li><li><strong>Nuanced judgment</strong> — Sometimes flags valid patterns</li></ul><h3>Our Recommendation</h3><p><strong>Use AI review as a first-pass filter, not a replacement for human review.</strong></p><p>The AI catches low-hanging fruit so humans can focus on architecture and logic.</p><h3>Getting Started</h3><h3>Quick Start (5 minutes)</h3><ol><li><strong>Install Ollama</strong> on any machine with 8GB+ RAM:</li></ol><pre>curl -fsSL https://ollama.ai/install.sh | sh ollama pull qwen2.5-coder:7b</pre><ol><li><strong>Add minimal CI job</strong>:</li></ol><pre>ai_review:   image: alpine:3.21   script:     - apk add curl jq git     - |       DIFF=$(git diff origin/main -- &#39;*.py&#39; &#39;*.js&#39; &#39;*.ts&#39;)       curl -s http://YOUR_OLLAMA_HOST:11434/api/generate \         -d &quot;{\&quot;model\&quot;:\&quot;qwen2.5-coder:7b\&quot;,\&quot;prompt\&quot;:\&quot;Review:\\n$DIFF\&quot;}&quot; \         | jq -r &#39;.response&#39;</pre><ol><li><strong>Iterate</strong> — Add batching, patterns, and GitLab posting as needed.</li></ol><h3>Resources</h3><ul><li><a href="https://ollama.ai/">Ollama Documentation</a></li><li><a href="https://huggingface.co/Qwen/Qwen2.5-Coder-7B">Qwen2.5-Coder Model Card</a></li><li><a href="https://docs.gitlab.com/ee/ci/">GitLab CI/CD Documentation</a></li></ul><h3>Conclusion</h3><p>Switching from cloud APIs to local Qwen2.5-Coder was one of the best infrastructure decisions we made. The key insights:</p><ol><li><strong>Budget tokens carefully</strong> — Context limits are real constraints</li><li><strong>Batch large reviews</strong> — Don’t try to review 50 files in one call</li><li><strong>Inject relevant context</strong> — Triggered patterns beat generic rules</li><li><strong>Tune LLM parameters</strong> — Low temperature + high repeat penalty = consistent output</li><li><strong>Use structured output</strong> — JSON is easier to parse than free text</li></ol><p>The result: <strong>Zero ongoing API costs, complete data privacy, and instant feedback on every MR.</strong></p><p>Is the AI perfect? No. But it catches enough issues to be valuable, and the price (after hardware) is unbeatable.</p><p><em>Have questions? Found improvements? Leave a comment below.</em></p><p><strong>Tags:</strong> #DevOps #AI #CodeReview #GitLabCI #Ollama #LLM #MachineLearning #SelfHosted #Qwen</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8010439a14e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Stop Wasting Tokens: How to Optimize Claude Code Context by 60%”]]></title>
            <link>https://medium.com/@jpranav97/stop-wasting-tokens-how-to-optimize-claude-code-context-by-60-bfad6fd477e5?source=rss-47964e83d7d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfad6fd477e5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[Jpranav]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 06:41:05 GMT</pubDate>
            <atom:updated>2025-11-18T06:41:05.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*hi37U1Lu7n-SwZr0EqbaLQ.png" /></figure><h3>Smart session hooks and tiered documentation can save you hundreds of dollars monthly</h3><p><em>A practical guide for any Claude Code project</em></p><h3>The Problem Every Developer Faces</h3><p>You’ve integrated Claude Code into your project. You wrote a comprehensive CLAUDE.md file to give your AI assistant all the context it needs. Everything works... until you check your usage.</p><p><strong>The wake-up call:</strong></p><ul><li>Every session loads 2,000+ tokens of context</li><li>70% of that context is irrelevant to your current task</li><li>You’re paying for information Claude doesn’t need</li><li>Response times are slower than they should be</li></ul><p>Here’s what’s actually happening:</p><pre>Session 1: &quot;Fix typo in README.md&quot;<br>Claude loads: Database schemas, deployment configs, testing guides,<br>API documentation, architecture diagrams...<br>Tokens used: 2,100<br>Relevant context: ~300 tokens (14%)</pre><pre>Session 2: &quot;Add error handling to API endpoint&quot;<br>Claude loads: Same 2,100 tokens<br>Relevant context: ~600 tokens (28%)</pre><pre>Session 3: &quot;Update Kubernetes configs&quot;<br>Claude loads: Same 2,100 tokens<br>Relevant context: ~500 tokens (24%)</pre><p><strong>The cost:</strong> At $0.03/1K tokens for input, you’re spending <strong>$0.063 per session</strong> on mostly irrelevant context.</p><p>For a team of 5 developers making 20 Claude Code requests per day:</p><ul><li>Daily cost: 100 requests × $0.063 = <strong>$6.30/day</strong></li><li>Monthly cost: <strong>$189/month</strong></li><li>Yearly cost: <strong>$2,268/year</strong></li></ul><p><strong>On wasted context.</strong></p><p>Let me show you how to cut that by 60%.</p><h3>The Solution: Tiered Context Architecture</h3><p>Instead of loading everything upfront, implement a <strong>3-tier system</strong>:</p><h3>Tier 1: Critical Context (Always Loaded)</h3><p>What Claude needs in <em>every</em> session:</p><ul><li>Project name and purpose (50–100 words)</li><li>Critical “never do this” rules</li><li>Quick start commands</li><li>Emergency troubleshooting</li></ul><p><strong>Target: &lt;800 tokens</strong></p><h3>Tier 2: Contextual (Loaded on Demand)</h3><p>What Claude needs for <em>specific tasks</em>:</p><ul><li>Component-specific documentation</li><li>API references</li><li>Deployment guides</li><li>Testing patterns</li></ul><p><strong>Target: 500–1,500 tokens (only when relevant)</strong></p><h3>Tier 3: Reference (Never Loaded)</h3><p>What Claude can <em>look up</em> if needed:</p><ul><li>Complete API specs</li><li>Historical change logs</li><li>Detailed troubleshooting</li><li>Generated documentation</li></ul><p><strong>Target: 0 tokens (linked, not loaded)</strong></p><p>The magic happens with Claude Code’s <strong>session-start hooks</strong>.</p><h3>Session-Start Hooks: Your Secret Weapon</h3><p>Claude Code executes .claude/hooks/session-start.sh before loading your CLAUDE.md. This gives you a chance to:</p><ol><li>Check your project’s current state</li><li>Determine what context is actually needed</li><li>Show relevant information immediately</li><li>Skip loading irrelevant docs</li></ol><h3>Example: Basic Session Hook</h3><pre>#!/bin/bash<br># .claude/hooks/session-start.sh</pre><pre>set -euo pipefail</pre><pre>echo &quot;🚀 Project Status&quot;<br>echo &quot;────────────────&quot;</pre><pre># 1. Check if database is running<br>if docker ps | grep -q postgres; then<br>    echo &quot;✅ PostgreSQL: Connected&quot;<br>else<br>    echo &quot;❌ PostgreSQL: Not running&quot;<br>    echo &quot;   Quick fix: docker-compose up -d&quot;<br>fi</pre><pre># 2. Check if Redis/cache is running<br>if docker ps | grep -q redis; then<br>    echo &quot;✅ Redis: Connected&quot;<br>else<br>    echo &quot;⚠️  Redis: Not running (optional)&quot;<br>fi</pre><pre># 3. Show current branch<br>echo &quot;&quot;<br>echo &quot;📍 Git: $(git branch --show-current)&quot;<br>echo &quot;   Last commit: $(git log -1 --oneline)&quot;</pre><pre># 4. Detect what you&#39;re working on<br>current_dir=$(basename &quot;$PWD&quot;)<br>case &quot;$current_dir&quot; in<br>    &quot;tests&quot;|&quot;test&quot;)<br>        echo &quot;&quot;<br>        echo &quot;💡 Working on tests? See: docs/TESTING.md&quot;<br>        ;;<br>    &quot;api&quot;|&quot;src&quot;)<br>        echo &quot;&quot;<br>        echo &quot;💡 Working on API? See: docs/API.md&quot;<br>        ;;<br>    &quot;deploy&quot;|&quot;k8s&quot;|&quot;docker&quot;)<br>        echo &quot;&quot;<br>        echo &quot;💡 Deploying? See: docs/DEPLOYMENT.md&quot;<br>        ;;<br>esac</pre><pre>echo &quot;────────────────&quot;</pre><p><strong>Make it executable:</strong></p><pre>chmod +x .claude/hooks/session-start.sh</pre><h3>What This Achieves</h3><p><strong>Before session hook:</strong></p><pre>You: &quot;Is the database running?&quot;<br>Claude: [Reads 200 lines of database troubleshooting docs]<br>Claude: &quot;Let me check... You should run: docker ps | grep postgres&quot;<br>You: [Runs command]<br>You: &quot;Yes, it&#39;s running&quot;</pre><pre>Tokens used: ~300<br>Time: 12 seconds</pre><p><strong>After session hook:</strong></p><pre>[Session starts]<br>Hook output: &quot;✅ PostgreSQL: Connected&quot;<br>You: &quot;Add error handling to user endpoint&quot;<br>Claude: &quot;I see your database is connected. Here&#39;s the error handling...&quot;</pre><pre>Tokens used: ~20 (just status line)<br>Time: 3 seconds</pre><p><strong>Savings: 280 tokens + 9 seconds per session</strong> ✅</p><h3>Optimizing Your CLAUDE.md</h3><p>Your CLAUDE.md is costing you tokens. Here’s how to fix it.</p><h3>Before: The Bloated Approach</h3><pre># My Project</pre><pre>## Overview<br>My project is a web application built with React, Node.js, PostgreSQL,<br>and Redis. It features user authentication, real-time notifications,<br>background job processing, and RESTful API endpoints. The frontend uses<br>React 18 with TypeScript, styled-components, and React Query for data<br>fetching. The backend uses Express.js with TypeScript, Prisma ORM for<br>database access, and Bull queues for job processing...</pre><pre>[500 more words of detailed explanation]</pre><pre>## Architecture<br>[600 lines of detailed architecture documentation]</pre><pre>## Database Schema<br>[400 lines of table definitions]</pre><pre>## API Endpoints<br>[800 lines of endpoint documentation]</pre><pre>## Deployment<br>[300 lines of deployment instructions]</pre><pre>## Troubleshooting<br>[500 lines of common issues]</pre><p><strong>Problem:</strong></p><ul><li>2,800+ lines loaded every session</li><li>~2,100 tokens consumed</li><li>Takes 10+ seconds to process</li><li>90% irrelevant to current task</li></ul><h3>After: The Optimized Approach</h3><pre># My Project</pre><pre>## 🎯 Overview (50 words)<br>Web app with React, Node.js, PostgreSQL, Redis. User auth, real-time<br>notifications, background jobs, REST API.</pre><pre>**Tech:** React 18 + TypeScript, Express.js, Prisma, Bull queues<br>**Docs:** See `docs/INDEX.md` for complete navigation</pre><pre>## 🚨 Critical Rules</pre><pre>1. **Never commit secrets** - Use `.env.local` for local, secrets manager for prod<br>2. **Run tests before commit** - `npm test` must pass<br>3. **Never force push to main** - Create PR for all changes<br>4. **Check DB migrations** - Review SQL before running `prisma migrate deploy`<br>5. **Don&#39;t skip type checking** - `npm run type-check` catches bugs early</pre><pre>## 🚀 Quick Start</pre><pre>**Install:** `npm install &amp;&amp; docker-compose up -d`<br>**Dev:** `npm run dev` (http://localhost:3000)<br>**Test:** `npm test`<br>**Build:** `npm run build`</pre><pre>## 🐛 Troubleshooting</pre><pre>| Issue | Fix |<br>|-------|-----|<br>| DB connection error | `docker-compose up -d &amp;&amp; npx prisma migrate dev` |<br>| Port 3000 in use | `lsof -ti:3000 \| xargs kill -9` |<br>| Type errors | `npm run type-check` then fix reported errors |<br>| Redis not connecting | `docker-compose restart redis` |</pre><pre>**Full guide:** `docs/TROUBLESHOOTING.md`</pre><pre>## 📂 Key Files</pre><p>src/ api/ — Express routes &amp; controllers components/ — React components lib/ — Utilities &amp; helpers prisma/ — Database schema docs/ API.md — Complete API reference DEPLOYMENT.md — Production deploy guide TESTING.md — Testing patterns</p><pre>## 📞 Where to Find More</pre><pre>- **API docs:** `docs/API.md`<br>- **Database schema:** `src/prisma/schema.prisma` + `docs/DATABASE.md`<br>- **Deployment:** `docs/DEPLOYMENT.md`<br>- **Testing:** `docs/TESTING.md`<br>- **Complete index:** `docs/INDEX.md`</pre><pre>---</pre><pre># Detailed Documentation (Below First 200 Lines)</pre><pre>[Full details that Claude only reads if specifically needed]</pre><p><strong>Result:</strong></p><ul><li>First 200 lines: ~800 tokens (62% reduction)</li><li>Critical info always available</li><li>Details linked, not loaded</li><li>Claude requests specific docs only when needed</li></ul><h3>Creating a Quick Reference Card</h3><p>For instant lookups, create a one-page cheat sheet:</p><p><strong>docs/QUICK_REF.md</strong></p><pre># Quick Reference</pre><pre>## Essential Commands</pre><pre>```bash<br># Development<br>npm run dev              # Start dev server (localhost:3000)<br>npm test                 # Run tests<br>npm run type-check       # TypeScript validation</pre><pre># Database<br>npx prisma studio        # DB GUI (localhost:5555)<br>npx prisma migrate dev   # Run migrations<br>docker-compose up -d     # Start PostgreSQL + Redis</pre><pre># Deployment<br>npm run build            # Production build<br>npm start                # Production server<br>docker build -t app .    # Build Docker image</pre><h3>Common Issues</h3><p>Problem</p><p>Solution</p><p>“Port 3000 already in use”</p><p>lsof -ti:3000 | xargs kill -9</p><p>Database not found</p><p>npx prisma migrate dev</p><p>Type errors</p><p>npm run type-check</p><p>Slow queries</p><p>Check docs/DATABASE.md (indexing guide)</p><h3>Tech Stack</h3><p>Layer</p><p>Technology</p><p>Frontend</p><p>React 18 + TypeScript + styled-components</p><p>Backend</p><p>Express.js + TypeScript + Prisma</p><p>Database</p><p>PostgreSQL 15</p><p>Cache</p><p>Redis 7</p><p>Jobs</p><p>Bull queues</p><h3>Project Structure</h3><pre>src/<br>  api/routes/           # API endpoints<br>  api/controllers/      # Request handlers<br>  components/           # React components<br>  lib/                  # Shared utilities<br>  prisma/schema.prisma  # Database schema</pre><h3>Critical Rules</h3><ol><li>✅ Run tests before commit</li><li>✅ Use TypeScript strict mode</li><li>❌ Never commit .env.local</li><li>❌ Never force push to main</li><li>✅ Review migrations before deploying</li></ol><h3>Links</h3><ul><li>Full Documentation</li><li>API Reference</li><li>Deployment Guide</li></ul><pre>**Usage:**<br>- Developer needs command: Check QUICK_REF.md<br>- Claude needs API info: References API.md<br>- **Token savings: ~200 tokens per common query**</pre><pre>---</pre><pre>## Smart Context Detection</pre><pre>Make your session hook detect what you&#39;re working on:</pre><pre>```bash<br>#!/bin/bash<br># .claude/hooks/session-start.sh</pre><pre>detect_work_context() {<br>    # Check recently changed files<br>    local changed_files=$(git diff --name-only HEAD~1 2&gt;/dev/null)</pre><pre>    if echo &quot;$changed_files&quot; | grep -q &quot;test/\|spec/\|__tests__&quot;; then<br>        echo &quot;💡 Testing context detected&quot;<br>        echo &quot;   Docs: docs/TESTING.md&quot;<br>        return<br>    fi</pre><pre>    if echo &quot;$changed_files&quot; | grep -q &quot;Dockerfile\|docker-compose\|k8s/&quot;; then<br>        echo &quot;💡 Deployment context detected&quot;<br>        echo &quot;   Docs: docs/DEPLOYMENT.md&quot;<br>        return<br>    fi</pre><pre>    if echo &quot;$changed_files&quot; | grep -q &quot;api/\|routes/\|controllers/&quot;; then<br>        echo &quot;💡 API development context detected&quot;<br>        echo &quot;   Docs: docs/API.md&quot;<br>        return<br>    fi</pre><pre>    if echo &quot;$changed_files&quot; | grep -q &quot;prisma/\|migrations/&quot;; then<br>        echo &quot;💡 Database work detected&quot;<br>        echo &quot;   Docs: docs/DATABASE.md&quot;<br>        echo &quot;   ⚠️  Don&#39;t forget to review migrations carefully!&quot;<br>        return<br>    fi<br>}</pre><pre># Call it in your session-start hook<br>detect_work_context</pre><p><strong>Result:</strong> Claude gets hints about what you’re working on <em>without</em> loading full documentation.</p><h3>Advanced: Environment-Aware Context</h3><p>Different contexts for different environments:</p><pre>#!/bin/bash<br># .claude/hooks/session-start.sh</pre><pre>show_environment_context() {<br>    # Detect environment<br>    if [ -f &quot;.env.production&quot; ]; then<br>        echo &quot;🔴 PRODUCTION environment detected&quot;<br>        echo &quot;   Extra caution required!&quot;<br>        echo &quot;   - All changes require PR review&quot;<br>        echo &quot;   - Migrations must be tested in staging first&quot;<br>        echo &quot;   - Never delete data without backup&quot;<br>    elif [ -f &quot;.env.staging&quot; ]; then<br>        echo &quot;🟡 STAGING environment detected&quot;<br>        echo &quot;   - Safe to test migrations&quot;<br>        echo &quot;   - Don&#39;t worry about breaking things&quot;<br>    else<br>        echo &quot;🟢 DEVELOPMENT environment&quot;<br>        echo &quot;   - Go wild, it&#39;s your local machine&quot;<br>    fi<br>}</pre><pre>show_environment_context</pre><p><strong>Prevents costly mistakes:</strong> Claude knows production context requires extra care.</p><h3>The Tiered Documentation Structure</h3><p>Organize docs by how frequently they’re needed:</p><pre>project/<br>├── CLAUDE.md              # Tier 1: Always loaded (Critical + Quick Start)<br>├── docs/<br>│   ├── QUICK_REF.md       # Tier 2: Common lookups (one-page)<br>│   ├── INDEX.md           # Navigation hub<br>│   ├── API.md             # Tier 2: When working on API<br>│   ├── DATABASE.md        # Tier 2: When working on DB<br>│   ├── TESTING.md         # Tier 2: When writing tests<br>│   ├── DEPLOYMENT.md      # Tier 2: When deploying<br>│   └── troubleshooting/   # Tier 3: Reference only<br>│       ├── database.md<br>│       ├── performance.md<br>│       └── common-errors.md</pre><p><strong>Navigation pattern:</strong></p><pre>&lt;!-- CLAUDE.md --&gt;<br>## Database</pre><pre>**Quick start:** `npx prisma studio` (GUI at localhost:5555)<br>**Schema:** `src/prisma/schema.prisma`<br>**Full docs:** `docs/DATABASE.md`</pre><pre>&lt;!-- When Claude needs DB docs, it reads docs/DATABASE.md --&gt;<br>&lt;!-- When you need quick command, CLAUDE.md has it --&gt;</pre><h3>Real Results: Before &amp; After</h3><h3>Before Optimization</h3><pre>CLAUDE.md: 2,800 lines<br>Startup tokens: 2,100<br>Time to first response: 10-12 seconds<br>Relevant context: ~30%<br>Cost per session: $0.063<br>Monthly cost (100 sessions/day, 5 devs): $189</pre><h3>After Optimization</h3><pre>CLAUDE.md (first 200 lines): 180 lines<br>Startup tokens: 800<br>Time to first response: 3-5 seconds<br>Relevant context: ~85%<br>Cost per session: $0.024<br>Monthly cost (100 sessions/day, 5 devs): $72</pre><h3>Savings</h3><ul><li><strong>Token reduction:</strong> 62% (1,300 tokens saved per session)</li><li><strong>Speed improvement:</strong> 70% faster (7 seconds saved)</li><li><strong>Cost savings:</strong> $117/month for small team</li><li><strong>Context relevance:</strong> +55% increase</li><li><strong>Annual savings:</strong> $1,404/year</li></ul><p>For a team of 20 developers: <strong>$5,616/year saved</strong></p><h3>Practical Checklist: Optimize Your Project Today</h3><h3>Quick Wins (15–30 minutes)</h3><p><strong>1. Create a session-start hook</strong></p><pre>mkdir -p .claude/hooks<br>cat &gt; .claude/hooks/session-start.sh &lt;&lt; &#39;EOF&#39;<br>#!/bin/bash<br>set -euo pipefail</pre><pre>echo &quot;🚀 $(basename &quot;$PWD&quot;) Status&quot;<br>echo &quot;────────────────────────────&quot;</pre><pre># Check database<br>if docker ps | grep -q postgres; then<br>    echo &quot;✅ Database: Connected&quot;<br>else<br>    echo &quot;❌ Database: Not running (docker-compose up -d)&quot;<br>fi</pre><pre># Show git context<br>echo &quot;📍 Branch: $(git branch --show-current)&quot;<br>echo &quot;   Last: $(git log -1 --oneline)&quot;</pre><pre>echo &quot;────────────────────────────&quot;<br>EOF</pre><pre>chmod +x .claude/hooks/session-start.sh</pre><p><strong>2. Create QUICK_REF.md</strong></p><pre>cat &gt; docs/QUICK_REF.md &lt;&lt; &#39;EOF&#39;<br># Quick Reference</pre><pre>## Essential Commands<br>[Your top 10 most-used commands]</pre><pre>## Troubleshooting<br>| Issue | Fix |<br>[Your top 5 most common issues]</pre><pre>## Critical Rules<br>[Your &quot;never do this&quot; list]<br>EOF</pre><p><strong>Token saved: ~300 per session</strong> ✅</p><h3>Medium Effort (1–2 hours)</h3><p><strong>3. Audit your CLAUDE.md</strong></p><pre># Count tokens (rough estimate)<br>wc -w CLAUDE.md | awk &#39;{print &quot;Estimated tokens:&quot;, $1 * 0.75}&#39;</pre><pre># Goal: First 200 lines should be &lt; 1,000 tokens<br>head -200 CLAUDE.md | wc -w | awk &#39;{print &quot;First 200 lines:&quot;, $1 * 0.75, &quot;tokens&quot;}&#39;</pre><p><strong>4. Optimize first 200 lines</strong></p><p>Before:</p><pre>## Architecture</pre><pre>Our application uses a microservices architecture with the following components:</pre><pre>### Frontend Service<br>The frontend is built with React 18 and TypeScript. It uses styled-components<br>for styling, React Query for data fetching, and React Router for navigation...<br>[200 more words]</pre><pre>### Backend Service<br>The backend consists of multiple Express.js microservices...<br>[300 more words]</pre><p>After:</p><pre>## Architecture</pre><pre>**Pattern:** Microservices (React frontend + Express.js backend)<br>**Full details:** `docs/ARCHITECTURE.md`</pre><p>Savings: 500 words → 15 words = <strong>~365 tokens saved</strong></p><p><strong>5. Create component-specific docs</strong></p><pre>mkdir -p docs<br>touch docs/API.md         # API endpoints reference<br>touch docs/DATABASE.md    # Schema and migrations<br>touch docs/TESTING.md     # Test patterns<br>touch docs/DEPLOYMENT.md  # Deploy instructions</pre><p>Reference them from CLAUDE.md:</p><pre>## Documentation</pre><pre>- **API:** `docs/API.md`<br>- **Database:** `docs/DATABASE.md`<br>- **Testing:** `docs/TESTING.md`<br>- **Deployment:** `docs/DEPLOYMENT.md`</pre><p><strong>Token saved: ~600 per startup</strong> ✅</p><h3>Advanced (Half day)</h3><p><strong>6. Implement smart context detection</strong></p><pre># Add to .claude/hooks/session-start.sh</pre><pre>detect_context() {<br>    local changed=$(git diff --name-only HEAD~1 2&gt;/dev/null)</pre><pre>    case &quot;$changed&quot; in<br>        *test*|*spec*) echo &quot;💡 Testing: docs/TESTING.md&quot; ;;<br>        *api/*|*routes/*) echo &quot;💡 API: docs/API.md&quot; ;;<br>        *prisma/*|*migrations/*) echo &quot;💡 Database: docs/DATABASE.md&quot; ;;<br>        *Dockerfile*|*k8s/*) echo &quot;💡 Deploy: docs/DEPLOYMENT.md&quot; ;;<br>    esac<br>}</pre><pre>detect_context</pre><p><strong>7. Create docs/INDEX.md navigation hub</strong></p><pre># Documentation Index</pre><pre>## I want to...</pre><pre>**...start developing**<br>1. CLAUDE.md (read first)<br>2. docs/QUICK_REF.md (commands)<br>3. README.md (setup)</pre><pre>**...work on the API**<br>1. docs/API.md (endpoints)<br>2. docs/DATABASE.md (schema)<br>3. docs/TESTING.md (API tests)</pre><pre>**...deploy to production**<br>1. docs/DEPLOYMENT.md (deploy guide)<br>2. docs/QUICK_REF.md (common commands)<br>3. CLAUDE.md (critical rules)</pre><pre>**...troubleshoot issues**<br>1. docs/QUICK_REF.md (common fixes)<br>2. docs/troubleshooting/ (detailed guides)</pre><p><strong>8. Measure and iterate</strong></p><pre># Add to session-start hook<br>START_TIME=$(date +%s%N)</pre><pre># ... your checks ...</pre><pre>END_TIME=$(date +%s%N)<br>DURATION=$(( (END_TIME - START_TIME) / 1000000 ))<br>echo &quot;⏱️  Hook: ${DURATION}ms&quot;</pre><p><strong>Target:</strong> &lt; 500ms for session-start hook</p><h3>Common Pitfalls to Avoid</h3><h3>❌ Don’t Load Everything Upfront</h3><pre>&lt;!-- Bad: 2,000 lines in CLAUDE.md --&gt;<br>## Complete API Reference<br>[Every endpoint documented in detail]</pre><pre>## Complete Database Schema<br>[Every table, column, constraint documented]</pre><h3>✅ Do Link to Detailed Docs</h3><pre>&lt;!-- Good: ~10 lines in CLAUDE.md --&gt;<br>## API Reference<br>**Endpoints:** 42 REST endpoints<br>**Auth:** JWT tokens (Bearer)<br>**Docs:** `docs/API.md`</pre><pre>## Database Schema<br>**Tables:** 15 core tables<br>**ORM:** Prisma<br>**Schema:** `src/prisma/schema.prisma`<br>**Docs:** `docs/DATABASE.md`</pre><h3>❌ Don’t Duplicate Troubleshooting</h3><pre>&lt;!-- api/README.md --&gt;<br>## Troubleshooting<br>Database connection error: docker-compose up -d</pre><pre>&lt;!-- frontend/README.md --&gt;<br>## Troubleshooting<br>Database connection error: docker-compose up -d</pre><pre>&lt;!-- [10 more files with same content] --&gt;</pre><h3>✅ Do Create Reusable Snippets</h3><pre>&lt;!-- docs/troubleshooting/database.md --&gt;<br>## PostgreSQL Issues<br>[Complete troubleshooting guide]</pre><pre>&lt;!-- All other docs --&gt;<br>**Database issues?** See `docs/troubleshooting/database.md`</pre><h3>❌ Don’t Hide Critical Info</h3><pre>&lt;!-- Line 2,500 of CLAUDE.md --&gt;<br>## Important: Never force push to main</pre><h3>✅ Do Put Critical Info First</h3><pre>&lt;!-- Lines 30-40 of CLAUDE.md --&gt;<br>## 🚨 Critical Rules<br>1. ✅ Run tests before commit<br>2. ❌ Never force push to main<br>3. ❌ Never commit secrets</pre><h3>Measuring Success</h3><h3>1. Token Usage</h3><pre># Rough estimate<br>head -200 CLAUDE.md | wc -w | awk &#39;{print &quot;Tokens:&quot;, $1 * 0.75}&#39;</pre><p><strong>Target:</strong> &lt; 1,000 tokens for first 200 lines</p><h3>2. Session-Start Time</h3><pre># Add to session-start hook<br>time .claude/hooks/session-start.sh</pre><p><strong>Target:</strong> &lt; 2 seconds</p><h3>3. Context Relevance</h3><p>Track how often Claude asks for additional context:</p><pre>Week 1: Claude requested docs 15 times / 50 sessions = 30% miss rate<br>Week 2: After optimization = 5 times / 50 sessions = 10% miss rate ✅</pre><p><strong>Target:</strong> &lt; 10% miss rate</p><h3>4. Developer Satisfaction</h3><p>Survey your team:</p><ul><li>“Do you find what you need in QUICK_REF.md?” (Target: &gt;80% yes)</li><li>“Is the session-start output helpful?” (Target: &gt;70% yes)</li><li>“Can you navigate docs easily?” (Target: &gt;85% yes)</li></ul><h3>Key Takeaways</h3><p><strong>1. Session-start hooks are powerful</strong></p><ul><li>Show project status immediately</li><li>Preempt common questions</li><li>Guide developers to relevant docs</li><li>Free to implement</li></ul><p><strong>2. Tiered documentation works</strong></p><ul><li>Critical context (always): &lt;800 tokens</li><li>Component docs (on demand): 500–1,500 tokens</li><li>Reference (linked only): 0 tokens</li><li>Result: 60% token reduction</li></ul><p><strong>3. Quick reference cards save time</strong></p><ul><li>One-page QUICK_REF.md for common tasks</li><li>Troubleshooting table for instant fixes</li><li>Essential commands for copy-paste</li><li>Result: Faster developer + AI workflow</li></ul><p><strong>4. Less context = more intelligence</strong></p><ul><li>85% relevant context vs 30% before</li><li>Faster responses (3s vs 10s)</li><li>Lower costs ($72/mo vs $189/mo)</li><li>Better developer experience</li></ul><p><strong>5. Measure, don’t guess</strong></p><ul><li>Track token usage (goal: &lt;1,000 startup)</li><li>Measure session-start time (goal: &lt;2s)</li><li>Monitor context miss rate (goal: &lt;10%)</li><li>Survey developer satisfaction (goal: &gt;80%)</li></ul><h3>Start Optimizing Today</h3><p><strong>The 15-minute quick win:</strong></p><pre># 1. Create session-start hook<br>mkdir -p .claude/hooks<br>cat &gt; .claude/hooks/session-start.sh &lt;&lt; &#39;EOF&#39;<br>#!/bin/bash<br>echo &quot;🚀 Project Status&quot;<br>docker ps | grep -q postgres &amp;&amp; echo &quot;✅ Database&quot; || echo &quot;❌ Database&quot;<br>echo &quot;📍 Branch: $(git branch --show-current)&quot;<br>EOF<br>chmod +x .claude/hooks/session-start.sh</pre><pre># 2. Create quick reference<br>cat &gt; docs/QUICK_REF.md &lt;&lt; &#39;EOF&#39;<br># Quick Reference<br>## Commands<br>[Your top 10 commands]<br>## Issues<br>[Your top 5 fixes]<br>EOF</pre><pre># 3. Test it<br>claude code .</pre><p><strong>Expected results:</strong></p><ul><li>300+ tokens saved per session</li><li>5+ seconds faster responses</li><li>$30–50/month savings (small team)</li><li>Happier developers</li></ul><p>Your Claude Code project deserves better context management.</p><p><strong>Start optimizing now.</strong></p><h3>Resources</h3><h3>Tools</h3><ul><li><a href="https://code.claude.com/">Claude Code Documentation</a></li><li><a href="https://platform.openai.com/tokenizer">Token Counter</a></li><li><a href="https://github.com/tcort/markdown-link-check">Markdown Link Checker</a></li></ul><h3>Best Practices</h3><ul><li><a href="https://developers.google.com/style">Google Documentation Style Guide</a></li><li><a href="https://www.writethedocs.org/">Write the Docs</a></li><li><a href="https://documentation.divio.com/">The Documentation System</a></li></ul><p><strong>Tags:</strong> #AI #ClaudeCode #DeveloperProductivity #TokenOptimization #Documentation #CostSavings #WebDevelopment</p><p><strong>Published:</strong> November 2024 <strong>Reading Time:</strong> 20 minutes <strong>Difficulty:</strong> Beginner to Intermediate</p><p><em>Found this helpful? Give it a clap 👏 and share with your team. Better context management benefits everyone.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfad6fd477e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>