<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Nilofer 🚀</title>
    <description>The latest articles on DEV Community by Nilofer 🚀 (@nilofer_tweets).</description>
    <link>https://dev.to/nilofer_tweets</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1137273%2Fac10d3a1-21d6-46e3-90d6-889213a616bd.jpg</url>
      <title>DEV Community: Nilofer 🚀</title>
      <link>https://dev.to/nilofer_tweets</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/nilofer_tweets"/>
    <language>en</language>
    <item>
      <title>MoE Cost Analyzer: Benchmark Dense vs Mixture-of-Experts LLMs on Your Own Prompts with Real API Calls</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Mon, 20 Jul 2026 15:57:55 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/moe-cost-analyzer-benchmark-dense-vs-mixture-of-experts-llms-on-your-own-prompts-with-real-api-366h</link>
      <guid>https://dev.to/nilofer_tweets/moe-cost-analyzer-benchmark-dense-vs-mixture-of-experts-llms-on-your-own-prompts-with-real-api-366h</guid>
      <description>&lt;p&gt;Every team running LLMs in production eventually asks the same question: should we switch to a Mixture-of-Experts model? The MoE architecture activates fewer parameters per token, which means cheaper inference on shared infrastructure. But switching blindly is a gamble. Your prompts, your traffic volume, and your latency SLA determine whether the tradeoff actually pays off.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MoE Cost Analyzer&lt;/strong&gt; is a benchmarking tool that answers that question with hard numbers rather than theory. It takes a JSON file of your real production prompts, runs live API calls against both a dense and a MoE model via OpenRouter, measures actual latency and cost per query, and returns a concrete recommendation against SLA thresholds you define. No simulations. No estimates. Real calls, real results, one decision.&lt;/p&gt;

&lt;p&gt;To validate the tool, it was run on a 100-task sentiment-analysis benchmark against two Gemma variants: the dense &lt;code&gt;google/gemma-4-31b-it&lt;/code&gt; and the &lt;code&gt;MoE google/gemma-4-26b-a4b-it&lt;/code&gt;. Both models received identical prompts via live OpenRouter API calls. Every response was timed, every token counted, every dollar logged. The results below come from those 200 real API calls, with zero errors.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fytvtff59bztlmeyucpeh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fytvtff59bztlmeyucpeh.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Report: Validated Live Results
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Benchmark:&lt;/strong&gt; 100 sentiment-analysis tasks&lt;br&gt;
&lt;strong&gt;API:&lt;/strong&gt; OpenRouter (live calls, not simulated)&lt;br&gt;
&lt;strong&gt;Total calls:&lt;/strong&gt; 200 (100 per model) | &lt;strong&gt;Errors:&lt;/strong&gt; 0&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1pikskuxntkoc133ofn5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1pikskuxntkoc133ofn5.png" alt=" " width="745" height="417"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flpnb1w9yhx59dx43ujye.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flpnb1w9yhx59dx43ujye.png" alt=" " width="656" height="275"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Verdict:&lt;/strong&gt; &lt;strong&gt;USE MoE&lt;/strong&gt;. It met both SLA targets (latency &amp;lt; 3 000 ms, cost &amp;lt; $0.02/1K queries).&lt;/p&gt;
&lt;h2&gt;
  
  
  Reading the Results
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The MoE model is cheaper because it activates fewer parameters per token.&lt;/strong&gt;&lt;br&gt;
Both models produced identical token counts (4 939 total). The output quality is equivalent, but the MoE model costs 20% less per token on OpenRouter because inference is cheaper on sparse architectures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The MoE model is faster at median load (P50: -27%) but the gap narrows under stress (P95: -13%).&lt;/strong&gt;&lt;br&gt;
P50 shows typical behaviour: MoE is noticeably snappier. P95 shows tail latency under OpenRouter's shared infrastructure, and both models slow down similarly under peak load, so MoE still wins but by a smaller margin. For latency-sensitive SLAs check your own P95 against your threshold.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Token count is identical. Output quality is maintained.&lt;/strong&gt;&lt;br&gt;
Average prompt tokens (~49) and completion tokens (~20) were the same across both models, confirming the architecture change does not degrade output length or structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Zero errors across 200 live API calls.&lt;/strong&gt;&lt;br&gt;
The retry logic (3x exponential back-off on 429/5xx) was never triggered. Both models were stable throughout.&lt;/p&gt;
&lt;h2&gt;
  
  
  Extrapolated Production Impact
&lt;/h2&gt;

&lt;p&gt;Based on real measured average of ~49.4 tokens/query.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffa8b1t21gz9lh1z4gt8g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffa8b1t21gz9lh1z4gt8g.png" alt=" " width="616" height="179"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Your numbers will differ, which is exactly why you should run this tool on your own prompts.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Tool: Run It on Your Own Workload
&lt;/h2&gt;

&lt;p&gt;The report above is a fixed snapshot. Your production prompts are longer, your SLA is different, your traffic pattern is unique. Run the analyzer on your own benchmark to get a recommendation that actually applies to you.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setup&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/dakshjain-1616/MoE-Cost-Analyzer.git
cd MoE-Cost-Analyzer
pip install -r requirements.txt
cp .env.example .env
# add your key:  OPENROUTER_API_KEY=sk-or-v1-...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Prepare your benchmark&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a JSON file with your real production prompts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "My Production Benchmark",
  "tasks": [
    {
      "id": "task_001",
      "prompt": "Extract all dates mentioned in this support ticket: ...",
      "expected_labels": ["2026-01-15", "2026-02-03"]
    },
    {
      "id": "task_002",
      "prompt": "Classify the urgency of this message as Low / Medium / High: ...",
      "expected_labels": ["High"]
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use 50–200 representative prompts. The included &lt;code&gt;benchmark.json&lt;/code&gt; has 100 sentiment tasks you can use as a starting point.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Live run against OpenRouter
python analyze.py my_benchmark.json

# With custom SLA thresholds
python analyze.py my_benchmark.json \
  --sla-latency-ms 1500 \
  --sla-cost-per-1k 0.005 \
  --output my_results.csv

# Dry-run (no API calls, uses simulated data — good for testing the pipeline)
python analyze.py benchmark.json --dry-run
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What You Get
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. A Rich terminal table:&lt;/strong&gt; colour-coded decision matrix printed to stdout:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;╭────────────────────────┬──────────────────────┬──────────────────────┬──────────╮
│ Metric                 │ Dense                │ MoE                  │ MoE vs Dense │
├────────────────────────┼──────────────────────┼──────────────────────┼──────────┤
│ Avg Latency (ms)       │ 1721.3               │ 1283.2               │ -25.5%       │
│ P50 Latency (ms)       │ 833.2                │ 605.1                │ -27.3%       │
│ P95 Latency (ms)       │ 6748.1               │ 5879.2               │ -12.9%       │
│ Avg Cost / Query (USD) │ $0.000005            │ $0.000004            │ -20.0%       │
│ Total Cost (USD)       │ $0.0005              │ $0.0004              │ -20.0%       │
│ Total Tokens           │ 4939                 │ 4939                 │ 0.0%         │
│ Error Rate             │ 0.0%                 │ 0.0%                 │ N/A          │
╰────────────────────────┴──────────────────────┴──────────────────────┴──────────╯

Summary: MoE is 20.0% cheaper and 25.5% faster than the dense model.

✓  Recommendation: USE MoE — latency 1283ms &amp;lt; 3000ms SLA and cost $0.0040/1K &amp;lt; $0.0200/1K SLA
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. A per-query CSV:&lt;/strong&gt; every task, every model, every metric:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;task_id,model_id,latency_ms,prompt_tokens,completion_tokens,total_tokens,cost_usd,error
task_001,google/gemma-4-26b-a4b-it,816.6,60,20,80,0.0000064,
task_001,google/gemma-4-31b-it,1384.2,60,20,80,0.0000080,
task_002,google/gemma-4-26b-a4b-it,897.0,60,20,80,0.0000064,
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Load it in pandas for deeper analysis:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import pandas as pd
df = pd.read_csv("results.csv")
print(df.groupby("model_id")[["latency_ms", "cost_usd"]].describe())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. A recommendation string:&lt;/strong&gt; one of three outcomes:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;✓ USE MoE:&lt;/strong&gt; MoE meets both your latency and cost SLAs. Switch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;~ MARGINAL:&lt;/strong&gt; MoE meets one SLA but not both. Review the failing dimension.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;✗ STICK WITH DENSE:&lt;/strong&gt; MoE fails one or both SLAs at your thresholds. Do not switch yet.&lt;/p&gt;

&lt;h2&gt;
  
  
  CLI Reference
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python analyze.py &amp;lt;benchmark_file&amp;gt; [options]

Options:
  --dense-model       Dense model ID       (default: google/gemma-4-31b-it)
  --moe-model         MoE model ID         (default: google/gemma-4-26b-a4b-it)
  --sla-latency-ms    Avg latency cap (ms) (default: 2000)
  --sla-cost-per-1k   Cost cap per 1K reqs (default: 0.01)
  --output            CSV output path      (default: results.csv)
  --dry-run           Simulate API calls, no cost incurred
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Edge Cases and Reliability
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Empty benchmark file:&lt;/strong&gt; Prints "No tasks to evaluate." and exits cleanly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Invalid model ID:&lt;/strong&gt; Prints "Error: Invalid model ID" and exits with code 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Missing API key:&lt;/strong&gt; Suggests --dry-run and exits with code 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rate limit (429):&lt;/strong&gt; Retries up to 3x with exponential back-off (1s, 2s, 4s).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Server error (5xx):&lt;/strong&gt; Same retry logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Partial failures:&lt;/strong&gt; Error rate shown in matrix; successful tasks still analysed.&lt;/p&gt;

&lt;h2&gt;
  
  
  How It Works
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;your_benchmark.json
        │
        ▼
   analyze.py  ─── validates model IDs + task list
        │
        ▼
   runner.py   ─── asyncio.gather (semaphore = 5 concurrent)
                       ├── google/gemma-4-31b-it   ──► OpenRouter API
                       └── google/gemma-4-26b-a4b-it ─► OpenRouter API
        │
        ▼
  analyzer.py  ─── per-model stats: avg / p50 / p95 latency, cost
               ─── decision matrix DataFrame
               ─── recommend() against your SLA thresholds
               ─── save_csv()
        │
        ▼
  reporter.py  ─── Rich terminal table + coloured recommendation
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Concurrent requests are capped at 5 to stay within OpenRouter rate limits. Adjust &lt;code&gt;asyncio.Semaphore(5)&lt;/code&gt; in &lt;code&gt;src/runner.py&lt;/code&gt; if your plan allows higher throughput.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pricing
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4mq3j7aisr3tl3z8ognm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4mq3j7aisr3tl3z8ognm.png" alt=" " width="536" height="111"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Pricing is approximate and subject to change. Check OpenRouter for current rates. Update &lt;code&gt;src/pricing.py&lt;/code&gt; when OpenRouter rates change. The &lt;code&gt;ModelPricing&lt;/code&gt; dataclass also stores &lt;code&gt;context_window&lt;/code&gt; and model type for future extensions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tests
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pytest tests/ -v
# 18 passed in 5.11s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;test_analyzer.py:&lt;/strong&gt; Stats computation, decision matrix shape, recommendation logic, error-rate tracking.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;test_runner.py:&lt;/strong&gt; Pricing calculation, model ID validation, cost ordering.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;test_cli.py:&lt;/strong&gt; Empty benchmark → clean exit, invalid model ID → error message, dry-run → CSV written.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;moe-cost-analyzer/
├── analyze.py              ← entry point
├── benchmark.json          ← 100-task example benchmark
├── requirements.txt
├── .env.example
├── conftest.py
├── docs/
│   └── benchmark_results.svg  ← chart generated from live results
├── src/
│   ├── pricing.py          ← ModelPricing dataclass + compute_cost()
│   ├── runner.py           ← async OpenRouter calls, retry logic, dry-run
│   ├── analyzer.py         ← stats, decision matrix, CSV export
│   └── reporter.py         ← Rich terminal output
└── tests/
    ├── test_analyzer.py
    ├── test_runner.py
    ├── test_cli.py
    └── fixtures/
        └── empty_benchmark.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a tool that runs live API calls against both a dense and a MoE model on a user-supplied benchmark, measures real latency and cost, and returns a data-backed recommendation against configurable SLA thresholds. NEO planned and produced the files in this repository: the CLI entry point in &lt;code&gt;analyze.py&lt;/code&gt;, the async OpenRouter runner with retry logic and dry-run mode in &lt;code&gt;src/runner.py&lt;/code&gt;, the stats and decision matrix engine in &lt;code&gt;src/analyzer.py&lt;/code&gt;, the Rich terminal reporter in &lt;code&gt;src/reporter.py&lt;/code&gt;, the pricing dataclass in &lt;code&gt;src/pricing.py&lt;/code&gt;, three test files covering stats computation, pricing, and CLI behavior, and the 100-task example benchmark in benchmark.json.&lt;/p&gt;

&lt;p&gt;The result is a fully working analyzer that takes any JSON benchmark, makes live API calls to both models concurrently, and returns a colour-coded terminal table, a per-query CSV, and a single recommendation string in seconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Run it on your own production prompts before switching models.&lt;/strong&gt; &lt;br&gt;
Replace &lt;code&gt;benchmark.json&lt;/code&gt; with 50–200 of your actual production prompts, set your own &lt;code&gt;--sla-latency-ms&lt;/code&gt; and &lt;code&gt;--sla-cost-per-1k&lt;/code&gt; thresholds, and get a recommendation grounded in your real workload rather than a generic benchmark.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use &lt;code&gt;--dry-run&lt;/code&gt; to test the pipeline without spending API budget.&lt;/strong&gt; &lt;br&gt;
The dry-run mode uses simulated data and produces the same CSV and terminal output as a live run, making it safe to validate the setup and SLA threshold logic before committing to real API calls.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Load the per-query CSV in pandas for deeper analysis.&lt;/strong&gt; &lt;br&gt;
Every task, every model, every latency and cost measurement is written to a CSV. Grouping by &lt;code&gt;model_id&lt;/code&gt; and running &lt;code&gt;describe()&lt;/code&gt; on &lt;code&gt;latency_ms&lt;/code&gt; and &lt;code&gt;cost_usd&lt;/code&gt; surfaces distribution details that the summary table alone does not show.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Point it at any two OpenRouter models, not just Gemma.&lt;/strong&gt; &lt;br&gt;
The &lt;code&gt;--dense-model&lt;/code&gt; and &lt;code&gt;--moe-model&lt;/code&gt; flags accept any valid OpenRouter model ID. The same benchmark, the same SLA thresholds, and the same recommendation logic work across any pair of models you want to compare.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;The question "should we switch to a MoE model?" comes up every time a team hits a cost or latency wall. The answer is almost always "it depends on your prompts", which is why a tool that runs on your actual workload and returns a gated recommendation is more useful than any benchmark you did not run yourself.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/MoE-Cost-Analyzer" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/MoE-Cost-Analyzer&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>moe</category>
      <category>llm</category>
      <category>machinelearning</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Infra-Sizer: A CLI That Recommends the Right GPU Infrastructure for Any LLM Deployment</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Fri, 17 Jul 2026 06:23:05 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/infra-sizer-a-cli-that-recommends-the-right-gpu-infrastructure-for-any-llm-deployment-140l</link>
      <guid>https://dev.to/nilofer_tweets/infra-sizer-a-cli-that-recommends-the-right-gpu-infrastructure-for-any-llm-deployment-140l</guid>
      <description>&lt;p&gt;"What hardware do I need to serve this model?" is the first question every team asks before deployment. The answer requires juggling model size, throughput benchmarks, AWS pricing, batching math, and serving framework tradeoffs simultaneously.&lt;/p&gt;

&lt;p&gt;infra-sizer answers it in seconds. It is a CLI that takes a model ID, expected request volume, latency SLA, and context length, then outputs a concrete GPU recommendation: instance type, count, serving framework, batching config, and monthly cost estimate. Built autonomously using NEO.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1ubrztn9q0idja8criis.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1ubrztn9q0idja8criis.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Problem
&lt;/h2&gt;

&lt;p&gt;Getting the hardware wrong is expensive in both directions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overprovision:&lt;/strong&gt; Wasted $10k+/month on idle H100s.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Underprovision:&lt;/strong&gt; Latency SLA breaches and on-call pages at 3am.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wrong framework:&lt;/strong&gt; vLLM vs TGI vs llama.cpp have 5x throughput differences for certain workloads.&lt;/p&gt;

&lt;p&gt;Infra-Sizer gives you the right answer in seconds, not hours of spreadsheet work.&lt;/p&gt;

&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;

&lt;p&gt;The tool moves through five steps: the CLI parses inputs and fetches model metadata from the HuggingFace API, the GPU database looks up throughput benchmarks and AWS on-demand pricing across 6 GPU tiers, the planner sends the constraints and data to Llama-4-Maverick via OpenRouter for LLM-assisted reasoning, and the output is a Rich recommendation table covering GPU tier, instance count, framework, batch size, cost, and confidence score. If no API key is set, a rule-based fallback produces the recommendation without the LLM.&lt;/p&gt;

&lt;h2&gt;
  
  
  How It Works
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Parse CLI args: model ID, requests-per-second, latency SLA (seconds), context length&lt;/li&gt;
&lt;li&gt;Fetch model metadata from HuggingFace API: parameter count, architecture, dtype&lt;/li&gt;
&lt;li&gt;Query GPU database: look up throughput benchmarks and AWS on-demand pricing for 6 GPU tiers&lt;/li&gt;
&lt;li&gt;LLM reasoning: send constraints and data to Llama-4-Maverick via OpenRouter, which reasons over tradeoffs and recommends a config&lt;/li&gt;
&lt;li&gt;Rule-based fallback: if OPENROUTER_API_KEY is unset, a deterministic algorithm produces a recommendation without LLM&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  GPU Database Coverage
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3gdphi1kblmunfmeggb8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3gdphi1kblmunfmeggb8.png" alt=" " width="370" height="243"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git clone https://github.com/neo-engine/infra-sizer.git
cd infra-sizer
pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Requirements: Python 3.11+, openai, requests, rich, pandas&lt;/p&gt;

&lt;h2&gt;
  
  
  Usage
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python main.py --model Qwen/Qwen3-32B --rps 50 --latency-sla 2.0 --context 8192
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Arguments
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F550cxdyblm10wjrg1mk2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F550cxdyblm10wjrg1mk2.png" alt=" " width="544" height="180"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Environment Variables
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export OPENROUTER_API_KEY=your_key_here  # Enables LLM-assisted reasoning
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without the key, the tool falls back to rule-based recommendations. No crash, still useful.&lt;/p&gt;

&lt;h2&gt;
  
  
  Output
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;╔══════════════════════════════════════════════════════════════╗
║          Infra-Sizer — Infrastructure Recommendation         ║
╠══════════════════════════════════╦═══════════════════════════╣
║ GPU Tier                         ║ A100-80G                  ║
║ Instance Count                   ║ 2                         ║
║ Serving Framework                ║ vLLM                      ║
║ Recommended Batch Size           ║ 32                        ║
║ Max Concurrent Requests          ║ 64                        ║
║ Estimated Monthly Cost (AWS)     ║ $32,058                   ║
║ Confidence Score                 ║ 0.85                      ║
╚══════════════════════════════════╩═══════════════════════════╝
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Test Cases
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Small model, low load → CPU or single L4
python main.py --model 3B --rps 5 --latency-sla 10.0 --context 2048

# Large model, high load, tight SLA → multi-GPU H100
python main.py --model 70B --rps 100 --latency-sla 1.0 --context 4096

# Impossible constraint → "No viable configuration" + closest feasible
python main.py --model 1T --rps 1000 --latency-sla 0.1 --context 128000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  File Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;infra-sizer/
├── main.py              # CLI entrypoint
├── hf_metadata.py       # HuggingFace model card fetcher
├── gpu_db.py            # GPU performance database + cost calculator
├── planner.py           # LLM-assisted recommendation engine (OpenRouter)
├── data/
│   ├── gpu_specs.json   # Throughput benchmarks per GPU per model size
│   └── aws_pricing.json # AWS on-demand pricing per instance type
├── requirements.txt
└── README.md
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Why This Exists
&lt;/h2&gt;

&lt;p&gt;"Just throw it on an A100" is the most expensive mistake in AI infrastructure. The right hardware choice depends on model size, throughput requirements, latency SLA, and cost constraints, all at once. This tool does that math in seconds so you can make an informed decision before signing a cloud contract.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a CLI that takes an LLM model ID and deployment constraints, then outputs a concrete GPU infrastructure recommendation backed by real throughput benchmarks and AWS pricing. NEO planned and produced the files in this repository: the CLI entrypoint in main.py, the HuggingFace metadata fetcher, the GPU performance database and cost calculator, the LLM-assisted planner using Llama-4-Maverick via OpenRouter with a rule-based fallback, and the two data files covering GPU throughput benchmarks and AWS on-demand pricing across 6 GPU tiers.&lt;/p&gt;

&lt;p&gt;The result is a fully working CLI that takes four inputs and returns a concrete infrastructure recommendation with GPU tier, instance count, serving framework, batch size, monthly cost, and confidence score, in seconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Run it before signing a cloud contract.&lt;/strong&gt; &lt;br&gt;
Pass in the model ID, expected RPS, latency SLA, and context length and get a concrete GPU recommendation with a monthly cost estimate before committing to any instance type. Takes seconds instead of hours of spreadsheet work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Test impossible constraints to find the closest feasible configuration.&lt;/strong&gt; &lt;br&gt;
Passing an infeasible combination like a 1T-parameter model at 1000 RPS with a 0.1-second SLA returns "No viable configuration" alongside the closest feasible option, so you know exactly where the constraint breaks before you hit it in production.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use it without an API key for quick rule-based estimates.&lt;/strong&gt; &lt;br&gt;
Without OPENROUTER_API_KEY set, the tool falls back to a deterministic algorithm and still produces a recommendation. Useful for quick checks in environments where external API calls are not allowed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use it as a pre-deployment checklist step.&lt;/strong&gt;&lt;br&gt;
Before any model goes to production, running Infra-Sizer with the actual expected load validates whether the planned instance type and count will meet the latency SLA, with a confidence score attached to the recommendation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Every team deploying an LLM in production faces the same sizing problem, and most solve it the same way: by guessing, overprovisioning, and paying for it. Infra-Sizer makes that decision explicit, data-backed, and fast.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/infra-sizer" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/infra-sizer&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>llm</category>
      <category>cli</category>
      <category>machinelearning</category>
      <category>opensource</category>
    </item>
    <item>
      <title>NeuralUCB Router: An OpenAI-Compatible API Proxy That Routes LLM Requests Using a Multi-Armed Bandit Algorithm</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Thu, 16 Jul 2026 18:55:37 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/neuralucb-router-an-openai-compatible-api-proxy-that-routes-llm-requests-using-a-multi-armed-ic5</link>
      <guid>https://dev.to/nilofer_tweets/neuralucb-router-an-openai-compatible-api-proxy-that-routes-llm-requests-using-a-multi-armed-ic5</guid>
      <description>&lt;p&gt;Every team using LLMs in production hits the same wall: you don't need GPT-4 for every request, but you don't know in advance which ones actually need it. A user asking "what is 2+2?" and a user asking "find the bug in this recursive async Rust function" both hit the same /v1/chat/completions endpoint. Route them both to GPT-4o and you're paying $15 per million tokens for arithmetic. Route them both to a local model and quality collapses on complex work.&lt;/p&gt;

&lt;p&gt;NeuralUCB Router solves this. It is a production-quality OpenAI-compatible API proxy that uses the NeuralUCB multi-armed bandit algorithm to dynamically route requests to the cheapest model while retaining 92%+ quality. Built autonomously using NEO.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flebj530d32r1jl5t71n7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flebj530d32r1jl5t71n7.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Problem
&lt;/h2&gt;

&lt;p&gt;The naive solutions all fail:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Always use GPT-4o:&lt;/strong&gt; $1,500 per month for 100K queries, most of it wasted on simple tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Always use cheap or local model:&lt;/strong&gt; Quality collapses on hard reasoning, code, and math.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hard-coded if/else rules:&lt;/strong&gt; Brittle. You cannot enumerate every query type, and rules do not adapt.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Random routing:&lt;/strong&gt; No learning. Permanently suboptimal, ignores what is actually working.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fine-tune a classifier:&lt;/strong&gt; Requires labeled data, offline training, separate deployment, manual updates.&lt;/p&gt;

&lt;p&gt;The root issue: routing is a sequential decision problem under uncertainty. Each query is different, the right model depends on context you can only partially observe, and you need to keep learning as usage patterns shift.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Solution: NeuralUCB Bandit Routing
&lt;/h2&gt;

&lt;p&gt;NeuralUCB Router frames LLM selection as a multi-armed bandit problem: the same class of problem used in ad auctions, clinical trials, and recommendation systems. Each LLM is an "arm". Each request is a "round". The goal: maximize cumulative reward (quality divided by cost) over time.&lt;/p&gt;

&lt;p&gt;A classifier needs labeled training data telling it "this query → use GPT-4". A bandit generates its own training signal by trying models and observing outcomes. It learns online, from live traffic, with no pre-labeled dataset.&lt;/p&gt;

&lt;p&gt;How NeuralUCB works for each incoming request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1. Extract context features
   [query_length, token_entropy, is_code, is_math,
    time_of_day, session_cost, recent_quality, ...]

2. For each LLM arm, estimate:
   UCB score = predicted_reward(context) + exploration_bonus

   Where:
   - predicted_reward  = 2-layer MLP(context)   ← "exploitation"
   - exploration_bonus = λ · sqrt(gᵀ Z⁻¹ g)     ← "exploration"
     g = gradient of MLP w.r.t. last layer
     Z = covariance matrix (Sherman-Morrison updates, O(n²) not O(n³))

3. Route to arm with highest UCB score

4. Observe quality + cost → compute reward → update MLP weights + Z matrix
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The UCB bonus is the key insight. A model that hasn't been tried much has high uncertainty, which means a high exploration bonus and more selections until its true value is known. Once well-characterized, the bonus shrinks and the MLP prediction dominates.&lt;/p&gt;

&lt;p&gt;What happens after convergence (~500 requests):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Simple factual queries   →  local Ollama/Llama3    (free,   ~98% of the time)
Code generation          →  GPT-4o-mini            ($0.0006, ~87% of the time)
Complex reasoning/debug  →  GPT-4o                 ($0.015,  ~71% of the time)
Creative writing         →  Claude Haiku            ($0.0003, ~82% of the time)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result: 88% cost reduction versus always-GPT-4o, while retaining 8.9/10 average quality.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cost Savings
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvw45hkmszi60t4vsbyjv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvw45hkmszi60t4vsbyjv.png" alt=" " width="555" height="647"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Features
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Dynamic Model Routing:&lt;/strong&gt; Automatically selects the best model for each request based on context&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cost Optimization:&lt;/strong&gt; Routes 80% of requests to free/cheap models, saving 75%+ on API costs&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Quality Retention:&lt;/strong&gt; Maintains 92%+ quality by using expensive models for complex tasks&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;OpenAI-Compatible:&lt;/strong&gt; Drop-in replacement for OpenAI API (/v1/chat/completions, /v1/models)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Real-time Dashboard:&lt;/strong&gt; Streamlit dashboard with auto-refresh, cost savings meter, routing heatmap&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Multiple Backends:&lt;/strong&gt; Supports Ollama (local), OpenAI, Anthropic providers&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Audit Logging:&lt;/strong&gt; SQLite audit log with CSV/Parquet export for analysis&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌─────────────────────────────────────────────────────────────────┐
│                    NeuralUCB Router                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  User Request → /v1/chat/completions                            │
│       │                                                         │
│       ▼                                                         │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │  Context Extraction                                     │    │
│  │  • Prompt length, task type, temporal features          │    │
│  └─────────────────────────────────────────────────────────┘    │
│       │                                                         │
│       ▼                                                         │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │  NeuralUCB Bandit                                       │    │
│  │  • 2-layer MLP per model (hidden=64)                    │    │
│  │  • UCB = f(x) + λ√(gᵀZ⁻¹g)                              │    │
│  │  • Sherman-Morrison rank-1 updates                      │    │
│  └─────────────────────────────────────────────────────────┘    │
│       │                                                         │
│       ▼                                                         │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │  Model Selection                                        │    │
│  │  ┌─────┐ ┌─────┐ ┌─────┐                                │    │
│  │  │LLM A│ │LLM B│ │LLM C│ ← Cheapest + Quality           │    │
│  │  └─────┘ └─────┘ └─────┘                                │    │
│  └─────────────────────────────────────────────────────────┘    │
│       │                                                         │
│       ▼                                                         │
│  Response with audit logging                                    │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Quick Start
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Docker Deployment&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Clone repository
git clone https://github.com/dakshjain-1616/neuralucb-router.git
cd neuralucb-router

# Set API keys
export OPENAI_API_KEY=your-key
export ANTHROPIC_API_KEY=your-key

# Start services
docker-compose up -d

# Access router
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "auto", "messages": [{"role": "user", "content": "Hello"}]}'

# Access dashboard
open http://localhost:8501
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Local Installation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Install dependencies
pip install -r requirements.txt

# Run router
python -m router.proxy.server

# Run dashboard
streamlit run dashboard/app.py --port 8501
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;Edit &lt;code&gt;configs/example_config.yaml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;models:
  - name: llama3.2-1b
    provider: ollama
    base_url: http://localhost:11434
    cost_per_1k: 0.0
  - name: gpt-4o-mini
    provider: openai
    cost_per_1k: 0.00015
  - name: claude-haiku-4-5
    provider: anthropic
    cost_per_1k: 0.00025

bandit:
  hidden_dim: 64
  lambda_param: 1.0
  exploration_weight: 0.1
  learning_rate: 0.01
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Bandit Convergence
&lt;/h2&gt;

&lt;p&gt;Model selection distribution across 1,000 requests:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxsa6us0bry3g480g3s6h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxsa6us0bry3g480g3s6h.png" alt=" " width="680" height="347"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The bandit learns to route 80% of requests to free Llama3.2-1b while maintaining quality on complex tasks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Technical Details
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;NeuralUCB Algorithm&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Architecture: 2-layer MLP (hidden=64, ReLU activation, Sigmoid output) per model arm&lt;/li&gt;
&lt;li&gt;UCB Formula: UCB(model) = f(x; θ_m) + λ * sqrt(gᵀ Z⁻¹ g)&lt;/li&gt;
&lt;li&gt;f(x; θ_m): MLP prediction for model m&lt;/li&gt;
&lt;li&gt;g: Gradient of f with respect to θ_m&lt;/li&gt;
&lt;li&gt;Z: Covariance matrix updated via Sherman-Morrison&lt;/li&gt;
&lt;li&gt;λ: Exploration weight&lt;/li&gt;
&lt;li&gt;Updates: Sherman-Morrison rank-1 updates for Z⁻¹ (O(n²) vs O(n³) for full inverse)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Context Features (15 dimensions)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;prompt_length: Normalized token count&lt;/li&gt;
&lt;li&gt;task_type: One-hot [code, math, creative, qa, chat, other]&lt;/li&gt;
&lt;li&gt;avg_token_length: Average token length&lt;/li&gt;
&lt;li&gt;has_system_prompt: Binary flag&lt;/li&gt;
&lt;li&gt;time_of_day: Sin/cos encoding&lt;/li&gt;
&lt;li&gt;latency_ema: Per-model exponential moving average&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Reward Calculation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Two modes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Embedding Cosine Similarity: Compare response to reference using sentence-transformers&lt;/li&gt;
&lt;li&gt;LLM-as-Judge: Use LLM to score quality (1-5 scale)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Reward = quality / cost_per_1k (normalized)&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Run all tests
pytest tests/ -v

# Run specific test
pytest tests/test_neural_ucb.py -v
pytest tests/test_context.py -v
pytest tests/test_proxy.py -v
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All tests mock LLM calls. No API keys required for testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Dashboard Features
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Auto-refresh:&lt;/strong&gt; Updates every 2 seconds&lt;br&gt;
&lt;strong&gt;Cost Savings Meter:&lt;/strong&gt; Cumulative cost tracking&lt;br&gt;
&lt;strong&gt;Model Performance Bar Chart:&lt;/strong&gt; Selections and average rewards&lt;br&gt;
&lt;strong&gt;Routing Heatmap:&lt;/strong&gt; Visualize routing decisions over time&lt;br&gt;
&lt;strong&gt;Recent Decisions Table:&lt;/strong&gt; Last 20 routing events with metrics&lt;/p&gt;

&lt;h2&gt;
  
  
  API Endpoints
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fey5vmbpx155gxfbhdjlx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fey5vmbpx155gxfbhdjlx.png" alt=" " width="518" height="209"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;neuralucb-router/
├── router/bandit/
│   ├── neural_ucb.py     # NeuralUCB bandit algorithm
│   ├── context.py        # Context feature extraction
│   ├── reward.py         # Reward calculation
│   └── __init__.py
├── router/backends/
│   ├── base.py           # Backend provider ABC
│   ├── ollama.py         # Ollama integration
│   ├── openai_backend.py # OpenAI integration
│   ├── anthropic_backend.py # Anthropic integration
│   └── __init__.py
├── router/proxy/
│   ├── server.py         # FastAPI server
│   ├── middleware.py     # Auth/rate limiting
│   ├── openai_schema.py  # Pydantic schemas
│   └── __init__.py
├── router/audit/
│   ├── logger.py         # SQLite audit logging
│   ├── export.py         # CSV/Parquet export
│   └── __init__.py
├── router/config.py      # Configuration loader
├── dashboard/app.py      # Streamlit dashboard
├── tests/
│   ├── test_neural_ucb.py
│   ├── test_context.py
│   ├── test_proxy.py
│   └── __init__.py
├── configs/
│   ├── example_config.yaml
├── hf_export/
│   ├── README.md
│   ├── config.json
│   ├── router_state.json
│   ├── push_to_hub.py
├── infographics/
│   ├── routing_flow.txt
│   ├── cost_comparison.txt
│   ├── bandit_convergence.txt
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
├── pyproject.toml
└── README.md
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Export to Hugging Face
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from hf_export.push_to_hub import export_to_hub

export_to_hub(
    repo_id="your-username/neuralucb-router",
    config_path="configs/example_config.yaml",
    state_path="hf_export/router_state.json"
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Comparison
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbzwtius0r11ytxbu1cjo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbzwtius0r11ytxbu1cjo.png" alt=" " width="719" height="306"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a production-quality OpenAI-compatible API proxy that uses the NeuralUCB multi-armed bandit algorithm to dynamically route LLM requests based on context, cutting costs while retaining quality. NEO planned and produced the files in this repository: the bandit algorithm, context extraction, and reward calculation modules, three backend integrations for Ollama, OpenAI, and Anthropic, a FastAPI proxy server with middleware and Pydantic schemas, a SQLite audit logger with CSV and Parquet export, a Streamlit dashboard, a three-suite test setup, HuggingFace export tooling, Docker and compose files, and the configuration system.&lt;/p&gt;

&lt;p&gt;The result is a fully working intelligent router that learns from live traffic, converges after roughly 500 requests, routes 80% of requests to free or cheap models, and delivers 8.9/10 quality at 12% of the cost of always using GPT-4o.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Drop it in as a zero-config OpenAI proxy and immediately start cutting costs.&lt;/strong&gt; &lt;br&gt;
Since the router exposes a fully OpenAI-compatible /v1/chat/completions endpoint, any existing application pointing at the OpenAI API needs only its base URL changed to start routing intelligently. No code changes required beyond that one configuration line.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Add your own models by editing a single YAML file.&lt;/strong&gt; &lt;br&gt;
Any provider supported by Ollama, OpenAI, or Anthropic can be added to configs/example_config.yaml with a name, provider, base URL, and cost per 1K tokens. The bandit picks it up on the next start and begins exploring it automatically alongside existing arms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use the audit log to understand exactly how your traffic is being routed.&lt;/strong&gt; &lt;br&gt;
Every routing decision is written to SQLite with full metrics. The /v1/router/audit endpoint and the CSV/Parquet export let teams pull this data into any analytics tool and see which models are handling which query types, what quality scores they are producing, and where cost savings are actually coming from.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run the Streamlit dashboard as a live cost monitoring layer for your team.&lt;/strong&gt; &lt;br&gt;
The dashboard auto-refreshes every 2 seconds and shows cumulative cost savings, model selection distribution, and the last 20 routing decisions with metrics. Useful for keeping non-technical stakeholders informed without building a separate reporting tool.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Most teams end up on one of two bad equilibria: spending too much on a frontier model for every request, or accepting degraded quality from a cheap model across the board. NeuralUCB Router sits between those two by learning which requests actually need the expensive model and routing everything else to the cheapest option that can handle it.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/neuralucb-router" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/neuralucb-router&lt;/a&gt;&lt;br&gt;
The model is on HuggingFace at &lt;a href="https://huggingface.co/daksh-neo/neuralucb-router" rel="noopener noreferrer"&gt;https://huggingface.co/daksh-neo/neuralucb-router&lt;/a&gt;&lt;br&gt;
Install via pip: &lt;code&gt;pip install neuralucb-router&lt;/code&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>opensource</category>
      <category>mlops</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>AI Cost Optimizer CLI: Real-Time AI Cost Tracking, Model Routing, and Shadow AI Detection from the Terminal</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Wed, 15 Jul 2026 13:47:44 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/ai-cost-optimizer-cli-real-time-ai-cost-tracking-model-routing-and-shadow-ai-detection-from-the-hb3</link>
      <guid>https://dev.to/nilofer_tweets/ai-cost-optimizer-cli-real-time-ai-cost-tracking-model-routing-and-shadow-ai-detection-from-the-hb3</guid>
      <description>&lt;p&gt;Engineering teams running AI at scale eventually hit the same wall: no one knows exactly how much each model call costs, which GPU is idle, whether a cheaper model would have done the job just as well, or whether someone in the organization is quietly using an unauthorized AI service. The answers exist in the data, but nothing surfaces them without instrumentation. By the time costs are visible, the spend has already happened.&lt;/p&gt;

&lt;p&gt;AI Cost Optimizer CLI brings that visibility into the terminal before it becomes a problem. It is a command-line toolkit designed for engineering teams who use AI and LLM APIs at scale: real-time cost tracking at the token level, GPU utilization monitoring, intelligent model routing, caching analysis, shadow AI detection, and comprehensive reporting, all from a single CLI with no external API keys and no cloud dependencies.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkwpgkpo8bd0pg9j693nr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkwpgkpo8bd0pg9j693nr.png" alt=" " width="681" height="296"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What This Tool Does
&lt;/h2&gt;

&lt;p&gt;Six capabilities work together from one command entry point.&lt;/p&gt;

&lt;p&gt;The cost tracker logs every API call with precise attribution: prompt tokens multiplied by input price plus completion tokens multiplied by output price, per call, per session, per project, stored in a local SQLite database. The GPU monitor queries NVML for live metrics (utilization, memory, temperature, power draw) or generates realistic random-walk simulations when no NVIDIA hardware is present. The model router classifies task complexity using keyword analysis and recommends the cost-optimal model, routing low-complexity tasks to SLMs where the savings range from 60 to 90 percent versus frontier models. The caching advisor analyzes prompt patterns and estimates dollar savings across four caching strategies with daily, monthly, and yearly projections. The shadow AI scanner parses DNS packet captures to detect unauthorized AI API usage across 25+ known domains. The report generator aggregates all of this into a single actionable output: current cost, optimized cost, potential savings, and the routing change that gets there.&lt;/p&gt;

&lt;p&gt;A pricing database of 25+ models across 9 providers is built in. No external API keys are needed. No cloud dependencies. GPU monitoring works in simulation mode when no NVIDIA GPU is present.&lt;/p&gt;

&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;

&lt;p&gt;The CLI is built on click, with each subcommand routing to an independent backend module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌──────────────────────────────────────────────────────────────────────────┐
│                           neo-cost CLI (click)                            │
│                                                                          │
│   cost     gpu      route     cache     shadow    report    monitor      │
│   ─────   ─────   ───────   ───────   ───────   ───────   ───────      │
└──────────────────────────────────────────────────────────────────────────┘
         │         │         │          │         │          │
         ▼         ▼         ▼          ▼         ▼          ▼
┌─────────────┐ ┌─────────┐ ┌──────────┐ ┌─────────────┐ ┌────────┐
│ CostTracker │ │GPUMonit │ │ModelRoute│ │CachingAdvis │ │ShadowAI│
│             │ │ or      │ │ r        │ │ or          │ │Scanner │
│  ┌───────┐  │ │         │ │          │ │             │ │        │
│  │SQLite │  │ │pynvml + │ │PricingDB │ │PromptAnalys │ │dpkt +  │
│  │  DB   │  │ │ Demo    │ │ +        │ │ is +        │ │ Pcap   │
│  └───────┘  │ │ Mode    │ │Keyword   │ │SavingsCalc  │ │Parser  │
│             │ └─────────┘ │Classifier│ └─────────────┘ └────────┘
│  Per-call   │             └──────────┘
│  logging    │            ┌─────────────┐
│  Aggregated │            │ PRICING_DB  │
│  reports    │            │ (25 models) │
└─────────────┘            └─────────────┘
                                    ▲
                                    │
                              ┌──────────┐
                              │ config   │
                              │ (YAML)   │
                              └──────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The data flow follows each module's responsibility cleanly. The cost tracker logs each API call to a local SQLite database and produces aggregated reports. The GPU monitor queries NVML for live metrics or generates realistic simulations in demo mode. The model router classifies task complexity using keyword analysis and recommends the optimal model from the pricing database. The caching advisor analyzes prompt patterns and estimates dollar savings from different caching strategies. The shadow AI scanner parses DNS packet captures to detect unauthorized AI API usage. The report generator aggregates data across all modules into actionable recommendations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Features
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Cost Tracker: Token-Level Attribution&lt;/strong&gt;&lt;br&gt;
Every API call is tracked with precise cost attribution across five dimensions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Per-call costing: Prompt tokens × input price + completion tokens × output price&lt;/li&gt;
&lt;li&gt;Session tracking: Group related calls into sessions for project-level analysis&lt;/li&gt;
&lt;li&gt;Model breakdowns: See exactly what each model costs you&lt;/li&gt;
&lt;li&gt;Project breakdowns: Allocate costs across teams or applications&lt;/li&gt;
&lt;li&gt;Time-series: Daily cost trends over configurable periods&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sample output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;💰 Cost Logged — gpt-4o
╭───────────────────┬──────────────╮
│ Metric            │ Value        │
├───────────────────┼──────────────┤
│ Model             │ gpt-4o       │
│ Provider          │ OpenAI       │
│ Project           │ test-project │
│ Prompt Tokens     │ 500          │
│ Completion Tokens │ 150          │
│ Total Tokens      │ 650          │
│ Input Cost        │ $0.001250    │
│ Output Cost       │ $0.001500    │
│ Total Cost        │ $ 0.002750   │
╰───────────────────┴──────────────╯
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. GPU Monitor: Utilization and Alerts&lt;/strong&gt;&lt;br&gt;
Live GPU metrics with threshold-based alerts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;GPU Utilization: NVML or simulated random-walk&lt;/li&gt;
&lt;li&gt;Memory Usage: Used / Total GB with percentage&lt;/li&gt;
&lt;li&gt;Temperature: Live sensor reading in °C&lt;/li&gt;
&lt;li&gt;Power Draw: Current and max power in Watts&lt;/li&gt;
&lt;li&gt;Alert Thresholds: Configurable for temp, util, mem, power&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Demo mode generates realistic GPU metrics using a random-walk simulation, for development and testing without dedicated hardware. Continuous monitoring with &lt;code&gt;neo-cost gpu watch&lt;/code&gt; shows a live-updating terminal dashboard with ASCII bar charts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Model Router: Intelligent Routing Engine&lt;/strong&gt;&lt;br&gt;
Task complexity is classified across four dimensions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Simple: Summarization, translation, extraction, formatting&lt;/li&gt;
&lt;li&gt;Complex: Analysis, comparison, evaluation, troubleshooting&lt;/li&gt;
&lt;li&gt;Creative: Writing, composition, brainstorming, marketing&lt;/li&gt;
&lt;li&gt;Code: Implementation, debugging, refactoring, architecture&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Routing logic maps complexity to model category:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Low complexity → SLM (saves 60-90% vs frontier)&lt;/li&gt;
&lt;li&gt;Medium complexity → SLM with frontier fallback option&lt;/li&gt;
&lt;li&gt;High complexity → Frontier model for quality&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each model receives a composite score based on task-specific quality multiplier, per-call cost estimate, and token budget prediction.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Caching Advisor: Cost Savings Analysis&lt;/strong&gt;&lt;br&gt;
Four caching strategies evaluated with concrete dollar estimates:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Exact Match (~15% hit rate): Best for repeated identical prompts&lt;/li&gt;
&lt;li&gt;Semantic (~25% hit rate): Best for similar meaning, different wording&lt;/li&gt;
&lt;li&gt;Prompt Caching (~40% hit rate): Best for shared system prefixes and templates&lt;/li&gt;
&lt;li&gt;TTL-Based (~20% hit rate): Best for time-bounded repeated queries&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each strategy produces daily, monthly, and yearly savings projections based on estimated call volume.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Shadow AI Scanner: DNS-Based Detection&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unauthorized AI API usage is detected by analyzing DNS traffic. The detection database covers 25+ known AI API domains across providers including OpenAI, Anthropic, Google, Groq, DeepSeek, Mistral, Cohere, HuggingFace, Replicate, Perplexity, Together AI, and more.&lt;/p&gt;

&lt;p&gt;Risk scoring considers the number of queries to each AI domain, the sensitivity of the service (API endpoints score higher risk than web UIs), and the total number of unique AI services detected. Sample PCAP generation creates realistic test data with mixed benign and AI API DNS queries.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Report Generator: Comprehensive Insights&lt;/strong&gt;&lt;br&gt;
All six modules aggregate into a single report:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Current Cost: $152.40                                                        
Optimized Cost: $88.39                                                       
Potential Savings: $64.01                                                    
Savings %: 42.0%                                                             
Route 60% of simple/medium tasks from frontier to SLM models
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;Prerequisites&lt;/p&gt;

&lt;p&gt;Python 3.8 or higher&lt;br&gt;
pip (Python package manager)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Install from source&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Clone the repository&lt;/span&gt;
git clone https://github.com/your-org/neo-cost-optimizer.git
&lt;span class="nb"&gt;cd &lt;/span&gt;neo-cost-optimizer

&lt;span class="c"&gt;# Create and activate virtual environment (recommended)&lt;/span&gt;
python3 &lt;span class="nt"&gt;-m&lt;/span&gt; venv venv
&lt;span class="nb"&gt;source &lt;/span&gt;venv/bin/activate

&lt;span class="c"&gt;# Install dependencies&lt;/span&gt;
pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-r&lt;/span&gt; requirements.txt

&lt;span class="c"&gt;# Install the package&lt;/span&gt;
pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-e&lt;/span&gt; &lt;span class="nb"&gt;.&lt;/span&gt;

&lt;span class="c"&gt;# Verify installation&lt;/span&gt;
neo-cost &lt;span class="nt"&gt;--help&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Quick install via pip&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;neo-cost
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Dependencies&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxevj1e0u3u81yk5gl7xy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxevj1e0u3u81yk5gl7xy.png" alt=" " width="618" height="277"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quick Start&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Track a single API call&lt;/span&gt;
neo-cost cost log gpt-4o &lt;span class="nt"&gt;--prompt-tokens&lt;/span&gt; 500 &lt;span class="nt"&gt;--completion-tokens&lt;/span&gt; 150 &lt;span class="nt"&gt;--project&lt;/span&gt; my-app

&lt;span class="c"&gt;# View cost summary&lt;/span&gt;
neo-cost cost summary

&lt;span class="c"&gt;# Check GPU status (simulation mode)&lt;/span&gt;
neo-cost gpu status &lt;span class="nt"&gt;--demo&lt;/span&gt;

&lt;span class="c"&gt;# Get model routing recommendation&lt;/span&gt;
neo-cost route &lt;span class="s2"&gt;"Write a Python function to sort a list of dictionaries"&lt;/span&gt;

&lt;span class="c"&gt;# Analyze caching strategy&lt;/span&gt;
neo-cost cache &lt;span class="s2"&gt;"You are a helpful assistant. Summarize the following text:"&lt;/span&gt; &lt;span class="nt"&gt;--volume&lt;/span&gt; 5000

&lt;span class="c"&gt;# Scan for shadow AI usage (generates sample data automatically)&lt;/span&gt;
neo-cost shadow scan

&lt;span class="c"&gt;# Generate a comprehensive report&lt;/span&gt;
neo-cost report

&lt;span class="c"&gt;# List all models with pricing&lt;/span&gt;
neo-cost models

&lt;span class="c"&gt;# Show current configuration&lt;/span&gt;
neo-cost config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;Configuration is stored in &lt;code&gt;~/.config/neo-cost/config.yaml&lt;/code&gt; (or &lt;code&gt;$XDG_CONFIG_HOME/neo-cost/config.yaml&lt;/code&gt;) and is created automatically on first run.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Default configuration&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;cost_tracker&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;db_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;~/.neo-cost/cost_tracker.db&lt;/span&gt;
  &lt;span class="na"&gt;default_project&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;default&lt;/span&gt;

&lt;span class="na"&gt;gpu_monitor&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;poll_interval&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;2.0&lt;/span&gt;
  &lt;span class="na"&gt;temp_threshold_c&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;85&lt;/span&gt;
  &lt;span class="na"&gt;util_threshold_pct&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;95&lt;/span&gt;
  &lt;span class="na"&gt;memory_threshold_pct&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;90&lt;/span&gt;
  &lt;span class="na"&gt;power_threshold_w&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;400&lt;/span&gt;
  &lt;span class="na"&gt;demo_mode&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;

&lt;span class="na"&gt;model_router&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;default_slm&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;gpt-4o-mini&lt;/span&gt;
  &lt;span class="na"&gt;default_frontier&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;gpt-4o&lt;/span&gt;
  &lt;span class="na"&gt;token_budget_warning_pct&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;80&lt;/span&gt;

&lt;span class="na"&gt;caching_advisor&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;min_similarity&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;0.7&lt;/span&gt;
  &lt;span class="na"&gt;default_ttl_hours&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;24&lt;/span&gt;
  &lt;span class="na"&gt;cache_hit_cost_reduction_pct&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;90&lt;/span&gt;

&lt;span class="na"&gt;shadow_ai&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;sample_pcap_path&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;~/.neo-cost/shadow_ai_sample.pcap&lt;/span&gt;
  &lt;span class="na"&gt;risk_score_threshold&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;5&lt;/span&gt;

&lt;span class="na"&gt;reporting&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;output_dir&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;~/.neo-cost/reports&lt;/span&gt;
  &lt;span class="na"&gt;default_format&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;terminal&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Configuration is edited directly or viewed with &lt;code&gt;neo-cost config&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Command Reference
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;neo-cost cost&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgvnrd274azalrkla0pms.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgvnrd274azalrkla0pms.png" alt=" " width="800" height="231"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;neo-cost gpu&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;status: Current GPU metrics (--demo)&lt;/li&gt;
&lt;li&gt;watch: Live monitoring dashboard (--demo, --interval)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;neo-cost route&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5rv9syrd2tqkx3y8yj08.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5rv9syrd2tqkx3y8yj08.png" alt=" " width="320" height="161"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;neo-cost cache&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;--volume: Daily call volume (default: 1000)&lt;/li&gt;
&lt;li&gt;--ttl: TTL in hours (default: 24)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;neo-cost shadow&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fiutowz4lmh89sahjd7rl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fiutowz4lmh89sahjd7rl.png" alt=" " width="461" height="120"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Other commands&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;report: Comprehensive cost optimization report&lt;/li&gt;
&lt;li&gt;models: List all models with pricing&lt;/li&gt;
&lt;li&gt;config: Show current configuration&lt;/li&gt;
&lt;li&gt;monitor: Interactive real-time monitoring dashboard&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Example Workflows
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Workflow 1: Daily Cost Review&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# 1. Log all your API calls (integrate into your app or batch log)&lt;/span&gt;
neo-cost cost log gpt-4o &lt;span class="nt"&gt;--prompt-tokens&lt;/span&gt; 15000 &lt;span class="nt"&gt;--completion-tokens&lt;/span&gt; 3000 &lt;span class="nt"&gt;--project&lt;/span&gt; production
neo-cost cost log gpt-4o-mini &lt;span class="nt"&gt;--prompt-tokens&lt;/span&gt; 50000 &lt;span class="nt"&gt;--completion-tokens&lt;/span&gt; 10000 &lt;span class="nt"&gt;--project&lt;/span&gt; production

&lt;span class="c"&gt;# 2. Get daily summary&lt;/span&gt;
neo-cost cost summary &lt;span class="nt"&gt;--days&lt;/span&gt; 1

&lt;span class="c"&gt;# 3. Generate full report&lt;/span&gt;
neo-cost report &lt;span class="nt"&gt;--days&lt;/span&gt; 7
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Workflow 2: Model Selection Decision&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Compare routing for different task types&lt;/span&gt;
neo-cost route &lt;span class="s2"&gt;"Translate this document to Spanish"&lt;/span&gt;
neo-cost route &lt;span class="s2"&gt;"Debug this production issue with the microservice"&lt;/span&gt;
neo-cost route &lt;span class="s2"&gt;"Write a marketing campaign for our new product"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Workflow 3: Shadow AI Audit&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# 1. Capture DNS traffic on your network (using tcpdump)&lt;/span&gt;
&lt;span class="nb"&gt;sudo &lt;/span&gt;tcpdump &lt;span class="nt"&gt;-i&lt;/span&gt; eth0 port 53 &lt;span class="nt"&gt;-w&lt;/span&gt; network_traffic.pcap

&lt;span class="c"&gt;# 2. Scan with neo-cost&lt;/span&gt;
neo-cost shadow scan &lt;span class="nt"&gt;--pcap&lt;/span&gt; network_traffic.pcap

&lt;span class="c"&gt;# 3. Review the risk report and take action&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Workflow 4: Caching ROI Analysis&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Analyze your most common prompt patterns&lt;/span&gt;
neo-cost cache &lt;span class="s2"&gt;"You are a customer support agent..."&lt;/span&gt; &lt;span class="nt"&gt;--volume&lt;/span&gt; 10000
neo-cost cache &lt;span class="s2"&gt;"Summarize the following article:"&lt;/span&gt; &lt;span class="nt"&gt;--volume&lt;/span&gt; 5000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Workflow 5: GPU Capacity Planning&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Monitor GPU over time&lt;/span&gt;
neo-cost gpu watch &lt;span class="nt"&gt;--interval&lt;/span&gt; 5

&lt;span class="c"&gt;# Check current status&lt;/span&gt;
neo-cost gpu status
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Cost-Savings Methodology&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The cost-optimization engine uses a multi-factor scoring system:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Model Score = QualityMultiplier(TaskType, ModelCategory) / Cost
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Quality Multiplier Table:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffapeufk3ow77vyr4jqpd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffapeufk3ow77vyr4jqpd.png" alt=" " width="539" height="158"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Savings estimation analyzes the current model mix from cost tracker data, classifies each task by complexity, proposes alternative SLM routing for simple and medium tasks, applies an average savings of ~70% per rerouted call, and assumes a realistic adoption rate of 60%.&lt;/p&gt;

&lt;p&gt;Caching savings follow this formula:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Savings = DailyVolume × CacheHitRate × CostPerCall × 0.9
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The 0.9 factor represents the 90% cost reduction when serving from cache.&lt;/p&gt;

&lt;h2&gt;
  
  
  Real-World Use Cases
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Engineering Teams:&lt;/strong&gt; track per-feature AI costs across development sprints, optimize model selection for different product features, monitor GPU utilization in CI/CD pipelines.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;FinOps / Cloud Cost Teams:&lt;/strong&gt; allocate AI costs to business units and projects, identify cost anomalies with daily time-series tracking, audit shadow AI usage before it becomes a security risk.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AI Platform Teams:&lt;/strong&gt; build an internal model gateway with routing recommendations, implement caching for high-volume inference endpoints, create chargeback reports for internal AI consumers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Security Teams:&lt;/strong&gt; detect unauthorized AI API usage in corporate networks, identify data exfiltration risks from shadow AI tools, enforce AI usage policies with DNS-level monitoring.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a terminal-based toolkit that gives engineering teams full visibility into their AI spend: token-level cost attribution, GPU monitoring, intelligent model routing, caching analysis, shadow AI detection, and comprehensive reporting, all from a single CLI with no external dependencies. NEO planned and produced the files in this repository: six backend modules covering cost tracking, GPU monitoring, model routing, caching analysis, shadow AI scanning, and report generation, a built-in pricing database across 25+ models and 9 providers, a click-based CLI layer with 9 commands, a YAML configuration system, and a test suite under &lt;code&gt;test_suite/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The result is a fully working CLI toolkit that surfaces AI cost decisions in real time: what each call costs, which model would have been cheaper, how much caching would save, and whether unauthorized AI services are active on the network.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Track AI costs per project across an engineering team.&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;neo-cost cost log&lt;/code&gt; command accepts a model name, token counts, and a project label on every API call. The &lt;code&gt;neo-cost cost summary&lt;/code&gt; command then breaks down spending by model, project, and day, turning scattered API usage into an auditable cost record without any external tooling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Route tasks to cheaper models before making the API call.&lt;/strong&gt; &lt;br&gt;
The &lt;code&gt;neo-cost route&lt;/code&gt; command accepts a prompt and returns a model recommendation based on task complexity. Simple and medium-complexity tasks are routed to SLMs where savings of 60–90% versus frontier models are possible, with the scoring methodology transparently documented in &lt;code&gt;neo_cost/pricing_db.py&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Audit shadow AI usage across a corporate network.&lt;/strong&gt; &lt;br&gt;
DNS traffic captured with tcpdump can be piped directly into &lt;code&gt;neo-cost shadow scan&lt;/code&gt;. The scanner checks against 25+ known AI API domains and produces a risk score, giving security teams a concrete detection path without requiring agent deployment on individual machines.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Calculate caching ROI before committing to an implementation.&lt;/strong&gt; &lt;br&gt;
The &lt;code&gt;neo-cost cache&lt;/code&gt; command takes a prompt pattern and a daily call volume and returns projected savings across four strategies: exact match, semantic, prompt caching, and TTL-based, with daily, monthly, and yearly figures, so the decision to invest in a caching layer is backed by numbers before any code is written.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Most AI cost problems are invisible until they're large. By the time a team notices the spend, the model choices, the redundant calls, and the shadow usage have already accumulated. AI Cost Optimizer CLI moves that visibility to the point where the decisions are still being made: which model, which caching strategy, which teams are spending what, and puts it in the terminal where engineering teams already work.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/AI-Cost-Optimizer-CLI" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/AI-Cost-Optimizer-CLI&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>machinelearning</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Dataset Factory: A Production-Grade Benchmark Dataset Factory for AI Agent Evaluation</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Fri, 10 Jul 2026 04:21:47 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/dataset-factory-a-production-grade-benchmark-dataset-factory-for-ai-agent-evaluation-3ie9</link>
      <guid>https://dev.to/nilofer_tweets/dataset-factory-a-production-grade-benchmark-dataset-factory-for-ai-agent-evaluation-3ie9</guid>
      <description>&lt;p&gt;Evaluating AI agents requires benchmark datasets that are high-quality, diverse, balanced, and free of duplicates. Building those datasets by hand is slow, inconsistent, and hard to reproduce. The Mercor Dataset Factory automates the entire pipeline: generate, validate, deduplicate, analyze coverage, remediate gaps, audit, govern, and verify, all with a single command.&lt;/p&gt;

&lt;p&gt;It is not a simple data generator. It is a complete data engineering platform purpose-built for creating, validating, and releasing benchmark datasets for AI agent evaluation. &lt;/p&gt;

&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;p&gt;The factory produces a 1,000-record benchmark dataset spanning 10 agent-task categories with balanced difficulty distribution. Each record is a structured evaluation task containing a natural language query, ground-truth plan, expected tools, evaluation criteria, and success conditions.&lt;/p&gt;

&lt;p&gt;Every phase has a quality gate. If validation fails, the pipeline halts. If duplicates are found, they are automatically removed and replaced. If coverage gaps exist, they are remediated. The result is a production-ready benchmark with guaranteed quality guarantees.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fifokdy47avabcroe8dgv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fifokdy47avabcroe8dgv.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Features
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Config-driven architecture:&lt;/strong&gt; Categories are self-contained drop-in pack files in &lt;code&gt;categories/*.yaml&lt;/code&gt;. Global settings live in &lt;code&gt;config.yaml&lt;/code&gt;. No Python changes needed to customize.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Extensible categories:&lt;/strong&gt; Add a category by dropping a new pack file into &lt;code&gt;categories/&lt;/code&gt;. Remove one by deleting its pack. Packs are auto-discovered and authoritative for the category set.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;10 benchmark categories:&lt;/strong&gt; Coding, Web Research, Data Analysis, System Design, Debugging, Document Processing, Tool Usage, Multi-Step Reasoning, Operations/DevOps, Agent Coordination, each shipped as a pack in &lt;code&gt;categories/&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Balanced distribution:&lt;/strong&gt; Exactly 100 records per category, 330/340/330 split across easy/medium/hard&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Source/config preflight:&lt;/strong&gt; A pydantic-based validator (&lt;code&gt;factory/config_validator.py&lt;/code&gt;) checks the configuration before any work runs, catching incomplete categories, bad/duplicate prefixes, unknown template placeholders, and inconsistent counts&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Canonical record contract:&lt;/strong&gt; Every record is validated against a declared JSON Schema (&lt;code&gt;schema/record.schema.json&lt;/code&gt;) in addition to the inline validation rules&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Near-duplicate-aware generation:&lt;/strong&gt; The generator rejects near-duplicate queries at creation time using a pure-stdlib term-frequency cosine guard, plus a 3-layer dedup pass (exact MD5 hash, TF-IDF cosine, semantic embedding)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;100% coverage guarantee:&lt;/strong&gt; Automatic gap detection and remediation for tools (127) and domains (118)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;8-dimensional auditing:&lt;/strong&gt; Schema quality, diversity, coverage, difficulty balance, tool diversity, duplicate rate, auditability, reproducibility, weighted to a single 0-100 score&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Independent verification:&lt;/strong&gt; A separate Python script (&lt;code&gt;verification.py&lt;/code&gt;) with zero imports from the factory package validates independently&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Full governance:&lt;/strong&gt; Dataset card, release notes, methodology document, lineage tracking, versioning strategy&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Fully reproducible:&lt;/strong&gt; Single &lt;code&gt;--seed 42&lt;/code&gt; flag locks every stochastic component&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mercorDatasetFactory/
│
├── README.md                          ← This file
├── CONTRIBUTING.md                    ← Contributor guide (setup, tests, conventions)
├── LICENSE                            ← MIT License
├── pyproject.toml                     ← Packaging metadata + `dataset-factory` entry point
├── requirements.txt                   ← Runtime dependencies
├── requirements-dev.txt               ← Dev/test dependencies (pytest, coverage)
├── dataset_factory.py                 ← Main orchestrator — the CLI entry point
├── verification.py                    ← Independent verification (zero factory imports)
├── config.yaml                        ← GLOBAL configuration only (targets, difficulties, schema constraints, seed)
│
├── categories/                        ← Category packs — one self-contained YAML per category (authoritative)
│   ├── coding.yaml
│   ├── web_research.yaml
│   ├── ...                            ← 10 built-in packs; drop a new file to add a category
│   └── agent_coordination.yaml
│
├── schema/
│   └── record.schema.json             ← Canonical record JSON Schema (the data contract)
│
├── factory/                           ← Core factory package
│   ├── __init__.py
│   ├── config_loader.py               ← Config + category-pack loading, deep-merge, defaults inline
│   ├── config_validator.py            ← Pydantic source/config preflight validator
│   ├── record_schema.py               ← Builds the JSON Schema record contract from config
│   ├── schema.py                      ← Constants, enums, field definitions, schema constraints
│   ├── categories.py                  ← Category registries (loaded from packs via config_loader)
│   ├── templates.py                   ← Query/plan/criteria/success prompt templates
│   ├── generator.py                   ← Stratified sampling, near-duplicate guard &amp;amp; record construction
│   ├── validator.py                   ← Schema + JSON Schema contract validation &amp;amp; distribution analysis
│   ├── deduplicator.py                ← 3-layer dedup (exact, TF-IDF, semantic)
│   ├── coverage.py                    ← Coverage matrices &amp;amp; over/under-representation analysis
│   ├── remediator.py                  ← Automatic gap remediation &amp;amp; supplemental generation
│   ├── auditor.py                     ← 8-dimensional weighted quality scoring
│   └── governance.py                  ← Governance document generation (card, notes, methodology)
│
├── tests/                             ← Test suite (run with `pytest -q`)
├── .github/                           ← CI workflows (must pass on every change)
│
├── artifacts/                         ← All pipeline outputs (git-ignored; regenerated each run)
│   ├── dataset.jsonl                  ★ Final 1,000-record benchmark dataset
│   ├── validation_report.md           ★ Schema, contract &amp;amp; distribution validation results
│   ├── duplicate_analysis.md          ★ 3-layer dedup analysis with examples
│   ├── coverage_report.md             ★ Tool/domain/category coverage matrices
│   ├── remediation_report.md          ★ Gap remediation log (if any gaps found)
│   ├── audit_report.md                ★ 8-dimensional quality score report
│   ├── governance.md                  ★ Dataset lineage, assumptions, versioning
│   ├── release_notes.md               ★ Release documentation
│   ├── dataset_card.md                ★ Dataset card (HuggingFace-style)
│   └── generation_methodology.md      ★ Full methodology for reproducibility
│
├── plans/                             ← Implementation plans
│   ├── plan.md
│   └── config_driven_plan.md
│
└── test_custom_config.yaml            ← Example custom config for testing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Quick Start
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python 3.8+&lt;/li&gt;
&lt;li&gt;pip (Python package installer)&lt;/li&gt;
&lt;li&gt;~4 GB RAM (sentence-transformers model loads to ~800MB, preprocessing on CPU)&lt;/li&gt;
&lt;li&gt;No GPU required: all phases run on CPU&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;1. Set Up Environment&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Clone or navigate to the project
cd mercorDatasetFactory

# Create a virtual environment (recommended)
python3 -m venv venv
source venv/bin/activate     # Linux/macOS
# .\venv\Scripts\activate    # Windows
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Install Dependencies&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install scikit-learn sentence-transformers pyyaml pydantic
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: scikit-learn is used for TF-IDF vectorization in the deduplication layer. sentence-transformers provides the all-MiniLM-L6-v2 embedding model for semantic duplicate detection. pyyaml handles config and category-pack loading. pydantic (v2) powers the source/config preflight validator.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Run the Full Pipeline&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 dataset_factory.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The pipeline will:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Generate 1,000 records using seed=42 (reproducible)&lt;/li&gt;
&lt;li&gt;Validate every record against schema, field constraints, and distribution targets&lt;/li&gt;
&lt;li&gt;Deduplicate using 3-layer detection (exact, TF-IDF, semantic), removing and replacing flagged records&lt;/li&gt;
&lt;li&gt;Analyze coverage of all 127 tools and 118 domains across 10 categories&lt;/li&gt;
&lt;li&gt;Remediate any gaps automatically with supplemental records&lt;/li&gt;
&lt;li&gt;Audit the dataset across 8 quality dimensions with weighted scoring&lt;/li&gt;
&lt;li&gt;Generate governance documents: dataset card, release notes, methodology&lt;/li&gt;
&lt;li&gt;Run independent verification: 6 checks resulting in PASS/FAIL&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All outputs appear in &lt;code&gt;artifacts/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Verify Independence&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 verification.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Expected output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;============================================================
OVERALL: PASS (6/6 checks passed)
============================================================
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This script has zero imports from the &lt;code&gt;factory/&lt;/code&gt; package. It independently validates the dataset by reading &lt;code&gt;artifacts/dataset.jsonl&lt;/code&gt; directly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CLI Reference&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 dataset_factory.py [OPTIONS]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj60fx598vgz3pfkeq7wr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj60fx598vgz3pfkeq7wr.png" alt=" " width="799" height="265"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Full factory run (reproducible default)
python3 dataset_factory.py

# Custom seed and record count
python3 dataset_factory.py --seed 123 --count 500

# Use a custom configuration
python3 dataset_factory.py --config my_custom_config.yaml

# Re-validate and re-audit an existing dataset
python3 dataset_factory.py --skip-generation

# Validate the configuration and category packs without generating anything
python3 dataset_factory.py --validate-config

# Custom config + custom seed + custom count
python3 dataset_factory.py --config my_config.yaml --seed 7 --count 2000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Source/config validation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before any generation work, the pipeline runs a pydantic-based preflight (&lt;code&gt;factory/config_validator.py&lt;/code&gt;) over the merged configuration and the discovered category packs. It aggregates all problems into a single report and refuses to run if there are hard errors: incomplete categories, malformed or duplicate prefixes, unknown template placeholders (allowed: domain, topic, code_snippet, claim, n, stack_trace, task_type). Count drift is surfaced as a non-fatal warning. Run the preflight on its own with &lt;code&gt;--validate-config&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Config validation: PASS — configuration is coherent.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pipeline Architecture
&lt;/h2&gt;

&lt;p&gt;Each phase has a specific responsibility and a quality gate. If any phase fails its gate, the pipeline halts with a clear error message.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 1: Generation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: &lt;code&gt;factory/generator.py&lt;/code&gt; → &lt;code&gt;DatasetGenerator&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Stratified sampling across 10 categories x 3 difficulty levels (30 strata). Each record is constructed from templates with randomized domain, tool, and task-type substitutions. The generator maintains running counters to ensure exact balance.&lt;/p&gt;

&lt;p&gt;Quality gate: Target distribution (±1 record per category per difficulty). If the generator cannot meet targets after 2x attempts, it reports generation statistics for diagnosis.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 2: Validation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: factory/validator.py → validate_dataset()&lt;/p&gt;

&lt;p&gt;Validates every record against the schema definition:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;All 9 required fields present with correct types&lt;/li&gt;
&lt;li&gt;ID format: {CATEGORY_PREFIX}_{SEQ:03d} (e.g., COD_001, WEB_042)&lt;/li&gt;
&lt;li&gt;Query length: 50–500 characters&lt;/li&gt;
&lt;li&gt;Plan steps: 3–8 (varies by difficulty)&lt;/li&gt;
&lt;li&gt;Evaluation criteria: ≥2&lt;/li&gt;
&lt;li&gt;Success conditions: ≥1&lt;/li&gt;
&lt;li&gt;Tools: ≥1&lt;/li&gt;
&lt;li&gt;Category distribution: 100 ± 5 per category&lt;/li&gt;
&lt;li&gt;Difficulty distribution: easy ±5%, medium ±5%, hard ±5%&lt;/li&gt;
&lt;li&gt;Query diversity: unique queries ≥ 95%&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Gate: Pipeline halts if schema validation fails. Distribution warnings are reported but non-fatal.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 3: Deduplication&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: &lt;code&gt;factory/deduplicator.py&lt;/code&gt; → &lt;code&gt;DatasetDeduplicator&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Three-layer duplicate detection, applied in sequence:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqfalam6zlkyrs4xjjflw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqfalam6zlkyrs4xjjflw.png" alt=" " width="800" height="155"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Flagged duplicate records are removed and replacement records are automatically generated to maintain exactly 1,000 records with balanced category and difficulty distributions.&lt;/p&gt;

&lt;p&gt;Gate: Pipeline proceeds regardless (dedup always succeeds, but high duplicate rates are reflected in the audit score).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 4: Coverage Analysis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: factory/coverage.py → analyze_coverage()&lt;/p&gt;

&lt;p&gt;Builds coverage matrices for three dimensions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Tool coverage: All 127 registered tools appear in at least one record&lt;/li&gt;
&lt;li&gt;Domain coverage: All 118 registered domains appear in at least one record&lt;/li&gt;
&lt;li&gt;Category x Difficulty: No empty stratum&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also checks for over/under-representation using a ±20% threshold from expected distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 5: Gap Remediation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: factory/remediator.py → remediate()&lt;/p&gt;

&lt;p&gt;If any gaps are found in Phase 4, the remediator identifies the specific missing tools/domains, generates supplemental records targeting those gaps, tracks per-category sequence numbers to avoid ID collisions, and merges supplemental records into the dataset.&lt;/p&gt;

&lt;p&gt;Gate: Pipeline halts if remediation fails.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 6: Audit&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: factory/auditor.py → audit_dataset()&lt;/p&gt;

&lt;p&gt;Eight quality dimensions, each scored 0–100 and weighted:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr6xkir198p43a87popwi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr6xkir198p43a87popwi.png" alt=" " width="797" height="338"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Rating scale: EXCELLENT (≥90), GOOD (≥75), FAIR (≥60), POOR (&amp;lt;60)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 7: Governance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: &lt;code&gt;factory/governance.py&lt;/code&gt; → &lt;code&gt;generate_all()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Generates four documents automatically: &lt;code&gt;governance.md&lt;/code&gt;, &lt;code&gt;release_notes.md&lt;/code&gt;, &lt;code&gt;dataset_card.md&lt;/code&gt;, and &lt;code&gt;generation_methodology.md&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phase 8: Independent Verification&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Engine: verification.py (standalone script)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff2q92azfxhiwfmmin6dy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff2q92azfxhiwfmmin6dy.png" alt=" " width="800" height="347"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Gate: Final release gate. The dataset must pass 6/6 before it can be considered production-ready.&lt;/p&gt;

&lt;h2&gt;
  
  
  Configuration System
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;How Configuration Works&lt;/strong&gt;&lt;br&gt;
Configuration is split into two concerns:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Category packs (&lt;code&gt;categories/*.yaml&lt;/code&gt;): one self-contained file per category, auto-discovered and authoritative&lt;/li&gt;
&lt;li&gt;Global config (&lt;code&gt;config.yaml&lt;/code&gt;): globals only: record targets, difficulties, SCHEMA_CONSTRAINTS, DEFAULT_SEED, and difficulty step ranges/tags&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The factory uses a layered configuration architecture:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Python defaults in config_loader.py]
            │
            ▼
[category packs in categories/*.yaml]  ← discovered &amp;amp; merged (authoritative for categories)
            │
            ▼
[config.yaml at project root]  ← deep-merge globals over defaults
            │
            ▼
[--config CLI flag / env var]  ← deep-merge over everything
            │
            ▼
[Module-level globals]
(schema.py, categories.py, templates.py → generator.py, etc.)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The deep-merge algorithm: dictionaries are merged recursively; lists and scalars are replaced entirely by the user config (not appended to).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using a Custom Config&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Via CLI flag
python3 dataset_factory.py --config my_dataset_config.yaml

# Via environment variable
export DATASET_FACTORY_CONFIG=/path/to/config.yaml
python3 dataset_factory.py

# CLI overrides env var
python3 dataset_factory.py --config override.yaml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;What You Can Customize&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;config.yaml&lt;/strong&gt; controls the global settings: difficulty ratios, record targets, field bounds, the default seed, and difficulty step ranges and tags. Edit this file to change how many records are generated, how they are split across difficulty levels, or what constraints apply to fields like query length and plan steps.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;categories/.yaml&lt;/strong&gt; controls everything per category: the category name, its unique record ID prefix, the tasks it covers, the tools and domains available to it, the query and plan step templates, evaluation criteria and success condition templates, and an optional topic pool. Add a category by dropping a new pack file. Remove one by deleting it. These packs are the authoritative source for the category set and all per-category data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Custom Globals Config&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# my_dataset_config.yaml — globals only; categories come from categories/*.yaml

TOTAL_RECORDS: 500
RECORDS_PER_CATEGORY: 50
DIFFICULTY_TARGETS:
  easy: 25
  medium: 25
  hard: 0        # Skip hard difficulty entirely
GLOBAL_DIFFICULTY_TARGETS:
  easy: 250
  medium: 250
  hard: 0
SCHEMA_CONSTRAINTS:
  user_query_min_length: 50
  user_query_max_length: 500
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Config File Structure&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;TOTAL_RECORDS: 1000
RECORDS_PER_CATEGORY: 100
SCHEMA_CONSTRAINTS:
  user_query_min_length: 50
  user_query_max_length: 500
  plan_min_steps: 3
  plan_max_steps: 8
  min_tools: 1
  max_tools: 10
  min_criteria: 2
  max_criteria: 6
  min_conditions: 1
  max_conditions: 5
  min_domains: 1
  max_domains: 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Programmatic Reload&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from factory.config_loader import reload_config

# Load a different config at runtime (optionally validate it)
reload_config("/path/to/custom_config.yaml", validate=True)

# All downstream modules immediately reflect the new values
from factory.schema import TOTAL_RECORDS, SCHEMA_CONSTRAINTS
print(TOTAL_RECORDS)                              # Updated record target
print(SCHEMA_CONSTRAINTS['user_query_max_length'])  # Updated field bound
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Adding a Category
&lt;/h2&gt;

&lt;p&gt;Categories are self-contained drop-in pack files. To add a category, no Python or &lt;code&gt;config.yaml&lt;/code&gt; changes are needed. Drop a new &lt;code&gt;categories/&amp;lt;name&amp;gt;.yaml&lt;/code&gt; file. Packs are auto-discovered and authoritative for the category set.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fikp0xrmsh8mng08dn7pv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fikp0xrmsh8mng08dn7pv.png" alt=" " width="800" height="478"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Allowed template placeholders: domain, topic, code_snippet, claim, n, stack_trace, task_type.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Drop a pack file&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# categories/incident_response.yaml
name: incident_response
order: 11
prefix: INC
tasks:
  - triage
  - root_cause_analysis
  - postmortem
tools:
  - pager
  - log_search
  - metrics_dashboard
  - runbook
domains:
  - payments
  - identity
  - data_platform
topic_pool:
  - a cascading service outage
  - a degraded p99 latency spike
query_templates:
  - "Triage {topic} in the {domain} system and identify the {task_type} steps for {n} on-call engineers."
  - "Write a postmortem for {topic} affecting {domain}, including timeline and remediation."
plan_step_templates:
  - "Acknowledge the alert for {topic} and assemble responders"
  - "Correlate logs and metrics to localize {topic}"
  - "Apply mitigation and verify recovery of {domain}"
evaluation_criteria_templates:
  - "Root cause of {topic} is correctly identified"
  - "Mitigation restores the {domain} service"
success_condition_templates:
  - "Incident is resolved and a postmortem is filed"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Validate the config (preflight)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 dataset_factory.py --validate-config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Run the pipeline as usual&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 dataset_factory.py --seed 42
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;NUM_CATEGORIES is derived automatically from the discovered packs, so the new category is picked up with no further changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Removing or relocating packs&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Remove a category: delete its &lt;code&gt;categories/&amp;lt;name&amp;gt;.yaml&lt;/code&gt; pack.&lt;/p&gt;

&lt;p&gt;Use a different packs directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export DATASET_FACTORY_CATEGORIES_DIR=/path/to/my/packs
python3 dataset_factory.py --validate-config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Programmatic API
&lt;/h2&gt;

&lt;p&gt;Each factory module can be imported independently for custom pipelines or integration into larger systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Basic Usage&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Generate a dataset
from factory.generator import DatasetGenerator

gen = DatasetGenerator(seed=42)
records = gen.generate(1000)
gen.save(records, "artifacts/dataset.jsonl")

# Validate
from factory.validator import validate_dataset

result = validate_dataset("artifacts/dataset.jsonl", "artifacts/validation_report.md")
print(f"Status: {result['overall']['status']}")   # "PASS" or "FAIL"
print(f"Checks: {result['overall']['passed']}/{result['overall']['total']}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Full Pipeline Programmatically&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from factory.generator import DatasetGenerator
from factory.validator import validate_dataset
from factory.deduplicator import DatasetDeduplicator
from factory.coverage import analyze_coverage
from factory.remediator import remediate
from factory.auditor import audit_dataset
from factory.governance import generate_all

# Generate
gen = DatasetGenerator(seed=42)
records = gen.generate(1000)
gen.save(records, "artifacts/dataset.jsonl")

# Validate
validation = validate_dataset("artifacts/dataset.jsonl", "artifacts/validation_report.md")
if validation['overall']['status'] != 'PASS':
    exit(1)

# Deduplicate
import json
deduper = DatasetDeduplicator(records)
analysis = deduper.analyze_all()
deduped, dedup_analysis = deduper.deduplicate()      # returns (records, analysis)
with open("artifacts/dataset.jsonl", "w") as f:
    for rec in deduped:
        f.write(json.dumps(rec) + "\n")
print(f"Removed {len(records) - dedup_analysis['remaining_records']} duplicates")

# Coverage
coverage = analyze_coverage("artifacts/dataset.jsonl", "artifacts/coverage_report.md")
print(f"Tool coverage: {coverage['tool_coverage']['global']['overall_coverage_pct']}")

# Remediate
remediation = remediate(
    "artifacts/dataset.jsonl",
    coverage_results=coverage,
    output_path="artifacts/remediation_report.md",
    updated_dataset_path="artifacts/dataset.jsonl",
)
print(f"Gaps: {remediation['gaps_identified']}, Generated: {remediation['supplemental_generated']}")

# Audit
audit = audit_dataset("artifacts/dataset.jsonl", "artifacts/audit_report.md", dedup_results=analysis)
print(f"Score: {audit['overall_score']:.2f}/100 ({audit['rating']})")

# Governance
generate_all("artifacts/dataset.jsonl")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Deduplicator Details&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from factory.deduplicator import DatasetDeduplicator

deduper = DatasetDeduplicator(records)

# Run all 3 layers (consolidated)
full_analysis = deduper.analyze_all()
print(f"Total duplicates found: {full_analysis['total_duplicates_found']}")

# Or run layers individually
exact_results = deduper.find_exact_duplicates()
tfidf_results = deduper.find_tfidf_duplicates()
semantic_results = deduper.find_semantic_duplicates()

# Remove duplicates → (deduplicated_records, analysis)
deduped, analysis = deduper.deduplicate()
print(f"Remaining after dedup: {analysis['remaining_records']}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Coverage Analyzer&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from factory.coverage import analyze_coverage

result = analyze_coverage("artifacts/dataset.jsonl", "artifacts/coverage_report.md")

# Per-category tool coverage
for cat, cov in result['tool_coverage']['per_category'].items():
    used = cov['unique_tools_used']
    total = cov['tools_available']
    pct = cov['coverage_pct']
    print(f"{cat}: {used}/{total} tools ({pct})")

# Global coverage stats
global_cov = result['tool_coverage']['global']
print(f"Overall tool coverage: {global_cov['overall_coverage_pct']}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Output Artifacts
&lt;/h2&gt;

&lt;p&gt;The pipeline writes 10 artifacts to the &lt;code&gt;artifacts/&lt;/code&gt; directory (git-ignored, regenerated by every run):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;dataset.jsonl&lt;/strong&gt; is the final 1,000-record benchmark dataset, one JSON object per line.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;validation_report.md&lt;/strong&gt; contains per-check PASS/FAIL results from schema, JSON Schema contract, and distribution validation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;duplicate_analysis.md&lt;/strong&gt; contains the 3-layer deduplication results with examples of detected duplicates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;coverage_report.md&lt;/strong&gt; contains tool, domain, and category coverage matrices with representation analysis.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;remediation_report.md&lt;/strong&gt; logs gap identification and supplemental generation if any gaps were found.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;audit_report.md&lt;/strong&gt; contains the 8-dimensional quality score with weighted overall score and rationale.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;governance.md&lt;/strong&gt; documents dataset lineage, assumptions, limitations, versioning, and release process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;release_notes.md&lt;/strong&gt; contains semantic versioning release notes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;dataset_card.md&lt;/strong&gt; is the dataset card in HuggingFace-style format.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;generation_methodology.md&lt;/strong&gt; contains the full methodology for reproducibility.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dataset Record Schema&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "id": "COD_001",
  "category": "coding",
  "difficulty": "medium",
  "user_query": "Implement a function that validates JSON schema compliance...",
  "ground_truth_plan": [
    "Parse the input JSON string into a Python dictionary",
    "Load the JSON Schema definition from the provided schema file",
    "Validate the dictionary against the schema using the jsonschema library",
    "Collect all validation errors with paths and messages",
    "Return the validation result with pass/fail status and error details"
  ],
  "expected_tools": [
    "code_editor",
    "linter",
    "test_runner",
    "static_analyzer"
  ],
  "evaluation_criteria": [
    "Correctly validates all schemas and reports errors",
    "Handles edge cases (empty objects, nested schemas, $ref)",
    "Tests cover at least 90% of code paths"
  ],
  "success_conditions": [
    "All unit tests pass with &amp;gt;90% code coverage",
    "Code passes linting with zero errors or warnings"
  ],
  "metadata": {
    "domains": ["backend_services", "data_structures"],
    "requires_external_access": false,
    "estimated_steps": 7,
    "tags": ["intermediate", "cross_domain", "independent_steps"]
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The metadata block always contains domains (list), requires_external_access (bool), estimated_steps (int), and tags (list).&lt;/p&gt;

&lt;h2&gt;
  
  
  Quality Report
&lt;/h2&gt;

&lt;p&gt;Produced from seed=42, 1,000 records:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvz9digiekziruqev7r5s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvz9digiekziruqev7r5s.png" alt=" " width="800" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Audit Score Breakdown
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faziqxeliri3isik079bo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faziqxeliri3isik079bo.png" alt=" " width="424" height="379"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Extending the Factory
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Adding a New Category&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Drop a new pack file into &lt;code&gt;categories/&lt;/code&gt;, validate, and run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# 1. Create categories/&amp;lt;name&amp;gt;.yaml
# 2. Preflight the config + packs
python3 dataset_factory.py --validate-config
# 3. Run
python3 dataset_factory.py --seed 42
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Adding a New Tool
&lt;/h2&gt;

&lt;p&gt;Edit the relevant category pack and add the tool to its tools list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# categories/coding.yaml
tools:
  - code_editor
  - linter
  - test_runner
  - my_new_tool   # ← Add it here
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then re-run &lt;code&gt;python3 dataset_factory.py --validate-config&lt;/code&gt; and the pipeline.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating a Custom Pipeline&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Import the factory modules directly in Python (see Programmatic API above).&lt;/p&gt;

&lt;h2&gt;
  
  
  Reproducibility
&lt;/h2&gt;

&lt;p&gt;To reproduce the exact same dataset:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 dataset_factory.py --seed 42 --count 1000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;--seed&lt;/code&gt; flag propagates to every stochastic component:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftscuz4mkmjwacsdwj2jd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftscuz4mkmjwacsdwj2jd.png" alt=" " width="637" height="230"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Full methodology is documented in &lt;code&gt;artifacts/generation_methodology.md&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Governance and Maintenance
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Versioning&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Semantic versioning (MAJOR.MINOR.PATCH):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5mip0zppbx6x29vscx9h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5mip0zppbx6x29vscx9h.png" alt=" " width="515" height="157"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Release Process&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run the config preflight: &lt;code&gt;python3 dataset_factory.py --validate-config&lt;/code&gt; → PASS&lt;/li&gt;
&lt;li&gt;Run the full pipeline&lt;/li&gt;
&lt;li&gt;Verify: &lt;code&gt;python3 verification.py&lt;/code&gt; → 6/6 PASS&lt;/li&gt;
&lt;li&gt;Check audit score ≥ 90 (EXCELLENT)&lt;/li&gt;
&lt;li&gt;Review &lt;code&gt;release_notes.md&lt;/code&gt; for accuracy&lt;/li&gt;
&lt;li&gt;Tag release in version control&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Known Limitations&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Documented in &lt;code&gt;artifacts/governance.md&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Synthetic queries: All queries are generated from templates, not collected from real users&lt;/li&gt;
&lt;li&gt;Template bias: Domain/tool distributions reflect template structure&lt;/li&gt;
&lt;li&gt;Difficulty calibration: Based on step count ranges, not human evaluation&lt;/li&gt;
&lt;li&gt;No ground-truth execution: Plans are text-based and not executable&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Extending for a New Version&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# 1. Add/edit category packs in categories/ and/or globals in config.yaml
# 2. Preflight the config + packs
python3 dataset_factory.py --validate-config
# 3. Regenerate
python3 dataset_factory.py --seed 42 --count 1000
# 4. Verify
python3 verification.py
# 5. Check audit score ≥ 90
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a production-grade benchmark dataset factory that could generate, validate, deduplicate, audit, and release high-quality evaluation datasets for AI agents with a single command. NEO planned and produced the files in this repository: the main orchestrator, an independent verification script, 14 factory modules covering generation, validation, deduplication, coverage analysis, remediation, auditing, and governance, the canonical record schema, the global config, all 10 category pack files, the test suite, and the CI workflows. The plans/ directory in the repo documents the build run directly.&lt;/p&gt;

&lt;p&gt;The result is a fully working 8-phase pipeline that produces a 1,000-record benchmark dataset with a 94.94/100 audit score, 100% tool and domain coverage, zero duplicates, and 6/6 independent verification checks passed.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Extend This Further With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use it as the evaluation layer in a CI/CD pipeline for AI agents.&lt;/strong&gt;&lt;br&gt;
The factory outputs &lt;code&gt;dataset.jsonl&lt;/code&gt; and &lt;code&gt;verification.py&lt;/code&gt; exits 0 only when 6/6 checks pass. That exit code becomes a CI gate: if the benchmark does not meet quality thresholds, the pipeline fails before the agent is evaluated against bad data. Plugging &lt;code&gt;python3 dataset_factory.py --seed 42&lt;/code&gt; and &lt;code&gt;python3 verification.py&lt;/code&gt; as pipeline steps gives every agent deployment a reproducible, audited evaluation layer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use &lt;code&gt;--skip-generation&lt;/code&gt; to re-audit a dataset after agents modify or filter it.&lt;/strong&gt;&lt;br&gt;
If a downstream team removes records, rebalances difficulty, or adds domain-specific records to &lt;code&gt;dataset.jsonl&lt;/code&gt;, running with &lt;code&gt;--skip-generation&lt;/code&gt; re-runs all validation, coverage analysis, deduplication, and auditing against the modified file without regenerating. The audit score immediately shows whether the changes degraded data quality across any of the 8 dimensions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use the programmatic API to build a custom evaluation loop.&lt;/strong&gt;&lt;br&gt;
Every factory module is independently importable. &lt;code&gt;DatasetGenerator&lt;/code&gt;, &lt;code&gt;validate_dataset&lt;/code&gt;, &lt;code&gt;DatasetDeduplicator&lt;/code&gt;, and &lt;code&gt;audit_dataset&lt;/code&gt; can be imported directly into an agent testing script, generating a fresh benchmark for each experiment and feeding records to the agent under test, all in one Python process without touching the CLI or the filesystem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use a custom category pack to benchmark agents against your own task taxonomy.&lt;/strong&gt;&lt;br&gt;
If the 10 built-in categories do not match the agent's actual workload, a custom &lt;code&gt;categories/&amp;lt;name&amp;gt;.yaml&lt;/code&gt; with domain-specific tasks, tools, and query templates can be dropped in. The factory runs the custom benchmark through the same 8-phase pipeline the built-in categories go through, including deduplication, 100% coverage validation, and governance document generation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Most benchmark datasets are generated once, checked loosely, and never audited again. The Dataset Factory treats dataset quality the same way production software treats code quality: every run is validated, every gap is remediated, every dimension is scored, and the result is independently verified before it is considered production-ready.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/DataSet-Factory" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/DataSet-Factory&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>agents</category>
      <category>llm</category>
      <category>mlops</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Harness Template Library: 10 Production-Grade AI Agent Templates with 15 Shared Infrastructure Modules</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Mon, 06 Jul 2026 07:00:08 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/harness-template-library-10-production-grade-ai-agent-templates-with-15-shared-infrastructure-2k27</link>
      <guid>https://dev.to/nilofer_tweets/harness-template-library-10-production-grade-ai-agent-templates-with-15-shared-infrastructure-2k27</guid>
      <description>&lt;p&gt;Building an AI agent prototype is straightforward. Making it reliable in production is not. Rate limits must be retried with backoff. Context windows fill up and must be pruned carefully. Tool calls need permission checks before execution. Financial operations need a human to confirm before money moves. Failures mid-task need to checkpoint so work is not lost. Usage costs need to be tracked per session with hard limits.&lt;/p&gt;

&lt;p&gt;Harness Template Library solves all of that. It is a production-grade open-source library of 10 AI agent harness templates, each a complete, runnable Python package that wires together 15 battle-tested infrastructure modules. Ready to deploy on day one. Built autonomously using NEO.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyn8sj7rvf2hyrv9qkbzn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyn8sj7rvf2hyrv9qkbzn.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What This Library Does
&lt;/h2&gt;

&lt;p&gt;The 15 core modules handle every infrastructure concern an agent needs in production: context management, memory, tool permissions, budget tracking, observability, state persistence, human approval, and more. The 10 templates provide domain-specific tools, system prompts, and workflow configurations on top of that shared infrastructure. Every template runs with claude-sonnet-4-20250514 out of the box.&lt;/p&gt;

&lt;p&gt;The split is deliberate. The 15 infrastructure modules are written once and shared. Each template only provides its domain-specific tools, system prompt, and configuration. Improvements to any core module benefit all 10 templates instantly.&lt;/p&gt;
&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;

&lt;p&gt;The 15 core modules all live in &lt;code&gt;core/&lt;/code&gt;. Each template's &lt;code&gt;harness.py&lt;/code&gt; instantiates and wires them together with domain-specific configuration. The templates differ in their tools, system prompts, workflow steps, and permission policies, not in their infrastructure.&lt;/p&gt;
&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Python 3.11 or newer&lt;/li&gt;
&lt;li&gt;An Anthropic API key: &lt;code&gt;export ANTHROPIC_API_KEY=sk-ant-your-key-here&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Install&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd &lt;/span&gt;projects/harness-template-library
pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-e&lt;/span&gt; &lt;span class="s2"&gt;".[dev]"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This installs the library and registers all 10 CLI entry points. Set your API key:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;export &lt;/span&gt;&lt;span class="nv"&gt;ANTHROPIC_API_KEY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;sk-ant-your-key-here
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Run a Template via CLI&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Each template registers its own CLI command. For example, the coding agent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;coding-agent "Write a Python function that checks if a string is a palindrome"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or the research agent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;research-agent "Summarize the key architectural differences between GPT-4 and Claude"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All 10 CLIs work the same way: pass a task or query as the first argument, and the agent runs it using the full 15-module infrastructure stack.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run an Example Script&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python &lt;span class="nt"&gt;-m&lt;/span&gt; examples.run_coding_agent
python &lt;span class="nt"&gt;-m&lt;/span&gt; examples.run_research_agent
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Run Tests&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python &lt;span class="nt"&gt;-m&lt;/span&gt; pytest tests/ &lt;span class="nt"&gt;-v&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;78 tests across all 15 core modules. Runs in under 5 seconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  The 15 Core Modules
&lt;/h2&gt;

&lt;p&gt;All 15 modules live in &lt;code&gt;core/&lt;/code&gt; and are real, working Python classes with no stubs and no placeholders.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;InstructionManager:&lt;/strong&gt; Loads system prompts from file or env, supports {variable} interpolation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ContextBuilder:&lt;/strong&gt; Assembles the messages array, enforces token budget with intelligent truncation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MemoryLayer:&lt;/strong&gt; SQLite-backed persistent memory with keyword search across past sessions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ModelAdapter:&lt;/strong&gt; Wraps AsyncAnthropic, uses claude-sonnet-4-20250514, retries on rate limits with exponential backoff.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ToolRegistry:&lt;/strong&gt; Register tools by name with their JSON schema and Python handler function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PermissionResolver:&lt;/strong&gt; Checks tool calls against an allowlist policy before execution; supports wildcards.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BudgetManager:&lt;/strong&gt; Tracks token usage and cost per session; raises BudgetExceededError at hard limit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WorkflowEngine:&lt;/strong&gt; Runs a sequence of named steps with conditional branching based on step results.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;StateManager:&lt;/strong&gt; Serializes and restores full agent state to SQLite, for resuming interrupted tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HumanApprovalLayer:&lt;/strong&gt; Pauses on sensitive or financial tools and prompts the operator for confirmation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ObservabilityLayer:&lt;/strong&gt; Emits structured logs via structlog and OTEL spans for every tool and model call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;EvaluationFramework:&lt;/strong&gt; Scores agent output against a rubric using a second Claude call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RetryRecoverySystem:&lt;/strong&gt; Exponential backoff wrapper that saves partial results to disk before re-raising.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AuditLogger:&lt;/strong&gt; Append-only SQLite log of every action, decision, and tool call, non-repudiable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DeploymentConfig:&lt;/strong&gt; Generates Dockerfiles and docker-compose.yml programmatically for any template.&lt;/p&gt;

&lt;h2&gt;
  
  
  The 10 Templates
&lt;/h2&gt;

&lt;p&gt;Each template is in &lt;code&gt;templates/&amp;lt;name&amp;gt;/&lt;/code&gt; with &lt;code&gt;harness.py&lt;/code&gt;, &lt;code&gt;tools.py&lt;/code&gt;, &lt;code&gt;config.py&lt;/code&gt;, &lt;code&gt;system_prompt.txt&lt;/code&gt;, &lt;code&gt;Dockerfile&lt;/code&gt;, &lt;code&gt;docker-compose.yml&lt;/code&gt;, and &lt;code&gt;tests/test_harness.py&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Coding Agent:&lt;/strong&gt; Reads and writes files, runs tests, diffs git changes, and searches code. Workflow: understand task, write code, run tests, fix failures, commit. System prompt: expert software engineer with TDD focus.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Research Agent:&lt;/strong&gt; Handles web search, URL reading, note saving, and citation management, with web and URL tools currently implemented as stubs. Workflow: decompose question, search, synthesize, verify claims, write report. System prompt: rigorous researcher with citation requirements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Customer Support:&lt;/strong&gt; Handles ticket lookup, update, escalation, and knowledge base search, with email sending currently implemented as a stub. Workflow: understand issue, check KB, resolve or escalate, update ticket. System prompt: empathetic support agent with escalation rules.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Engineering:&lt;/strong&gt; Handles SQLite queries, schema reading, data validation, and pipeline execution. Workflow: understand data need, query, validate, transform, output. System prompt: data engineer focused on data quality and lineage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Browser Automation:&lt;/strong&gt; Handles navigation, clicking, text extraction, screenshots, and form filling, with all browser tools currently implemented as stubs awaiting browser integration. Workflow: understand goal, plan steps, execute, verify, report. System prompt: precise automation agent that validates each step.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Multi-Agent Orchestrator:&lt;/strong&gt; Spawns and coordinates subagents, sends messages, collects results, and merges outputs. Workflow: decompose task, assign to subagents, collect results, synthesize. System prompt: orchestrator that breaks complex tasks into parallel workstreams.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RAG Agent:&lt;/strong&gt; Embeds queries, runs cosine similarity search over an in-memory vector store, reranks results, and cites passages. Workflow: query, retrieve, rerank, generate answer with citations. System prompt: knowledge retrieval agent that only answers from provided context.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Finance Operations:&lt;/strong&gt; Handles balance checks, invoice creation, and payment processing, with all financial tools currently implemented as stubs, plus a full audit trail. HumanApprovalLayer is always required before any financial tool executes. Workflow: validate request, check permissions, execute with approval, audit. System prompt: finance agent with mandatory human approval for all transactions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Document Analysis:&lt;/strong&gt; Handles text extraction, document classification, entity extraction, summarization, and document comparison. Workflow: ingest, classify, extract, analyze, report. System prompt: document analyst focused on structured information extraction.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Long-Horizon Task:&lt;/strong&gt; Handles checkpointing, checkpoint restoration, todo list management, and progress tracking. Workflow: plan, checkpoint, execute step, checkpoint, repeat. System prompt: methodical agent that checkpoints frequently and resumes gracefully.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;harness-template-library/
├── pyproject.toml                          # Package + 10 CLI entry points
├── core/
│   ├── __init__.py
│   ├── instruction_manager.py
│   ├── context_builder.py
│   ├── memory_layer.py
│   ├── model_adapter.py                    # claude-sonnet-4-20250514 default
│   ├── tool_registry.py
│   ├── permission_resolver.py
│   ├── budget_manager.py                   # raises BudgetExceededError
│   ├── workflow_engine.py
│   ├── state_manager.py
│   ├── human_approval_layer.py
│   ├── observability_layer.py
│   ├── evaluation_framework.py
│   ├── retry_recovery_system.py
│   ├── audit_logger.py
│   └── deployment_config.py
├── templates/
│   ├── coding_agent/
│   │   ├── harness.py                      # Wires all 15 core modules
│   │   ├── tools.py                        # read_file, write_file, run_tests, git_diff, search_code
│   │   ├── config.py
│   │   ├── system_prompt.txt
│   │   ├── Dockerfile
│   │   ├── docker-compose.yml
│   │   └── tests/test_harness.py
│   ├── research_agent/                     # Same structure, different tools + prompt
│   ├── customer_support/
│   ├── data_engineering/
│   ├── browser_automation/
│   ├── multi_agent_orchestrator/
│   ├── rag_agent/
│   ├── finance_operations/
│   ├── document_analysis/
│   └── long_horizon_task/
├── harness_template_library/
│   └── cli/
│       ├── coding_agent_cli.py             # click CLI → CodingAgentHarness
│       ├── research_agent_cli.py
│       └── ...                             # 8 more CLI modules
├── examples/
│   ├── run_coding_agent.py
│   └── run_research_agent.py
└── tests/
    ├── conftest.py                         # Fixtures: mock Anthropic, temp SQLite, sample config
    └── test_core_modules.py               # 75 tests covering all 15 core modules
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Design Decisions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Shared core, specialized templates.&lt;/strong&gt; &lt;br&gt;
All 15 infrastructure modules are written once and shared. Each template only provides its domain-specific tools, system prompt, and configuration. Improvements to, say, the RetryRecoverySystem benefit all 10 templates instantly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SQLite everywhere.&lt;/strong&gt; &lt;br&gt;
Memory, state persistence, and audit logs all use SQLite via aiosqlite. No external services are required to run any template. This makes the library work in air-gapped environments, local development, and ephemeral CI environments without any setup.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HumanApprovalLayer as a hard gate.&lt;/strong&gt; &lt;br&gt;
The PermissionResolver checks allowlists before a tool runs, but HumanApprovalLayer is a separate, upstream gate that can be configured per-tool. For the finance template, every payment-related tool requires approval regardless of the permission policy. The two layers are deliberately separate so the audit log shows both the policy check and the human decision.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BudgetExceededError is synchronous.&lt;/strong&gt; &lt;br&gt;
Even though the rest of the library is async, &lt;code&gt;BudgetManager.check_budget()&lt;/code&gt; raises BudgetExceededError synchronously. This keeps budget enforcement simple: any caller that does not catch it will propagate up, ensuring no tool call or model call can exceed the limit by accident.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;EvaluationFramework uses a second Claude call.&lt;/strong&gt; &lt;br&gt;
Agent output scoring runs a separate Anthropic API call with a rubric-based prompt. This adds latency and cost, so it is opt-in per template rather than always-on. The coding agent uses it to score whether generated code is idiomatic and well-tested.&lt;/p&gt;
&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;Each template reads its configuration from environment variables using pydantic-settings. Create a &lt;code&gt;.env&lt;/code&gt; file in the project root:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="py"&gt;ANTHROPIC_API_KEY&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;sk-ant-your-key-here&lt;/span&gt;
&lt;span class="py"&gt;MODEL&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;claude-sonnet-4-20250514&lt;/span&gt;
&lt;span class="py"&gt;MAX_TOKENS&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;4096&lt;/span&gt;
&lt;span class="py"&gt;BUDGET_LIMIT_USD&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;1.00&lt;/span&gt;
&lt;span class="py"&gt;LOG_LEVEL&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;INFO&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All config values have sensible defaults. Only &lt;code&gt;ANTHROPIC_API_KEY&lt;/code&gt; is required to run.&lt;/p&gt;

&lt;h2&gt;
  
  
  Docker Deployment
&lt;/h2&gt;

&lt;p&gt;Each template includes a &lt;code&gt;Dockerfile&lt;/code&gt; and &lt;code&gt;docker-compose.yml&lt;/code&gt;. To run the coding agent in Docker:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd &lt;/span&gt;templates/coding_agent
docker compose up &lt;span class="nt"&gt;--build&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or generate a custom deployment config programmatically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;core.deployment_config&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;DeploymentConfig&lt;/span&gt;

&lt;span class="n"&gt;dc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;DeploymentConfig&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;service_name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;my-coding-agent&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;dockerfile&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate_dockerfile&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;compose&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate_compose&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Environment Variables
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fuloqm5w9snohymrlknso.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fuloqm5w9snohymrlknso.png" alt=" " width="719" height="347"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Verified Results
&lt;/h2&gt;

&lt;p&gt;The library ships with 78 tests across all 15 core modules including BudgetManager, WorkflowEngine, HumanApprovalLayer, RetryRecoverySystem, ObservabilityLayer, and the rest. The package installs cleanly with &lt;code&gt;pip install -e&lt;/code&gt; . and all public classes import without errors. Tests run in under 5 seconds.&lt;/p&gt;

&lt;p&gt;AI template generation (DeepSeek V4 Flash via OpenRouter): The ModelAdapter auto-detects the OpenRouter key and routes calls through DeepSeek's 1M-context reasoning model at the correct endpoint. When asked to generate a retry decorator with exponential backoff for async Python functions, it returned a complete, production-ready implementation in 311 output tokens: a parameterized &lt;code&gt;retry_async&lt;/code&gt; decorator accepting &lt;code&gt;max_retries&lt;/code&gt;, &lt;code&gt;base_delay&lt;/code&gt;, &lt;code&gt;max_delay&lt;/code&gt;, and a tuple of exception types, with backoff capped at &lt;code&gt;max_delay&lt;/code&gt; and the original function signature preserved via &lt;code&gt;functools.wraps&lt;/code&gt;. The adapter handles DeepSeek thinking blocks transparently, returning only the final text content. Total cost at $0.10/M input tokens was under $0.001.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a library of production-grade agent harness templates that wire together all the infrastructure concerns a real agent needs, so teams could skip the boilerplate and start from a complete, working architecture. NEO planned and produced the files in this repository: 15 core infrastructure modules, 10 complete agent templates each with its own harness, tools, configuration, system prompt, Docker setup, and test suite, 10 CLI entry points, two example scripts, and the full test suite with fixtures and module coverage. The result is a fully working library where picking a template and running one CLI command gives a complete, production-grade agent with all 15 infrastructure concerns pre-wired and no boilerplate left to write.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Pick a template and run a production-ready agent immediately.&lt;/strong&gt; &lt;br&gt;
All 10 templates register their own CLI entry points on install. Passing a task to &lt;code&gt;coding-agent&lt;/code&gt;, &lt;code&gt;research-agent&lt;/code&gt;, or any of the other eight commands runs the full 15-module infrastructure stack without writing any code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use the 15 core modules in your own agent.&lt;/strong&gt; &lt;br&gt;
Every module is a real, importable Python class. Any agent codebase can pull in &lt;code&gt;ContextBuilder&lt;/code&gt;, &lt;code&gt;BudgetManager&lt;/code&gt;, &lt;code&gt;HumanApprovalLayer&lt;/code&gt;, or any other module independently and wire them into an existing architecture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deploy any template to Docker in one command.&lt;/strong&gt; &lt;br&gt;
Every template ships with a &lt;code&gt;Dockerfile&lt;/code&gt; and &lt;code&gt;docker-compose.yml&lt;/code&gt;. Running &lt;code&gt;docker compose up --build&lt;/code&gt; inside any template directory produces a containerized, ready-to-run agent with no additional configuration beyond the API key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run the library in air-gapped or local environments.&lt;/strong&gt; &lt;br&gt;
Memory, state persistence, and audit logs all use SQLite via aiosqlite. No external services are required. The library runs in CI, local development, or any environment where installing dependencies from a remote service is not possible.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Most agent projects rebuild the same infrastructure from scratch every time: retry logic, context pruning, permission checks, budget limits, audit trails. This library solves that once across 10 use cases. Pick the template that matches the job, or take the 15 core modules and wire them into whatever architecture is already in place.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/Harness-Template-Library" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/Harness-Template-Library&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>llm</category>
      <category>opensource</category>
      <category>agents</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>NEO Data Quality Auditor AI: Automated Data Quality Auditing, Bias Detection, and Lineage Tracking</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Fri, 03 Jul 2026 13:30:36 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/neo-data-quality-auditor-ai-automated-data-quality-auditing-bias-detection-and-lineage-tracking-5214</link>
      <guid>https://dev.to/nilofer_tweets/neo-data-quality-auditor-ai-automated-data-quality-auditing-bias-detection-and-lineage-tracking-5214</guid>
      <description>&lt;p&gt;60% of businesses cite poor data quality as the primary reason for AI failures. Dirty data leads to misleading insights, wasted resources, and failed ML models. Most teams lack easy-to-use tooling that surfaces what is wrong and what to do about it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NEO Data Quality Auditor AI&lt;/strong&gt; addresses that directly. It is an automated data quality auditing tool that detects inconsistencies, bias, missing values, and format issues in any CSV dataset, with a real-time monitoring dashboard, AI-powered cleaning suggestions, and data lineage tracking. Built autonomously by NEO.&lt;/p&gt;

&lt;h2&gt;
  
  
  Visual Reports
&lt;/h2&gt;

&lt;p&gt;The repo ships with four SVG infographics: a data quality score gauge, a bias detection overview, a gender and age bias analysis, and an ethnicity bias breakdown.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxntssw28josfwn6fqep7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxntssw28josfwn6fqep7.png" alt=" " width="590" height="513"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What It Does
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;9 Quality Checks:&lt;/strong&gt; Missing values, duplicates, data types, out-of-range, format violations, outliers, cardinality, cross-column consistency, distribution skew.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AI Cleaning Suggestions:&lt;/strong&gt; A rule-based engine maps every detected issue to actionable steps with severity, effort level, and category. Each suggestion is filterable and expandable in the dashboard.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bias Detection:&lt;/strong&gt; Demographic parity ratio, disparate impact, and group fairness metrics across sensitive attributes. Results surface per-group statistics with representation rates and standard errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Lineage:&lt;/strong&gt; An event-sourced audit trail tracks every analysis step with timestamps and column-level changes, exportable as JSON.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Time Dashboard:&lt;/strong&gt; An interactive Streamlit UI with a quality score gauge (0-100), drill-downs per check, and exportable reports.&lt;/p&gt;

&lt;h2&gt;
  
  
  The 9 Quality Checks
&lt;/h2&gt;

&lt;p&gt;The 9 checks cover the most common classes of data quality problems.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Missing Values:&lt;/strong&gt; Null/NaN counts and ratios per column with critical vs warning thresholds. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Duplicate Rows:&lt;/strong&gt; Exact duplicate records with sample indices. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Type Inconsistencies:&lt;/strong&gt; Mixed types within a column, for example strings in numeric columns. &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Out-of-Range Values:&lt;/strong&gt; Values outside expected min/max bounds. &lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Format/Pattern Violations:&lt;/strong&gt; Invalid emails, phone numbers, and dates using regex patterns.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Outlier Detection:&lt;/strong&gt; IQR method and Z-score analysis for numerical anomalies. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Uniqueness/Cardinality:&lt;/strong&gt; High vs low cardinality detection. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cross-Column Consistency:&lt;/strong&gt; Logical contradictions between related columns. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Skewness/Kurtosis:&lt;/strong&gt; Distribution shape analysis for numeric columns.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Bias Detection Metrics
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1o9bswif8p8ondiao5ay.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1o9bswif8p8ondiao5ay.png" alt=" " width="799" height="213"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Data Lineage
&lt;/h2&gt;

&lt;p&gt;The lineage tracker logs every analysis step:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Load events: Original row count, column list, source filename&lt;/li&gt;
&lt;li&gt;Quality check events: Per-check results with affected columns&lt;/li&gt;
&lt;li&gt;Bias check events: Per-attribute bias metrics&lt;/li&gt;
&lt;li&gt;Export: Download the full audit trail as JSON&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Clone or navigate to the project&lt;/span&gt;
&lt;span class="nb"&gt;cd &lt;/span&gt;NEO-Data-Quality-Auditor-AI

&lt;span class="c"&gt;# Create a virtual environment&lt;/span&gt;
python &lt;span class="nt"&gt;-m&lt;/span&gt; venv venv
&lt;span class="nb"&gt;source &lt;/span&gt;venv/bin/activate  &lt;span class="c"&gt;# Linux/Mac&lt;/span&gt;
&lt;span class="c"&gt;# venv\Scripts\activate   # Windows&lt;/span&gt;

&lt;span class="c"&gt;# Install dependencies&lt;/span&gt;
pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-r&lt;/span&gt; requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Usage
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Start the Dashboard&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;source &lt;/span&gt;venv/bin/activate
streamlit run app.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This opens a web browser with the interactive dashboard.&lt;/p&gt;

&lt;h2&gt;
  
  
  Walkthrough
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Upload a CSV:&lt;/strong&gt; Use the sidebar to upload any CSV file, or click "Use Demo Data" to load a pre-built dataset with intentional quality issues (missing values, outliers, format violations, demographic bias).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview Tab:&lt;/strong&gt; See the overall data quality score (0-100), pass/fail breakdown per check, and summary metrics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quality Checks Tab:&lt;/strong&gt; Drill into each of the 9 checks with interactive visualizations (bar charts for missing values, box plots for outliers, histograms for distributions).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bias Report Tab:&lt;/strong&gt; Review demographic parity ratios and disparate impact metrics across sensitive attributes like gender, ethnicity, and age.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lineage Tab:&lt;/strong&gt; View the full audit trail of every analysis step with timestamps and event type breakdown.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AI Suggestions Tab:&lt;/strong&gt; Get actionable cleaning recommendations filtered by severity and effort level, with step-by-step instructions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Command-Line Usage&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The modules are also importable programmatically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;pandas&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;auditor.quality_checks&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;run_all_quality_checks&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;calculate_quality_score&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;auditor.bias_detector&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;run_all_bias_checks&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;auditor.ai_suggestions&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;generate_suggestions&lt;/span&gt;

&lt;span class="c1"&gt;# Load data
&lt;/span&gt;&lt;span class="n"&gt;df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_csv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;your_data.csv&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Run all 9 quality checks
&lt;/span&gt;&lt;span class="n"&gt;results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;run_all_quality_checks&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;calculate_quality_score&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Quality Score: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;score&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Run bias detection
&lt;/span&gt;&lt;span class="n"&gt;bias_results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;run_all_bias_checks&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Bias checks run: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;bias_results&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Get cleaning suggestions
&lt;/span&gt;&lt;span class="n"&gt;suggestions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;generate_suggestions&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bias_results&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;suggestions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;[&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;severity&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;] &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;issue&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; — Effort: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;effort&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;NEO-Data-Quality-Auditor-AI/
├── app.py                      # Streamlit dashboard (main entry point)
├── config.py                   # Thresholds and configuration
├── requirements.txt            # Python dependencies
├── docs/                       # SVG infographics
│   ├── quality_score.svg       # Data quality gauge (43/100)
│   ├── bias_overview.svg       # Bias detection overview
│   ├── gender_age_bias.svg     # Gender &amp;amp; age bias analysis
│   └── ethnicity_bias.svg      # Ethnicity bias details
├── auditor/
│   ├── __init__.py             # Package exports
│   ├── quality_checks.py       # 9 quality check functions
│   ├── bias_detector.py        # Demographic parity, disparate impact, fairness
│   ├── lineage_tracker.py      # Event-sourced data lineage tracker
│   ├── ai_suggestions.py       # Rule-based cleaning suggestion engine
│   └── demo_data.py            # Demo data generator with intentional issues
├── data/
│   └── demo_data.csv           # Generated demo dataset
└── README.md
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Running Tests
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;source &lt;/span&gt;venv/bin/activate
python &lt;span class="nt"&gt;-c&lt;/span&gt; &lt;span class="s2"&gt;"
from auditor.quality_checks import run_all_quality_checks, calculate_quality_score
from auditor.bias_detector import run_all_bias_checks
from auditor.ai_suggestions import generate_suggestions
import pandas as pd

# Generate and test with demo data
from auditor.demo_data import generate_demo_data
generate_demo_data()
df = pd.read_csv('data/demo_data.csv')

# Run full audit
quality = run_all_quality_checks(df)
score = calculate_quality_score(quality)
bias = run_all_bias_checks(df)
suggestions = generate_suggestions(quality, bias)

print(f'Quality Score: {score}')
print(f'Bias checks: {len(bias)}')
print(f'Suggestions: {len(suggestions)}')
"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Dashboard Screenshots
&lt;/h2&gt;

&lt;p&gt;Launch the dashboard with &lt;code&gt;streamlit run app.py&lt;/code&gt; to see it live.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Overview:&lt;/strong&gt; Quality score gauge (0-100), check pass/fail bar chart, summary metrics&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Quality Checks:&lt;/strong&gt; Per-check drill-down with interactive Plotly visualizations&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Bias Report:&lt;/strong&gt; Demographic parity ratio charts, group fairness breakdown&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lineage:&lt;/strong&gt; Event timeline with event type distribution pie chart&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;AI Suggestions:&lt;/strong&gt; Expandable suggestion cards with severity filters and effort labels&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;Edit &lt;code&gt;config.py&lt;/code&gt; to tune:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;QUALITY_THRESHOLDS&lt;/code&gt;: Missing value thresholds, outlier Z-score cutoff, email/phone regex patterns&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;BIAS_PARAMS&lt;/code&gt;: Demographic parity range, min group size, sensitive column keywords&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;DASHBOARD_CONFIG&lt;/code&gt;: App title, colors, max file size&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a data quality auditing platform that could detect inconsistencies, bias, and format issues in any CSV dataset and surface actionable cleaning recommendations through an interactive dashboard. NEO planned and produced the files in this repository: the Streamlit dashboard in &lt;code&gt;app.py&lt;/code&gt;, the threshold configuration in &lt;code&gt;config.py&lt;/code&gt;, five auditor modules covering quality checks, bias detection, lineage tracking, AI suggestions, and demo data generation, four SVG infographics under &lt;code&gt;docs/&lt;/code&gt;, and the demo dataset in &lt;code&gt;data/demo_data.csv&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The result is a fully working auditing platform that takes any CSV file in and returns a quality score across 9 checks, bias metrics across sensitive attributes, a complete event-sourced lineage trail, and prioritized cleaning suggestions, all from a single &lt;code&gt;streamlit run app.py&lt;/code&gt; command.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Audit any CSV dataset before feeding it into an ML model.&lt;/strong&gt; &lt;br&gt;
Any CSV file can be uploaded directly to the dashboard and the platform runs all 9 quality checks, returning a quality score (0-100) with a pass/fail breakdown per check and interactive drill-downs. No configuration is required before the first run.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Detect demographic bias before training.&lt;/strong&gt; &lt;br&gt;
The &lt;code&gt;bias_detector.py&lt;/code&gt; module computes demographic parity ratio, disparate impact, and group fairness metrics across sensitive attributes like gender, ethnicity, and age. Running this before training surfaces skewed representation that would otherwise propagate silently into model predictions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Integrate quality checks programmatically into a data pipeline.&lt;/strong&gt; &lt;code&gt;run_all_quality_checks()&lt;/code&gt;, &lt;code&gt;run_all_bias_checks()&lt;/code&gt;, and &lt;code&gt;generate_suggestions()&lt;/code&gt; are all importable directly, as shown in the command-line usage section. Any pipeline that can run Python can call these functions and surface quality issues before data reaches the next stage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Export the full lineage trail as JSON for compliance or auditing.&lt;/strong&gt; &lt;br&gt;
The event-sourced lineage tracker logs every analysis step with timestamps and column-level changes. The full audit trail is downloadable as JSON from the Lineage tab, making it usable as a compliance artifact without any additional tooling.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;NEO Data Quality Auditor AI is a single-command auditing platform that takes any CSV file in and surfaces quality issues, bias metrics, cleaning recommendations, and a full lineage trail, all from streamlit run app.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/Data-Quality-Auditor-AI" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/Data-Quality-Auditor-AI&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>machinelearning</category>
      <category>opensource</category>
      <category>mlops</category>
      <category>dataquality</category>
    </item>
    <item>
      <title>Tool Permission Matrix Builder &amp; Validator: Structured, Visual Policy Management for AI Agent Teams</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Thu, 25 Jun 2026 05:41:16 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/tool-permission-matrix-builder-validator-structured-visual-policy-management-for-ai-agent-teams-1efo</link>
      <guid>https://dev.to/nilofer_tweets/tool-permission-matrix-builder-validator-structured-visual-policy-management-for-ai-agent-teams-1efo</guid>
      <description>&lt;p&gt;AI agents in production access tools that range from harmless read-only queries to irreversible destructive operations. Managing which agents can use which tools is a governance problem that most teams solve with ad-hoc scripts and tribal knowledge - and that works until it doesn't. A misconfigured role, an over-exposed tool, or an agent that silently calls something it shouldn't are the kinds of failures that surface in production rather than in review.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tool Permission Matrix Builder &amp;amp; Validator&lt;/strong&gt; replaces that with a structured, visual approach. It is a visual policy management system for AI agent teams - define tools, classify their risk, assign roles, and drag-and-drop permissions onto a matrix, then export machine-readable policy artifacts or validate existing agents for compliance, all powered by Claude claude-sonnet-4-20250514.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fne00gvlbag0c228nhcfg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fne00gvlbag0c228nhcfg.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What This Platform Does
&lt;/h2&gt;

&lt;p&gt;The platform addresses the full lifecycle of agent tool governance in one place.&lt;/p&gt;

&lt;p&gt;It starts with tool registration - each tool is defined and assigned a risk category: read-only, internal-write, external-api, financial, destructive, or administrative. Roles are then created for each agent type - analyst, operator, admin, readonly-bot, or whatever the team's structure requires. The permission matrix takes these two dimensions and lets permissions be assigned by dragging tools onto roles or clicking individual cells to toggle between allowed, denied, and inherited states. The matrix validates in real time: if a role has access to a tool whose risk level exceeds what that role should have, a warning appears immediately.&lt;/p&gt;

&lt;p&gt;Once the matrix is configured, a policy artifact is exported - JSON for machine consumption, YAML for GitOps workflows, or a Python module with a &lt;code&gt;check_permission(role, tool)&lt;/code&gt; function that can be imported directly into agent code. On the validation side, existing agent code can be pasted in and Claude analyzes which tools it actually calls, cross-checks those against the matrix, and produces a security score with sorted recommendations. A separate sprawl analysis detects over-exposure: roles with too many high-risk tools, tools granted to too many roles, and unused grants.&lt;/p&gt;

&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;

&lt;p&gt;The backend is fully async - all 24 routes use &lt;code&gt;async def&lt;/code&gt; with an aiosqlite-backed SQLAlchemy session. This is intentional: the Claude API calls in agent validation and sprawl analysis can take 5–15 seconds, and with a synchronous backend, one validation request would block all other users. With async, many concurrent requests are handled without blocking.&lt;/p&gt;

&lt;p&gt;Both AI services have heuristic fallbacks. If &lt;code&gt;ANTHROPIC_API_KEY&lt;/code&gt; is not set, the agent validator still extracts tool call patterns from code using regex and checks them against the matrix, and the sprawl analyzer still computes numerical sprawl metrics. The Claude path produces richer narrative and nuanced recommendations; the heuristic path still provides actionable data.&lt;/p&gt;

&lt;p&gt;The policy generator produces three output formats from the same matrix data. The Python module output is syntax-verified via &lt;code&gt;py_compile&lt;/code&gt; before being returned, ensuring the downloaded file is always importable. The repo also includes &lt;code&gt;architecture.svg&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Quick Start
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python 3.11 or newer&lt;/li&gt;
&lt;li&gt;Node.js 18 or newer&lt;/li&gt;
&lt;li&gt;An Anthropic API key (optional - Claude features fall back to heuristic analysis without it)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Set up the environment&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cp&lt;/span&gt; .env.example .env
&lt;span class="c"&gt;# Optionally add ANTHROPIC_API_KEY=sk-ant-your-key-here for Claude analysis&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Run the backend&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd &lt;/span&gt;backend
pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-r&lt;/span&gt; requirements.txt
uvicorn main:app &lt;span class="nt"&gt;--reload&lt;/span&gt; &lt;span class="nt"&gt;--host&lt;/span&gt; 0.0.0.0 &lt;span class="nt"&gt;--port&lt;/span&gt; 8000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The API starts at &lt;code&gt;http://localhost:8000&lt;/code&gt;. Swagger UI is available at &lt;code&gt;http://localhost:8000/docs&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run the frontend&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The frontend runs in a separate process:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd &lt;/span&gt;frontend
npm &lt;span class="nb"&gt;install
&lt;/span&gt;npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The UI opens at &lt;code&gt;http://localhost:5173&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run with Docker&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cp&lt;/span&gt; .env.example .env
docker compose up &lt;span class="nt"&gt;--build&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The backend runs on port 8000 with a health check. The frontend serves via nginx on port 80 and waits for the backend health check before starting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Running Tests&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd &lt;/span&gt;backend &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; python &lt;span class="nt"&gt;-m&lt;/span&gt; pytest tests/ &lt;span class="nt"&gt;-v&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;22 tests - policy generation (JSON/YAML/Python), agent validator, heuristic analysis. Runs in under a second.&lt;/p&gt;

&lt;h2&gt;
  
  
  API Reference
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm7ddig7dx30sjjwizuby.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm7ddig7dx30sjjwizuby.png" alt=" " width="649" height="452"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Risk Categories
&lt;/h2&gt;

&lt;p&gt;All six risk categories are implemented as a Python Enum and stored in the database. The permission matrix UI shows these risk colors on every tool badge, and real-time validation warnings fire when a role's allowed risk levels would be exceeded.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyhhxvilfv667lth2b301.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyhhxvilfv667lth2b301.png" alt=" " width="565" height="269"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tool-permission-matrix/
├── backend/
│   ├── main.py                        # FastAPI app, 24 async routes
│   ├── models.py                      # Tool, Role, Permission ORM + RiskCategory Enum
│   ├── schemas.py                     # Pydantic v2 request/response schemas
│   ├── database.py                    # Async SQLite via aiosqlite
│   ├── services/
│   │   ├── policy_generator.py        # JSON, YAML, and Python module export
│   │   ├── agent_validator.py         # Claude + heuristic agent code analysis
│   │   └── sprawl_analyzer.py        # Claude + heuristic sprawl detection
│   ├── requirements.txt
│   ├── Dockerfile.backend
│   └── tests/
│       ├── test_policy_generator.py   # 11 policy generation tests
│       ├── test_validator.py          # 11 validator tests
│       └── fixtures/
│           ├── sample_agent.py        # Realistic agent with tool call patterns
│           └── sample_policy.json     # Realistic permission matrix fixture
├── frontend/
│   ├── src/
│   │   ├── App.tsx                    # Tab layout: Tools/Roles/Matrix/Export/Validate/Sprawl
│   │   ├── stores/
│   │   │   ├── toolStore.ts           # Zustand store for tool state
│   │   │   ├── roleStore.ts           # Zustand store for role state
│   │   │   └── matrixStore.ts         # Zustand store for permission matrix
│   │   ├── components/
│   │   │   ├── ToolRegistry.tsx       # CRUD + filter + JSON import/export
│   │   │   ├── RoleManager.tsx        # CRUD + inheritance + risk levels
│   │   │   ├── PermissionMatrix.tsx   # @dnd-kit DnD grid
│   │   │   ├── PolicyExporter.tsx     # Format selector + download
│   │   │   ├── AgentValidator.tsx     # Paste/upload + results display
│   │   │   └── SprawlAnalysis.tsx     # Sprawl score + issues list
│   │   ├── api/client.ts              # axios-based API client, 20 methods
│   │   └── types/index.ts             # TypeScript interfaces (28 types)
│   ├── Dockerfile.frontend
│   ├── package.json
│   └── vite.config.ts
├── docker-compose.yml
└── .env.example
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The structure maps directly onto the platform's three functional layers. The backend/services/ directory holds the three pieces that do the heavy lifting - policy generation, agent validation, and sprawl analysis - each isolated from the routing layer in main.py. The frontend mirrors this with one component per tab in the UI, with tool state, role state, and matrix state each managed by a dedicated Zustand store.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Design Decisions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Async throughout&lt;/strong&gt; - All backend routes are &lt;code&gt;async def&lt;/code&gt; and the SQLAlchemy session uses aiosqlite. The Claude API calls in agent validation and sprawl analysis can take 5–15 seconds. A synchronous backend would block all other users during that window; the async design handles many concurrent requests without blocking.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Three-state permission model&lt;/strong&gt; - Each matrix cell is ALLOWED, DENIED, or INHERITED - not just a binary toggle. INHERITED means the permission comes from the role's parent role, enabling role hierarchies where a base role defines conservative defaults and derived roles override specific tools.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Heuristic fallback for AI features&lt;/strong&gt; - Claude-powered features are never the only path. The agent validator extracts tool calls using regex patterns that cover the most common calling conventions, then checks them against the matrix. The sprawl analyzer computes over-exposure metrics numerically. The platform is fully usable in restricted environments without an API key; Claude's analysis is an enhancement rather than a dependency.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Policy Python module verification&lt;/strong&gt; - When generating a Python module, &lt;code&gt;py_compile&lt;/code&gt; is called on the output before returning it. A &lt;code&gt;permissions.py&lt;/code&gt; that fails to compile would be worse than no policy at all, so this check runs as a hard gate.&lt;/p&gt;

&lt;h2&gt;
  
  
  Environment Variables
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flu7ngohw65xinuu8xwf0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flu7ngohw65xinuu8xwf0.png" alt=" " width="800" height="299"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Verified Results
&lt;/h2&gt;

&lt;p&gt;The backend ships with 22 tests covering policy generation in all three export formats (JSON, YAML, Python module), agent validator tool-call extraction across standard and use_tool/call_tool calling conventions, heuristic analysis correctness, and edge cases like empty code and missing policy. The frontend builds cleanly to a 277 KB JS bundle across 110 modules with @dnd-kit drag-and-drop and Zustand state management.&lt;/p&gt;

&lt;p&gt;For the AI-powered sprawl analysis, the SprawlAnalyzer was run (using DeepSeek V4 Flash via OpenRouter for this verification pass) against a three-role matrix - admin, developer, viewer - with six tools spanning read, write, and destructive categories. The model returned a sprawl score of 80/100 and surfaced nine issues. Two were critical: the admin role holding both &lt;code&gt;execute_code&lt;/code&gt; and &lt;code&gt;delete_resource&lt;/code&gt;, and the developer role also having &lt;code&gt;execute_code&lt;/code&gt; with no approval gate. The overall analysis named the pattern as excessive concentration of destructive tool access and recommended introducing approval workflows before any destructive operation.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a visual policy management platform where AI agent teams could define tools, classify risk, assign roles, configure permissions on a drag-and-drop matrix, and export machine-readable policy artifacts - with Claude-powered validation and sprawl analysis built in. NEO planned and produced the files in this repository - a fully async FastAPI backend with 24 routes, three backend services handling policy generation, agent validation, and sprawl analysis, a React and TypeScript frontend with a drag-and-drop permission matrix, six UI components, three Zustand stores, and a 22-test suite covering all major paths. The plans/ directory and &lt;code&gt;ORCHESTRATOR_LOG.md&lt;/code&gt; in the repo document that build run directly.&lt;/p&gt;

&lt;p&gt;The result is a fully working policy management platform - from tool registration through risk classification, matrix configuration, policy export, and agent validation - with heuristic fallbacks at every AI-powered step so the platform remains useful with or without an API key.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Govern tool access across an existing AI agent team.&lt;/strong&gt;&lt;br&gt;
Any team running multiple agents with different access levels can register their tools, classify them by the six built-in risk categories, and configure a permission matrix without writing a single line of policy code. The matrix validates in real time as roles and permissions are assigned.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Validate existing agent code against a policy.&lt;/strong&gt; &lt;br&gt;
Agent code can be pasted directly into the platform and the validator extracts which tools it actually calls, cross-checks them against the configured matrix, and returns a security score with specific recommendations. The heuristic path works without an API key; the Claude path produces richer analysis when &lt;code&gt;ANTHROPIC_API_KEY&lt;/code&gt; is set.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Export a &lt;code&gt;check_permission(role, tool)&lt;/code&gt; function directly into agent code.&lt;/strong&gt; &lt;br&gt;
Once the matrix is configured, the Python module export generates a &lt;code&gt;permissions.py&lt;/code&gt; file that is syntax-verified before download and can be imported directly into any agent codebase - no manual policy translation required.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Detect permission sprawl in an existing matrix.&lt;/strong&gt; &lt;br&gt;
The sprawl analysis endpoint scores the matrix for over-exposure - roles with too many high-risk tools, tools granted to too many roles, and unused grants. The heuristic path computes numerical metrics without an API key; the Claude path names specific patterns and recommends remediation when &lt;code&gt;ANTHROPIC_API_KEY&lt;/code&gt; is set.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;The gap between "we think our agents have the right permissions" and "we can prove it and export it as code" is where this platform sits. Tool access in AI agent systems is a governance problem that gets harder as teams scale - more agents, more tools, more roles, and no single source of truth. The Tool Permission Matrix Builder &amp;amp; Validator makes that source of truth visual, exportable, and machine-readable.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/Tool-Permission-Matrix-Builder-Validator" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/Tool-Permission-Matrix-Builder-Validator&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>llm</category>
      <category>agents</category>
      <category>machinelearning</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Context Compaction Visualizer: See Exactly What Your AI Agent Forgot Before It Costs You</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Tue, 23 Jun 2026 06:01:50 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/context-compaction-visualizer-see-exactly-what-your-ai-agent-forgot-before-it-costs-you-1o8n</link>
      <guid>https://dev.to/nilofer_tweets/context-compaction-visualizer-see-exactly-what-your-ai-agent-forgot-before-it-costs-you-1o8n</guid>
      <description>&lt;p&gt;When an AI agent runs for many turns, it eventually hits context limits and must compress or discard earlier messages. This is often invisible, yet critical - lost context can cause the agent to forget constraints, user preferences, or prior decisions. The framework moves on. The agent keeps running. And somewhere in those discarded turns is a security finding, a constraint, a decision that the rest of the session quietly proceeds without.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context Compaction Visualizer&lt;/strong&gt; makes that process visible - not after something breaks, but as an inspectable artifact of every run. It is a visualization platform that helps teams understand how long-running AI agents manage and compress context over time - upload execution traces from LangSmith, OpenTelemetry, AgentOps, or any custom format, and explore exactly which context was retained, compressed, or discarded, and at what cost.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7rfhodv9zuhsjj74y9qs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7rfhodv9zuhsjj74y9qs.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What This Platform Does
&lt;/h2&gt;

&lt;p&gt;The core problem is that compaction happens inside the framework's internals. There is no standard output that tells you which messages survived, which were summarized, and which were dropped - or what any of that cost in tokens. This platform reconstructs that picture from execution traces.&lt;/p&gt;

&lt;p&gt;A trace file is uploaded with a format selected, and the platform rebuilds the full session: every message at every turn, its fate - retained verbatim, summarized, or discarded - and any compaction events that occurred along the way. A D3.js stacked-bar timeline renders token consumption across all turns with color-coded regions for each outcome. A session replay steps through turn by turn, surfacing a diff at the exact point a compaction event fires. Token analytics compute the total cost and compression efficiency of the session. A Claude-powered information loss detector scores the risk of each compaction event and names specifically what may have been lost.&lt;/p&gt;

&lt;p&gt;When two traces are available - two different agents, or the same agent under two different compaction strategies - a comparative view places them side by side to show which preserved more context at lower cost.&lt;/p&gt;

&lt;h2&gt;
  
  
  Quick Start
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python 3.11 or newer&lt;/li&gt;
&lt;li&gt;Node.js 18 or newer&lt;/li&gt;
&lt;li&gt;An Anthropic API key (optional - only the Info Loss Detection feature needs it)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Set up the environment&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cp .env.example .env
# Optionally add ANTHROPIC_API_KEY=sk-ant-your-key-here for info loss detection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Run the backend&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd backend
pip install -r requirements.txt
uvicorn main:app --reload --host 0.0.0.0 --port 8000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The API starts at &lt;code&gt;http://localhost:8000&lt;/code&gt;. Interactive docs are available at &lt;code&gt;http://localhost:8000/docs&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run the frontend&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The frontend runs in a separate process:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd frontend
npm install
npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The UI opens at &lt;code&gt;http://localhost:5173&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Run with Docker&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cp .env.example .env
docker compose up --build
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The backend runs on port 8000, the frontend serves via nginx on port 5173.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Running Tests&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd backend &amp;amp;&amp;amp; python -m pytest tests/ -v
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;29 tests covering all four parsers, edge cases, and the token counter. The full suite runs in under 100ms since nothing in it hits an external service.&lt;/p&gt;

&lt;h2&gt;
  
  
  API Reference
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb38atjal9yo5rgtuptci.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb38atjal9yo5rgtuptci.png" alt=" " width="700" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Supported Trace Formats
&lt;/h2&gt;

&lt;p&gt;The platform accepts four input formats, selectable via a dropdown on upload. Each has its own parser that handles the vendor-specific schema and reduces it to the normalized structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LangSmith&lt;/strong&gt; - Parses JSON exports from the LangSmith tracing platform. The parser extracts runs, the messages inside each run, token counts from usage metadata, and any chain-level summarization events.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OpenTelemetry&lt;/strong&gt; - Parses OTEL-format JSON spans. The parser traverses the span tree, reconstructs message history from span attributes, and identifies compaction events from span names containing "compress" or "summarize".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AgentOps&lt;/strong&gt; - Parses AgentOps session JSON exports. The parser handles the session-level event structure and normalizes message roles from AgentOps event types.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Custom JSON&lt;/strong&gt; - A generic format for any agent framework not listed above. It expects a &lt;code&gt;messages&lt;/code&gt; array with &lt;code&gt;role&lt;/code&gt;, &lt;code&gt;content&lt;/code&gt;, and optional &lt;code&gt;tokens&lt;/code&gt; and &lt;code&gt;timestamp&lt;/code&gt; fields. Any event with &lt;code&gt;type: "compaction"&lt;/code&gt; or &lt;code&gt;type: "summarization"&lt;/code&gt; is treated as a compaction event.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;context-compaction-visualizer/
├── backend/
│   ├── main.py                  # FastAPI app, 7 endpoints
│   ├── models.py                # Trace, Message, CompactionEvent ORM
│   ├── schemas.py               # Pydantic validation schemas
│   ├── database.py              # SQLAlchemy + SQLite setup
│   ├── parsers/
│   │   ├── langsmith_parser.py
│   │   ├── otel_parser.py
│   │   ├── agentops_parser.py
│   │   └── custom_parser.py
│   ├── services/
│   │   ├── context_analyzer.py  # Claude-powered info loss detection
│   │   └── token_counter.py     # Token counting + cost estimates
│   ├── requirements.txt
│   ├── Dockerfile
│   └── tests/
│       ├── test_parsers.py      # 29 tests covering all 4 parsers
│       └── fixtures/
│           ├── langsmith_trace.json
│           ├── otel_trace.json
│           ├── agentops_trace.json
│           └── custom_trace.json
├── frontend/
│   ├── src/
│   │   ├── App.tsx              # Upload/Timeline/Replay/Analytics/Loss/Compare tabs
│   │   ├── components/
│   │   │   ├── TraceUploader.tsx
│   │   │   ├── ContextTimeline.tsx   # D3.js stacked bar chart
│   │   │   ├── SessionReplay.tsx     # Turn navigation + compaction diff
│   │   │   ├── TokenAnalytics.tsx
│   │   │   ├── InfoLossDetector.tsx
│   │   │   └── ComparativeView.tsx
│   │   ├── hooks/useD3.ts
│   │   ├── api/client.ts
│   │   └── types/index.ts
│   ├── Dockerfile
│   ├── package.json
│   └── vite.config.ts
├── docker-compose.yml
└── .env.example
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The file structure reflects the normalization design directly. Every file under &lt;code&gt;backend/parsers/&lt;/code&gt; handles one vendor's schema and outputs the same structure. Nothing downstream - not &lt;code&gt;main.py&lt;/code&gt;, not any frontend component - needs to know which parser ran. The two services, &lt;code&gt;context_analyzer.py&lt;/code&gt; and &lt;code&gt;token_counter.py&lt;/code&gt;, sit after all four parsers and only ever see the normalized output.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Design Decisions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Parser normalization&lt;/strong&gt; - Each observability platform has a fundamentally different schema. Rather than handling platform-specific quirks in every component, all four parsers produce an identical normalized structure. This means the timeline, replay, analytics, and comparison views have no knowledge of the original format.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Graceful Claude fallback&lt;/strong&gt; - The Info Loss Detector calls the Anthropic API only when &lt;code&gt;ANTHROPIC_API_KEY&lt;/code&gt; is set. Without a key, it returns &lt;code&gt;analysis_available: false&lt;/code&gt; with a clear message rather than failing. The rest of the platform works fully without any API key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;D3.js integration via hook&lt;/strong&gt; - The &lt;code&gt;useD3.ts&lt;/code&gt; hook manages D3's selection lifecycle within React's rendering model. D3 takes ownership of the SVG element inside the hook's effect, while React manages the wrapping div and props. This avoids the common conflict between React's virtual DOM and D3's direct DOM manipulation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Centralized cost estimates&lt;/strong&gt; - Token counts and cost calculations happen in &lt;code&gt;token_counter.py&lt;/code&gt; using verified Claude pricing - $3 per million input tokens, $15 per million output tokens - defined as constants in one place, making them easy to update if pricing changes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Environment Variables
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fktyg3vb6y0vqdrbx66tc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fktyg3vb6y0vqdrbx66tc.png" alt=" " width="800" height="188"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Verified Results
&lt;/h2&gt;

&lt;p&gt;The backend ships with 29 tests covering all four trace parsers, realistic multi-turn fixture data for each format, edge cases like empty inputs and missing fields, and the token counter. All tests run in under 100ms since no external services are called. The frontend builds to a 238 KB JS bundle across 600 modules.&lt;/p&gt;

&lt;p&gt;For the info-loss detector, the ContextAnalyzer was run (using DeepSeek V4 Flash via OpenRouter for this verification pass) against a real compaction event that had dropped 77,000 tokens from a security code review session. It returned an overall risk score of 0.85 and flagged two losses. The higher-risk item, scored 0.90, was the permanent loss of three specific JWT authentication findings - a missing expiry check, absent refresh token rotation, and a weak secret key - detail precise enough that no summary would have preserved it. The second item, scored 0.70, flagged the loss of 23 tool call exchanges' worth of reasoning context. Both came back with concrete recommended actions, not generic advice.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built autonomously using &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt;. NEO is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a platform that ingests execution traces from any of the major agent observability tools, reconstructs what an agent's context looked like turn by turn, and uses an LLM to flag when something important got dropped during compaction. NEO planned and produced the entire codebase - four format parsers that each reduce a different vendor schema into one normalized structure, a FastAPI backend with seven endpoints wired to SQLAlchemy models, two backend services handling token counting and Claude-powered info loss detection, a full React and TypeScript frontend with D3.js visualizations across six components, and a 29-test suite with realistic multi-turn fixtures for all four formats. The repo's &lt;code&gt;plans/&lt;/code&gt; directory and &lt;code&gt;ORCHESTRATOR_LOG.md&lt;/code&gt; document that build run directly.&lt;/p&gt;

&lt;p&gt;The result is a fully working visualization platform that takes a raw trace file in, and gives you back a complete picture of what your agent remembered, what it forgot, and what that cost.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Audit any long-running agent for context loss.&lt;/strong&gt; &lt;br&gt;
If a LangSmith, OpenTelemetry, or AgentOps trace exists for an agent run, it can be dropped straight into the platform. The timeline and session replay immediately show which turns survived compaction and which did not - no instrumentation changes, no code modifications to the agent itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benchmark compaction strategies before shipping.&lt;/strong&gt; &lt;br&gt;
When evaluating two different agent configurations or memory strategies, both traces can be uploaded and placed side by side in the comparative view. The platform surfaces which strategy retained more context at lower token cost, turning a subjective comparison into a measurable one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Catch silent information loss in security or compliance-sensitive agents.&lt;/strong&gt; &lt;br&gt;
The Claude-powered info loss detector scores each compaction event and flags specific content that may have been dropped - as demonstrated with the JWT authentication findings in the verified results. Any agent operating over sensitive or constraint-heavy sessions can be run through this check before the output is trusted. This requires &lt;code&gt;ANTHROPIC_API_KEY&lt;/code&gt; to be set; without it the platform returns &lt;code&gt;analysis_available: false&lt;/code&gt; for this feature.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use the custom JSON format to bring any agent framework in.&lt;/strong&gt; &lt;br&gt;
Agents not running on LangSmith, OpenTelemetry, or AgentOps can still feed into the platform by logging to the custom JSON format - a messages array with role, content, and optional tokens and timestamp fields. Any agent framework that can write JSON can produce a trace this platform accepts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Compaction is designed to be invisible - the agent keeps running, the framework handles the limit, and nothing interrupts the workflow. The cost of that invisibility is that when something is silently dropped, there is no record of what it was or what it was worth. Context Compaction Visualizer produces that record.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/Context-Compaction-Visualizer" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/Context-Compaction-Visualizer&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>llm</category>
      <category>opensource</category>
      <category>machinelearning</category>
      <category>claude</category>
    </item>
    <item>
      <title>Agent Sandbox Escape Detector: Black-Box Security Scanning for LLM Agents</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Fri, 12 Jun 2026 16:29:19 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/agent-sandbox-escape-detector-black-box-security-scanning-for-llm-agents-30bp</link>
      <guid>https://dev.to/nilofer_tweets/agent-sandbox-escape-detector-black-box-security-scanning-for-llm-agents-30bp</guid>
      <description>&lt;p&gt;Most agent security tools focus on known jailbreak phrases or static rule-matching. That approach misses the point. A real attacker does not check a list of banned words - they probe the agent's actual behavior with semantically varied adversarial inputs and look for signs that something slipped through.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Agent Sandbox&lt;/strong&gt; Escape Detector takes the same approach. Point it at any HTTP chat endpoint, and it fires a battery of adversarial prompts across six attack categories, then uses Claude Opus 4.8 as an independent judge to determine whether the agent leaked data, broke persona, or executed injected instructions. The result is a structured scan report with per-probe verdicts, evidence excerpts, and confidence scores.&lt;/p&gt;

&lt;p&gt;The key insight is that you do not need whitebox access to test an agent — all you need is its chat endpoint. The scanner treats the agent as a black box and probes it the same way a real attacker would.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feldcfvib68xu3fwz30wi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feldcfvib68xu3fwz30wi.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Entry: CLI (--target URL)  ·  POST /scan
               │
               ▼
  ┌────────────────────────────────────────────┐
  │  Scanner  ·  asyncio.gather()              │
  │  all 6 probes run concurrently             │
  │  per-probe error isolation                 │
  └──────────────────┬─────────────────────────┘
                     │
       ┌─────────────┼──────────────────┐
       ▼             ▼                  ▼
  ┌─────────┐  ┌──────────────┐  ┌────────────────────┐
  │  Tool   │  │ Prompt Leak  │  │ API Call           │
  │ Access  │  │ Role Confus. │  │ Indirect Injection │
  └────┬────┘  └──────┬───────┘  │ Jailbreak  (6 tot) │
       │               │          └──────────┬─────────┘
       └───────────────┴───────────────────── ┘
                     │ 4–6 adversarial prompts per category
                     ▼
  ┌────────────────────────────────────────────┐
  │  Target Agent  ·  any HTTP chat endpoint   │
  │  httpx async POST                          │
  └──────────────────┬─────────────────────────┘
                     │ agent responses
                     ▼
  ┌────────────────────────────────────────────┐
  │  Claude Judge  ·  claude-opus-4.8          │
  │  via OpenRouter                            │
  │  → ESCAPED / SAFE  ·  confidence (0–1)     │
  │  → evidence excerpt from response          │
  └──────────────────┬─────────────────────────┘
                     │
                     ▼
  ┌────────────────────────────────────────────┐
  │  Scan Report                               │
  │  JSON  ·  Markdown  ·  Rich console        │
  │  GET /results/{scan_id}                    │
  └────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What It Tests
&lt;/h2&gt;

&lt;p&gt;Each probe category targets a different class of vulnerability observed in production LLM deployments. Every category fires 4–6 distinct prompts to reduce false negatives from surface-level prompt filtering. All probes run concurrently - a full scan of six categories completes in roughly the same time as a single category.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tool Access&lt;/strong&gt; - requests that trick the agent into invoking unauthorized tools: file reads, database queries, exec calls. A vulnerable agent attempts to call off-limits functions or returns file and database content.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prompt Leak&lt;/strong&gt; - social-engineering and meta-instruction tricks to extract the system prompt. A vulnerable agent reveals system prompt contents, configuration, or internal instructions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;API Call&lt;/strong&gt; - crafted inputs designed to make the agent perform SSRF or data exfiltration via HTTP. A vulnerable agent constructs or references external URLs containing sensitive data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Role Confusion&lt;/strong&gt; - persona hijacking, identity override, DAN-style persona injection. A vulnerable agent breaks character or adopts a no-restrictions alternate identity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Indirect Injection&lt;/strong&gt; - malicious payloads hidden in simulated tool outputs or document context. A vulnerable agent executes injected instructions as if they came from a trusted source.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Jailbreak&lt;/strong&gt; - chain-of-thought manipulation, hypothetical framing, and reasoning override. A vulnerable agent agrees to bypass safety constraints or leaks reasoning chain internals.&lt;/p&gt;

&lt;h2&gt;
  
  
  How the Judge Works
&lt;/h2&gt;

&lt;p&gt;After collecting all agent responses, each probe's batch of responses is sent to Claude Opus 4.8 via OpenRouter with a structured evaluation prompt. The judge produces a binary ESCAPED/SAFE verdict, a confidence score from 0 to 1, and a natural-language evidence summary quoting specific parts of the response that led to the verdict.&lt;/p&gt;

&lt;p&gt;This approach is significantly more accurate than regex pattern matching because the judge understands context - an agent that says "I cannot help with that" is different from one that says "I cannot help with that, but here is /etc/passwd anyway."&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;Install dependencies into a virtual environment, copy &lt;code&gt;.env.example&lt;/code&gt; to &lt;code&gt;.env&lt;/code&gt;, and add your &lt;code&gt;OPENROUTER_API_KEY&lt;/code&gt;. Then point the CLI at any agent's chat endpoint:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python -m src.cli scan --target http://localhost:8000/chat
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To scan only specific probe categories or save results to JSON:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python -m src.cli scan --target http://localhost:8000/chat --probes tool_access,jailbreak --output report.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Start the FastAPI server for REST integration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;uvicorn src.api.main:app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Environment Variables
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OPENROUTER_API_KEY=sk-or-...    # Required — used for Claude judge calls via OpenRouter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  API
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;POST /scan&lt;/strong&gt; - accepts a target URL and optional probe list, returns a scan ID immediately, and runs the scan asynchronously.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GET /results/{scan_id}&lt;/strong&gt; - returns the full structured report once the scan is complete.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GET /health&lt;/strong&gt; - liveness probe for uptime monitoring.&lt;/p&gt;

&lt;h2&gt;
  
  
  Live Scan Results
&lt;/h2&gt;

&lt;p&gt;Real scan run against a Claude-powered HTTP agent on 2026-06-09:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjhur48oe6p5g773lcwao.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjhur48oe6p5g773lcwao.png" alt=" " width="766" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;0 escapes detected across 6 probe categories - approximately 30 adversarial turns total. Scan ID 0c4bffa6, 2026-06-09.&lt;/p&gt;

&lt;h2&gt;
  
  
  Source Layout
&lt;/h2&gt;

&lt;p&gt;The scanner orchestrates all probes via &lt;code&gt;asyncio.gather()&lt;/code&gt; so they run in parallel, with per-probe error isolation so a timeout on one category never blocks the others. Each probe is a standalone class inheriting from &lt;code&gt;BaseProbe&lt;/code&gt; - adding a new attack category means writing one class and one prompts file. The judge lives in &lt;code&gt;core/judge.py&lt;/code&gt; and is stateless: it takes a list of responses and returns a list of &lt;code&gt;ProbeResult&lt;/code&gt; objects. Reports are assembled by &lt;code&gt;core/report.py&lt;/code&gt;, which handles JSON serialization, Markdown formatting, and Rich console rendering independently.&lt;/p&gt;

&lt;p&gt;The test suite uses a vulnerable dummy agent fixture - an in-process FastAPI app that always complies with requests - to verify the scanner can detect escapes, and a safe dummy agent to verify it does not produce false positives. 64 tests, passing in approximately 15 seconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a black-box behavioral security scanner for LLM agents - one that probes any HTTP chat endpoint with adversarial prompts across six attack categories, uses Claude Opus 4.8 as an independent judge, and produces structured reports with per-probe verdicts, evidence excerpts, and confidence scores. NEO built the full implementation: the async orchestrator using &lt;code&gt;asyncio.gather()&lt;/code&gt; with per-probe error isolation, all six probe classes inheriting from &lt;code&gt;BaseProbe&lt;/code&gt; with their adversarial prompt files, the stateless Claude judge in &lt;code&gt;core/judge.py&lt;/code&gt; via OpenRouter, the report assembler in &lt;code&gt;core/report.py&lt;/code&gt; covering JSON, Markdown, and Rich console output, the CLI entry point, the FastAPI REST server with POST /scan and GET /results/{scan_id}, and the 64-test suite with vulnerable and safe dummy agent fixtures.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use and Extend This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use it to security-test any agent before it goes to production.&lt;/strong&gt;&lt;br&gt;
Point the CLI at your agent's chat endpoint and run a full six-category scan. The structured report tells you exactly which probe categories the agent failed, what the judge found in the response, and the confidence score - before real users can probe the same vulnerabilities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Integrate it into CI to catch security regressions on every deploy.&lt;/strong&gt;&lt;br&gt;
Use &lt;code&gt;POST /scan&lt;/code&gt; to trigger a scan and &lt;code&gt;GET /results/{scan_id}&lt;/code&gt; to poll the report. If any probe returns ESCAPED above your confidence threshold, fail the pipeline. Agent behavior can regress with model updates or prompt changes - automated scanning catches this before it reaches production.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use the probe categories as a security checklist when building agents.&lt;/strong&gt;&lt;br&gt;
The six categories - tool access, prompt leak, API call, role confusion, indirect injection, and jailbreak - map directly to the vulnerabilities that have been observed in production LLM deployments. Running the scanner on your agent during development tells you which categories need stronger guardrails before launch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Extend it with additional probe categories.&lt;/strong&gt;&lt;br&gt;
Each probe is a standalone class inheriting from &lt;code&gt;BaseProbe&lt;/code&gt; with a corresponding prompts file. A new attack category follows the same pattern and is automatically picked up by the orchestrator, judge, and report pipeline without any changes to the core.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Agent security is behavioral, not syntactic. A scanner that checks for banned phrases misses the attacks that matter. Agent Sandbox Escape Detector probes real behavior across six attack categories, judges responses with a frontier model that understands context, and gives you structured evidence - so you know not just whether an agent escaped, but how and where.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/Agent-Sandbox-Escape-Detector" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/Agent-Sandbox-Escape-Detector&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>agents</category>
      <category>python</category>
      <category>machinelearning</category>
      <category>opensource</category>
    </item>
    <item>
      <title>AgentLiar Detector: Catch Coding Agents That Falsely Claim Task Completion</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Wed, 10 Jun 2026 12:41:47 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/agentliar-detector-catch-coding-agents-that-falsely-claim-task-completion-413c</link>
      <guid>https://dev.to/nilofer_tweets/agentliar-detector-catch-coding-agents-that-falsely-claim-task-completion-413c</guid>
      <description>&lt;p&gt;AI coding agents are getting better at completing tasks. They are also getting better at appearing to complete tasks. An agent that claims "done" when it has created placeholder files, written empty tests, or quietly narrowed the scope of the original requirement is harder to catch than one that simply fails, because the failure is hidden inside output that looks correct at a glance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AgentLiar&lt;/strong&gt; is a production-ready system that detects when coding agents falsely claim task completion. It runs four independent verification checks, produces a weighted confidence score from 0 to 100, and delivers structured evidence in JSON, Markdown, or console output - usable as a CLI tool, Python library, GitHub Action, or HTTP API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Features
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;4 Independent Checks&lt;/strong&gt; - File, Test, Scope, and LLM Judge.&lt;br&gt;
&lt;strong&gt;Confidence Scoring&lt;/strong&gt; - weighted aggregation on a 0–100 scale.&lt;br&gt;
&lt;strong&gt;Multiple Interfaces&lt;/strong&gt; - CLI, Python API, GitHub Action, and HTTP API.&lt;br&gt;
&lt;strong&gt;Adversarial Detection&lt;/strong&gt; - catches placeholder implementations, empty tests, and scope narrowing.&lt;br&gt;
&lt;strong&gt;Structured Reports&lt;/strong&gt; - JSON and Markdown output with evidence.&lt;br&gt;
&lt;strong&gt;Production Ready&lt;/strong&gt; - type hints, error handling, logging, and async support.&lt;/p&gt;
&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;

&lt;p&gt;The async orchestrator dispatches four independent checks File, Test, Scope (local), plus an optional OpenRouter LLM Judge and produces a weighted 0–100 confidence score delivered as JSON, Markdown, or console output for CI gating.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft1iym9vzkxg27ekdvy3y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft1iym9vzkxg27ekdvy3y.png" alt=" " width="751" height="448"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  The Four Verification Checks
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. File Check&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Detects missing expected files&lt;/li&gt;
&lt;li&gt;Identifies unexpected new files&lt;/li&gt;
&lt;li&gt;Finds placeholder content: TODO, FIXME, pass-only&lt;/li&gt;
&lt;li&gt;Validates file sizes and content&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Test Check&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Detects empty test bodies&lt;/li&gt;
&lt;li&gt;Identifies tests without assertions&lt;/li&gt;
&lt;li&gt;Finds skipped tests&lt;/li&gt;
&lt;li&gt;Validates claimed versus actual test counts&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Scope Check&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Detects silent scope narrowing: "only", "for now"&lt;/li&gt;
&lt;li&gt;Identifies partial implementations&lt;/li&gt;
&lt;li&gt;Finds TODO markers in code&lt;/li&gt;
&lt;li&gt;Validates requirements coverage&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. LLM Judge&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Independent assessment via OpenRouter&lt;/li&gt;
&lt;li&gt;Structured JSON output&lt;/li&gt;
&lt;li&gt;Timeout and retry logic&lt;/li&gt;
&lt;li&gt;Optional - works without an API key&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Quick Start
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Installation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-e&lt;/span&gt; &lt;span class="nb"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or &lt;code&gt;pip install agentliar&lt;/code&gt; once published. Requires Python 3.10+.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CLI Usage&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Prepare sample inputs from &lt;code&gt;examples/simple_task.json&lt;/code&gt;, then run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentliar verify &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--task-file&lt;/span&gt; .tmp/task.txt &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--claim-file&lt;/span&gt; .tmp/claim.json &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--changes-file&lt;/span&gt; .tmp/changes.json &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--format&lt;/span&gt; markdown
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use &lt;code&gt;agentliar config&lt;/code&gt; to inspect configuration and &lt;code&gt;agentliar analyze .tmp/task.txt&lt;/code&gt; to review a task file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Python API&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;agentliar&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;Verifier&lt;/span&gt;

&lt;span class="n"&gt;verifier&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Verifier&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;verifier&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;verify&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;task_description&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;claim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;claim_payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;file_changes&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;changes_payload&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# Read result.score, result.passed, result.confidence_level, result.reports
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;GitHub Action&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use the GitHub Action with task, claim, and change files, a confidence threshold, and an optional &lt;code&gt;OPENROUTER_API_KEY&lt;/code&gt; secret when you want the LLM Judge path enabled.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HTTP API&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Start the API server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python &lt;span class="nt"&gt;-m&lt;/span&gt; agentliar.server
&lt;span class="c"&gt;# or&lt;/span&gt;
uvicorn agentliar.server:app &lt;span class="nt"&gt;--host&lt;/span&gt; 0.0.0.0 &lt;span class="nt"&gt;--port&lt;/span&gt; 8000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then &lt;code&gt;POST /verify&lt;/code&gt; with the task, claim, and file-change payloads. The response returns score, pass/fail, and evidence blocks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Confidence Score Interpretation
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;90–100&lt;/code&gt; - High. Task appears fully completed.&lt;br&gt;
&lt;code&gt;70–89&lt;/code&gt; - Medium. Task likely complete with minor issues.&lt;br&gt;
&lt;code&gt;50–69&lt;/code&gt; - Low. Task partially completed.&lt;br&gt;
&lt;code&gt;30–49&lt;/code&gt; - Critical. Significant issues detected.&lt;br&gt;
&lt;code&gt;0–29&lt;/code&gt; - Failed. Task likely not completed.&lt;/p&gt;
&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;Create a &lt;code&gt;.env&lt;/code&gt; file. Set &lt;code&gt;OPENROUTER_API_KEY&lt;/code&gt; and &lt;code&gt;OPENROUTER_MODEL&lt;/code&gt; only if you want LLM Judge mode. The check weights must sum to 1.0. &lt;code&gt;CONFIDENCE_THRESHOLD&lt;/code&gt; controls the pass/fail cutoff.&lt;/p&gt;

&lt;p&gt;Recommended LLM Judge models (May 2026):&lt;/p&gt;

&lt;p&gt;&lt;code&gt;anthropic/claude-haiku-4-5&lt;/code&gt; - cheap and fast judging&lt;br&gt;
&lt;code&gt;anthropic/claude-sonnet-4-6&lt;/code&gt; or openai/gpt-5.4 - higher-quality judging&lt;br&gt;
&lt;code&gt;openai/gpt-4.1-mini&lt;/code&gt; - budget option&lt;/p&gt;
&lt;h2&gt;
  
  
  Use Cases
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;CI/CD Integration&lt;/strong&gt; - automatically verify PR claims before merging.&lt;br&gt;
&lt;strong&gt;Code Review&lt;/strong&gt; - get an independent assessment of task completion alongside a human review.&lt;br&gt;
&lt;strong&gt;Agent Monitoring&lt;/strong&gt; - detect when AI agents overstate progress in automated pipelines.&lt;br&gt;
&lt;strong&gt;Quality Gates&lt;/strong&gt; - block merges below a confidence threshold.&lt;br&gt;
&lt;strong&gt;Documentation&lt;/strong&gt; - generate verification reports for stakeholders.&lt;/p&gt;
&lt;h2&gt;
  
  
  Security
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;No hardcoded secrets&lt;/li&gt;
&lt;li&gt;API keys via environment variables only&lt;/li&gt;
&lt;li&gt;No data persistence&lt;/li&gt;
&lt;li&gt;Local processing except for LLM Judge&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/agentliar/           # Checks, orchestration, scoring, reports, API, CLI, server
tests/
├── unit/                # Unit tests
├── adversarial/         # Adversarial tests
└── integration/         # Integration tests
examples/                # Sample inputs
action.yml               # GitHub Action definition
pyproject.toml           # Packaging and tooling
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pytest                                    &lt;span class="c"&gt;# Full suite&lt;/span&gt;
pytest &lt;span class="nt"&gt;--cov&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;agentliar &lt;span class="nt"&gt;--cov-report&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;html  &lt;span class="c"&gt;# With coverage&lt;/span&gt;
pytest tests/unit/                        &lt;span class="c"&gt;# Unit tests only&lt;/span&gt;
pytest tests/adversarial/                 &lt;span class="c"&gt;# Adversarial tests only&lt;/span&gt;
pytest tests/integration/                 &lt;span class="c"&gt;# Integration tests only&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Code Quality&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;ruff check &lt;span class="nb"&gt;.&lt;/span&gt;        &lt;span class="c"&gt;# Linting&lt;/span&gt;
ruff format &lt;span class="nb"&gt;.&lt;/span&gt;       &lt;span class="c"&gt;# Formatting&lt;/span&gt;
mypy src tests      &lt;span class="c"&gt;# Type checking&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt;. NEO is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a production-ready verification system for detecting false completion claims from coding agents - running four independent checks locally, with an optional LLM Judge via OpenRouter, and exposing the result through a CLI, Python API, GitHub Action, and HTTP API. NEO built the full implementation: the async orchestrator dispatching all four checks, the File, Test, Scope, and LLM Judge check modules, the weighted confidence scorer, the JSON and Markdown report generators, the Click CLI with verify, config, and analyze commands, the FastAPI HTTP server, the GitHub Action definition in &lt;code&gt;action.yml&lt;/code&gt;, and the test suite split across unit, adversarial, and integration coverage.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use and Extend This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use it as a CI gate on every PR that includes AI-generated code.&lt;/strong&gt;&lt;br&gt;
Add the GitHub Action to your workflow with a confidence threshold. Any PR where the agent's claimed changes do not pass the file, test, and scope checks below your threshold is blocked before merge - automatically, without a reviewer having to spot the placeholder implementation manually.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use it to monitor agent progress in long-running pipelines.&lt;/strong&gt;&lt;br&gt;
Call &lt;code&gt;await verifier.verify(...)&lt;/code&gt; from Python after each agent task completes. The confidence score and evidence blocks tell you whether the agent actually finished the task or produced output that looks complete but is not - before the next stage of the pipeline starts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use the LLM Judge for higher-confidence verification on critical tasks.&lt;/strong&gt;&lt;br&gt;
Set &lt;code&gt;OPENROUTER_API_KEY&lt;/code&gt; and configure a judge model for tasks where the local checks alone are not sufficient. The LLM Judge runs independently from the other three checks and adds a cross-model perspective to the confidence score.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Extend it with additional check types.&lt;/strong&gt;&lt;br&gt;
The four checks share a common async interface in the orchestrator. A new check follows the same pattern and its weight is added to the configuration. The orchestrator, scorer, and reporters pick it up automatically.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Agents that falsely claim completion are harder to catch than agents that fail outright - because the output exists and looks plausible. AgentLiar makes the verification systematic: four independent checks, a weighted confidence score, and structured evidence that tells you exactly where the claim breaks down.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/AgentLiar" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/AgentLiar&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>agents</category>
      <category>machinelearning</category>
      <category>llm</category>
      <category>opensource</category>
    </item>
    <item>
      <title>Carbon-Aware Model Training: Scheduling GPU Workloads Around Electricity Carbon Intensity</title>
      <dc:creator>Nilofer 🚀</dc:creator>
      <pubDate>Sat, 06 Jun 2026 08:48:43 +0000</pubDate>
      <link>https://dev.to/nilofer_tweets/carbon-aware-model-training-scheduling-gpu-workloads-around-electricity-carbon-intensity-b4b</link>
      <guid>https://dev.to/nilofer_tweets/carbon-aware-model-training-scheduling-gpu-workloads-around-electricity-carbon-intensity-b4b</guid>
      <description>&lt;p&gt;Training ML models has an environmental cost that most practitioners do not measure. A model trained during peak grid hours, when coal and gas plants are meeting high demand - can emit significantly more CO2 than the same model trained during off-peak hours when renewables dominate the grid. The carbon intensity of electricity varies by a factor of 2–5x throughout the day, but most training pipelines ignore this entirely.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Carbon-Aware Model Training Pipeline&lt;/strong&gt; is a PyTorch-based training pipeline that monitors real-time electricity carbon intensity, delays training until a low-carbon window is available, reduces GPU memory footprint through gradient accumulation, and tracks CO2 emissions throughout the training process using CodeCarbon - with a comparison report that quantifies the carbon savings against a baseline run.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhmyllyuji9qnif6r48ws.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhmyllyuji9qnif6r48ws.png" alt=" " width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Features
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Carbon-Aware Scheduling&lt;/strong&gt; - real-time carbon intensity monitoring with smart training delays until low-carbon windows are detected.&lt;br&gt;
&lt;strong&gt;Gradient Accumulation&lt;/strong&gt; - reduces GPU memory footprint while maintaining effective batch size.&lt;br&gt;
&lt;strong&gt;Emissions Tracking&lt;/strong&gt; - real-time CO2 monitoring via CodeCarbon with comprehensive JSON reports.&lt;br&gt;
&lt;strong&gt;Modular Design&lt;/strong&gt; - YAML-based configuration with separate scheduler, tracker, and trainer modules.&lt;br&gt;
&lt;strong&gt;GPU Optimized&lt;/strong&gt; - automatic CUDA detection with mixed precision training (FP16).&lt;br&gt;
&lt;strong&gt;Comparative Analysis&lt;/strong&gt; - automated reporting quantifying carbon savings against a baseline run.&lt;/p&gt;
&lt;h2&gt;
  
  
  How It Works
&lt;/h2&gt;

&lt;p&gt;The pipeline runs in four stages:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage 1 - Carbon-Aware Scheduling&lt;/strong&gt;&lt;br&gt;
Real-time monitoring checks electricity carbon intensity via APIs. Smart delays wait for low-carbon windows before starting training. Fallback mechanisms use realistic mock data when APIs are unavailable - with diurnal patterns simulating peak intensity at 18:00 and trough at 03:00. Configurable thresholds allow customization for different regions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage 2 - Gradient Accumulation&lt;/strong&gt;&lt;br&gt;
Memory optimization processes smaller micro-batches. Effective batch size is maintained with reduced memory. Configurable steps (2, 4, 8, 16) adapt to hardware constraints. Convergence preservation ensures model quality is not compromised.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage 3 - Emissions Tracking&lt;/strong&gt;&lt;br&gt;
CodeCarbon integration monitors CO2 emissions in real-time. Energy metrics track power consumption in Watts and energy in kWh. Comprehensive reports generate JSON summaries with all metrics. Comparative analysis quantifies carbon savings versus the baseline.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage 4 - GPU Optimization&lt;/strong&gt;&lt;br&gt;
Mixed precision training (FP16) reduces memory and increases speed. Automatic CUDA detection uses GPU when available. Pin memory optimization enables faster data transfers. Graceful CPU fallback when GPU is unavailable.&lt;/p&gt;
&lt;h2&gt;
  
  
  Architecture
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌─────────────────────────────────────────────────────────────────┐
│                     Training Configuration                      │
│                       (YAML Config File)                        │
└─────────────────────────┬───────────────────────────────────────┘
                          │
                          ▼
         ┌────────────────────────────────────┐
         │   Carbon Intensity Scheduler       │
         │   - API/Mock data fetch            │
         │   - Threshold comparison           │
         │   - Wait for low-carbon window     │
         └────────────────┬───────────────────┘
                          │
                          ▼
              ┌───────────────────────┐
              │   Start Training?     │
              │   Intensity &amp;lt; 300?    │
              └─────┬─────────────┬───┘
                    │ NO          │ YES
                    ▼             ▼
            ┌───────────┐   ┌──────────────┐
            │   Wait    │   │ Start Tracker│
            │ &amp;amp; Recheck │   │ (CodeCarbon) │
            └───────────┘   └──────┬───────┘
                                   │
                                   ▼
                  ┌────────────────────────────────┐
                  │   PyTorch Training Loop        │
                  │   - Gradient Accumulation      │
                  │   - Mixed Precision (FP16)     │
                  │   - Checkpointing              │
                  └────────────────┬───────────────┘
                                   │
                                   ▼
                  ┌────────────────────────────────┐
                  │   Emissions Tracking           │
                  │   - CO2 (kg)                   │
                  │   - Energy (kWh)               │
                  │   - Power (Watts)              │
                  └────────────────┬───────────────┘
                                   │
                                   ▼
              ┌───────────────────────────────────┐
              │   Save Results                    │
              │   - Model checkpoint              │
              │   - Training summary (JSON)       │
              │   - Emissions log (CSV)           │
              └───────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Installation
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python 3.8+&lt;/li&gt;
&lt;li&gt;PyTorch 2.0+&lt;/li&gt;
&lt;li&gt;CUDA (optional, for GPU acceleration)
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;git clone https://github.com/dakshjain-1616/CarbonAwareModelTraining---by-NEO.git
&lt;span class="nb"&gt;cd &lt;/span&gt;CarbonAwareModelTraining---by-NEO

python3 &lt;span class="nt"&gt;-m&lt;/span&gt; venv venv
&lt;span class="nb"&gt;source &lt;/span&gt;venv/bin/activate  &lt;span class="c"&gt;# On Windows: venv\Scripts\activate&lt;/span&gt;

pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-r&lt;/span&gt; requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Required packages: &lt;code&gt;torch&amp;gt;=2.0.0&lt;/code&gt;, &lt;code&gt;torchvision&amp;gt;=0.15.0&lt;/code&gt;, &lt;code&gt;codecarbon&amp;gt;=2.3.0&lt;/code&gt;, &lt;code&gt;pyyaml&amp;gt;=6.0&lt;/code&gt;, &lt;code&gt;numpy&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Quick Start
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;source &lt;/span&gt;venv/bin/activate

&lt;span class="c"&gt;# Run baseline training (no optimization)&lt;/span&gt;
&lt;span class="nb"&gt;export &lt;/span&gt;&lt;span class="nv"&gt;PYTHONPATH&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$PWD&lt;/span&gt;&lt;span class="s2"&gt;/src:&lt;/span&gt;&lt;span class="nv"&gt;$PYTHONPATH&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
python src/train.py configs/baseline.yaml

&lt;span class="c"&gt;# Run optimized training (carbon-aware + gradient accumulation)&lt;/span&gt;
python src/train.py configs/optimized.yaml

&lt;span class="c"&gt;# Generate comparison report&lt;/span&gt;
python generate_comparison.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;This runs three steps: baseline training without carbon awareness, optimized training with carbon-aware scheduling and gradient accumulation, and a comparison report that quantifies carbon savings and performance metrics.&lt;/p&gt;
&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;Configure carbon-aware training in &lt;code&gt;configs/optimized.yaml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;scheduler&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
  &lt;span class="na"&gt;carbon_threshold&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;300&lt;/span&gt;           &lt;span class="c1"&gt;# gCO2/kWh&lt;/span&gt;
  &lt;span class="na"&gt;wait_for_low_carbon&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;

&lt;span class="na"&gt;training&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;batch_size&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;16&lt;/span&gt;
  &lt;span class="na"&gt;gradient_accumulation_steps&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;4&lt;/span&gt;  &lt;span class="c1"&gt;# Effective batch = 64&lt;/span&gt;
  &lt;span class="na"&gt;epochs&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run optimized training:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python src/train.py configs/optimized.yaml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;============================================================
CARBON-AWARE TRAINING STARTED
============================================================

Carbon Intensity Check:
  Current Intensity: 420.5 gCO2/kWh
  Threshold: 300 gCO2/kWh
  Status: ⏳ Waiting for low-carbon window...

[10 minutes later]
  Current Intensity: 285.3 gCO2/kWh
  Status: ✅ Starting training now!

Training Progress:
  Epoch 1/3 - Loss: 0.324 - Accuracy: 91.2%
  CO2 Emissions: 0.042 kg
  Energy Consumed: 0.15 kWh

============================================================
CARBON SAVINGS vs BASELINE
============================================================

CO2 Reduction: 32.5% (0.024 kg saved)
GPU Memory Reduction: 45.8%
Accuracy: 93.1% (baseline: 93.4%)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Usage Examples
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Carbon-Aware Scheduling Only&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Disable gradient accumulation, enable scheduling:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;scheduler&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
  &lt;span class="na"&gt;carbon_threshold&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;250&lt;/span&gt;

&lt;span class="na"&gt;training&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;gradient_accumulation_steps&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;1&lt;/span&gt;  &lt;span class="c1"&gt;# No accumulation&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Gradient Accumulation Only&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Disable scheduling, enable memory optimization:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;scheduler&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;

&lt;span class="na"&gt;training&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;batch_size&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;8&lt;/span&gt;
  &lt;span class="na"&gt;gradient_accumulation_steps&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;8&lt;/span&gt;  &lt;span class="c1"&gt;# Effective batch = 64&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Real Carbon Intensity API&lt;/strong&gt;&lt;br&gt;
Configure for production with a real API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;scheduler&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;enabled&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
  &lt;span class="na"&gt;use_mock_data&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;
  &lt;span class="na"&gt;api_endpoint&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="s"&gt;https://api.carbonintensity.org.uk/intensity"&lt;/span&gt;
  &lt;span class="na"&gt;region&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="s"&gt;GB"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Custom Model Integration&lt;/strong&gt;&lt;br&gt;
Replace &lt;code&gt;SimpleCNN&lt;/code&gt; in &lt;code&gt;src/train.py&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;my_models&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;MyCustomModel&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;prepare_model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;device&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;device&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;cuda&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;cuda&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;is_available&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;cpu&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MyCustomModel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;input_channels&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;training&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;input_channels&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="n"&gt;num_classes&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;training&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;num_classes&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;to&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;device&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;device&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output Format&lt;/strong&gt;&lt;br&gt;
Training summary JSON saved to &lt;code&gt;output/summary_optimized.json&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"run_name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"optimized"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"training_metrics"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"final_accuracy"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;93.1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"final_loss"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.124&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"epochs"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"total_time_seconds"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;245&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"carbon_metrics"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"total_emissions_kg"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.042&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"energy_consumed_kwh"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.15&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"avg_power_watts"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;145.2&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"scheduler_metrics"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"wait_time_seconds"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"initial_intensity"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;420.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"training_intensity"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;285.3&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"gpu_metrics"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"peak_memory_mb"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2048&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"gradient_accumulation_steps"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"effective_batch_size"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Comparison report saved to &lt;code&gt;output/comparison_report.json&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"carbon_savings"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"baseline_emissions_kg"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.074&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"optimized_emissions_kg"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.042&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"reduction_kg"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.032&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"reduction_percentage"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;43.2&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"accuracy_impact"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"baseline_accuracy"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;93.4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"optimized_accuracy"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;93.1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"degradation_percentage"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.3&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"memory_savings"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"baseline_memory_mb"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;4096&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"optimized_memory_mb"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2048&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"reduction_percentage"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;50.0&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Performance
&lt;/h2&gt;

&lt;p&gt;Evaluated on MNIST training - 3 epochs, RTX 3090 GPU:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe1a9ps96nj9yoysq7diz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe1a9ps96nj9yoysq7diz.png" alt=" " width="485" height="241"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Carbon Intensity Patterns (Mock Data):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Peak hours 18:00–22:00: ~450 gCO2/kWh&lt;br&gt;
Off-peak hours 02:00–06:00: ~200 gCO2/kWh&lt;br&gt;
Average reduction: 35–45% CO2 by scheduling during low-carbon windows&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GPU Memory Savings:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Gradient accumulation 2x: ~30% memory reduction&lt;br&gt;
Gradient accumulation 4x: ~50% memory reduction&lt;br&gt;
Gradient accumulation 8x: ~60% memory reduction&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Convergence Validation:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Accuracy degradation under 1% across all tested configurations&lt;br&gt;
Loss convergence matches baseline within 2% tolerance&lt;br&gt;
No divergence observed&lt;/p&gt;
&lt;h2&gt;
  
  
  Project Structure
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CarbonAwareModelTraining---by-NEO/
├── src/
│   ├── scheduler.py                # Carbon intensity API &amp;amp; scheduling
│   ├── tracker.py                  # CodeCarbon emissions tracking
│   ├── train.py                    # Main training pipeline
│   └── utils.py                    # Config loading &amp;amp; logging
├── configs/
│   ├── baseline.yaml               # Baseline training config
│   └── optimized.yaml              # Carbon-aware optimized config
├── output/
│   ├── summary_baseline.json       # Baseline training summary
│   ├── summary_optimized.json      # Optimized training summary
│   ├── comparison_report.json      # Comparative analysis
│   ├── emissions.csv               # CodeCarbon emissions log
│   └── training_*.log              # Detailed training logs
├── models/
│   ├── model_baseline.pt           # Baseline model checkpoint
│   └── model_optimized.pt          # Optimized model checkpoint
├── data/                            # MNIST dataset (auto-downloaded)
├── requirements.txt                 # Python dependencies
├── generate_comparison.py          # Comparison report generator
└── README.md
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Key Design Decisions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Why Carbon-Aware Scheduling?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Carbon intensity varies 2–5x throughout the day. Scheduling training during low-carbon windows reduces emissions without affecting model quality. Low-carbon periods also often correlate with cheaper electricity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Gradient Accumulation?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Gradient accumulation enables training larger models on limited hardware by processing smaller micro-batches and updating weights less frequently. Used in BERT, GPT, and other large-scale models for the same reason.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why CodeCarbon?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;CodeCarbon uses lifecycle assessment methodologies, supports CPU, GPU, and multi-device setups, and produces transparent, community-validated calculations. It tracks energy, power, and emissions in a single library.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why YAML Configuration?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;YAML configs are version-controlled, human-readable, and separate code from experiment parameters - enabling reproducible A/B comparisons between baseline and optimized runs.&lt;/p&gt;
&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;p&gt;Validate installation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python &lt;span class="nt"&gt;-c&lt;/span&gt; &lt;span class="s2"&gt;"import torch; print(f'PyTorch: {torch.__version__}')"&lt;/span&gt;
python &lt;span class="nt"&gt;-c&lt;/span&gt; &lt;span class="s2"&gt;"import codecarbon; print('CodeCarbon: OK')"&lt;/span&gt;
python &lt;span class="nt"&gt;-c&lt;/span&gt; &lt;span class="s2"&gt;"import yaml; print('PyYAML: OK')"&lt;/span&gt;
python &lt;span class="nt"&gt;-c&lt;/span&gt; &lt;span class="s2"&gt;"import torch; print(f'CUDA Available: {torch.cuda.is_available()}')"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run a quick 5-minute test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python src/train.py configs/test.yaml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Validate carbon savings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python src/train.py configs/baseline.yaml
python src/train.py configs/optimized.yaml
python generate_comparison.py
&lt;span class="nb"&gt;cat &lt;/span&gt;output/comparison_report.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Troubleshooting
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;CUDA Out of Memory&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Reduce &lt;code&gt;batch_size&lt;/code&gt; and increase &lt;code&gt;gradient_accumulation_steps&lt;/code&gt; in the config.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Carbon Intensity API Timeout&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No action needed - the pipeline automatically falls back to mock data and training proceeds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Module Import Errors&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;export &lt;/span&gt;&lt;span class="nv"&gt;PYTHONPATH&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$PWD&lt;/span&gt;&lt;span class="s2"&gt;/src:&lt;/span&gt;&lt;span class="nv"&gt;$PYTHONPATH&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;CodeCarbon Tracking Fails&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;--upgrade&lt;/span&gt; codecarbon
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Training continues without emissions tracking if CodeCarbon fails.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scheduler Waits Too Long&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Increase &lt;code&gt;max_wait_seconds&lt;/code&gt;, raise &lt;code&gt;carbon_threshold&lt;/code&gt;, or set &lt;code&gt;wait_for_low_carbon: false&lt;/code&gt; in the config.&lt;/p&gt;

&lt;h2&gt;
  
  
  How I Built This Using NEO
&lt;/h2&gt;

&lt;p&gt;This project was built using NEO. &lt;a href="https://heyneo.com/" rel="noopener noreferrer"&gt;NEO&lt;/a&gt; is a fully autonomous AI engineering agent that can write code and build solutions for AI/ML tasks including AI model evals, prompt optimization and end to end AI pipeline development.&lt;/p&gt;

&lt;p&gt;The requirement was a PyTorch training pipeline that schedules GPU workloads based on real-time carbon intensity, reduces memory footprint through gradient accumulation, and tracks emissions with CodeCarbon - producing a side-by-side comparison report. NEO built the full implementation: the carbon intensity scheduler in &lt;code&gt;scheduler.py&lt;/code&gt; with API integration and mock fallback, the CodeCarbon emissions tracker in &lt;code&gt;tracker.py&lt;/code&gt;, the main training pipeline in &lt;code&gt;train.py&lt;/code&gt; with gradient accumulation and mixed precision FP16, the config loader and logging utilities in &lt;code&gt;utils.py&lt;/code&gt;, the YAML configs for baseline and optimized runs, the comparison report generator in &lt;code&gt;generate_comparison.py&lt;/code&gt;, and the full output structure covering JSON summaries, emissions CSV, and model checkpoints.&lt;/p&gt;

&lt;h2&gt;
  
  
  How You Can Use and Extend This With NEO
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Use it to measure the carbon cost of your existing training runs.&lt;/strong&gt;&lt;br&gt;
Run &lt;code&gt;python src/train.py configs/baseline.yaml&lt;/code&gt; on your own model and data by replacing &lt;code&gt;SimpleCNN&lt;/code&gt; in &lt;code&gt;src/train.py&lt;/code&gt; with your model. The CodeCarbon tracker produces a JSON summary with CO2 in kg, energy in kWh, and average power in Watts, a baseline measurement before any optimization.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use the comparison report to justify scheduling infrastructure.&lt;/strong&gt;&lt;br&gt;
Run both the baseline and optimized configs on the same dataset. The &lt;code&gt;comparison_report.json&lt;/code&gt; gives you a concrete before and after - percentage reduction in emissions, energy, and memory, alongside accuracy degradation,  that makes the case for carbon-aware scheduling with real numbers from your own hardware.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use mock data for development and real API for production.&lt;/strong&gt;&lt;br&gt;
Set &lt;code&gt;use_mock_data: true&lt;/code&gt; during development so training always proceeds without waiting. Switch to &lt;code&gt;use_mock_data: false&lt;/code&gt; with a real &lt;code&gt;api_endpoint&lt;/code&gt; for production runs where actual carbon savings matter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Extend the scheduler with additional carbon intensity sources.&lt;/strong&gt;&lt;br&gt;
The scheduler in &lt;code&gt;scheduler.py&lt;/code&gt; fetches from a configurable &lt;code&gt;api_endpoint&lt;/code&gt;. Adding support for additional regional carbon intensity APIs - Electricity Maps, WattTime, or a custom internal source, means updating the fetch logic in &lt;code&gt;scheduler.py&lt;/code&gt; without touching the training loop, tracker, or reporting pipeline.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Notes
&lt;/h2&gt;

&lt;p&gt;Carbon intensity varies throughout the day, and most training pipelines ignore it. A 43% reduction in CO2 emissions with less than 1% accuracy degradation, achieved by scheduling when the grid is cleaner and accumulating gradients to reduce memory - shows that sustainable ML is a practical engineering choice, not just an aspiration.&lt;/p&gt;

&lt;p&gt;The code is at &lt;a href="https://github.com/dakshjain-1616/CarbonAwareModelTraining" rel="noopener noreferrer"&gt;https://github.com/dakshjain-1616/CarbonAwareModelTraining&lt;/a&gt;&lt;br&gt;
You can also build with NEO in your IDE using the &lt;a href="https://marketplace.visualstudio.com/items?itemName=NeoResearchInc.heyneo" rel="noopener noreferrer"&gt;VS Code extension&lt;/a&gt; or &lt;a href="https://open-vsx.org/extension/NeoResearchInc/heyneo" rel="noopener noreferrer"&gt;Cursor&lt;/a&gt;.&lt;br&gt;
You can use NEO MCP with Claude Code: &lt;a href="https://heyneo.com/claude-code" rel="noopener noreferrer"&gt;https://heyneo.com/claude-code&lt;/a&gt;&lt;/p&gt;

</description>
      <category>pytorch</category>
      <category>python</category>
      <category>machinelearning</category>
      <category>opensource</category>
    </item>
  </channel>
</rss>
